{"nl": {"description": "Levko has an array that consists of integers: a1,\u2009a2,\u2009... ,\u2009an. But he doesn\u2019t like this array at all.Levko thinks that the beauty of the array a directly depends on value c(a), which can be calculated by the formula: The less value c(a) is, the more beautiful the array is.It\u2019s time to change the world and Levko is going to change his array for the better. To be exact, Levko wants to change the values of at most k array elements (it is allowed to replace the values by any integers). Of course, the changes should make the array as beautiful as possible.Help Levko and calculate what minimum number c(a) he can reach.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20092000). The second line contains space-separated integers a1,\u2009a2,\u2009... ,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "A single number \u2014 the minimum value of c(a) Levko can get.", "sample_inputs": ["5 2\n4 7 4 7 4", "3 1\n-100 0 100", "6 3\n1 2 3 7 8 9"], "sample_outputs": ["0", "100", "1"], "notes": "NoteIn the first sample Levko can change the second and fourth elements and get array: 4, 4, 4, 4, 4.In the third sample he can get array: 1, 2, 3, 4, 5, 6."}, "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 def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }\n\n val Array(n, k) = readInts(2)\n val as = readLongs(n)\n\n def can(c: Long): Boolean = {\n val dp = Array.tabulate(n)(identity)\n for (i <- 1 until n) {\n for (\n j <- 0 until i;\n if math.abs(as(i) - as(j)) <= (i - j) * c\n ) dp(i) = math.min(dp(i), dp(j) + i - j - 1)\n if (dp(i) + n - i - 1 <= k) return true\n }\n false\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 if (n == 1) println(0)\n else println(binSearch(0, 2000000001))\n}"}], "negative_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 Array(n, k) = readInts(2)\n val as = readInts(n)\n\n def can(c: Int): Boolean = {\n val dp = Array.tabulate(n)(identity)\n for (i <- 1 until n) {\n for (\n j <- 0 until i;\n if math.abs(as(i) - as(j)) <= (i - j) * c\n ) dp(i) = math.min(dp(i), dp(j) + i - j - 1)\n if (dp(i) + n - i - 1 <= k) return true\n }\n false\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\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 if (n == 1) println(0)\n else println(binSearch(0, 2000000001))\n}"}], "src_uid": "544dd0c7274ac337744b8ba0996add1d"} {"nl": {"description": "Salem gave you $$$n$$$ sticks with integer positive lengths $$$a_1, a_2, \\ldots, a_n$$$.For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $$$a$$$ to $$$b$$$ is $$$|a - b|$$$, where $$$|x|$$$ means the absolute value of $$$x$$$.A stick length $$$a_i$$$ is called almost good for some integer $$$t$$$ if $$$|a_i - t| \\le 1$$$.Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $$$t$$$ and the total cost of changing is minimum possible. The value of $$$t$$$ is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of $$$t$$$ and the minimum cost. If there are multiple optimal choices for $$$t$$$, print any of them.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the number of sticks. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 100$$$)\u00a0\u2014 the lengths of the sticks.", "output_spec": "Print the value of $$$t$$$ and the minimum possible cost. If there are multiple optimal choices for $$$t$$$, print any of them.", "sample_inputs": ["3\n10 1 4", "5\n1 1 2 2 3"], "sample_outputs": ["3 7", "2 0"], "notes": "NoteIn the first example, we can change $$$1$$$ into $$$2$$$ and $$$10$$$ into $$$4$$$ with cost $$$|1 - 2| + |10 - 4| = 1 + 6 = 7$$$ and the resulting lengths $$$[2, 4, 4]$$$ are almost good for $$$t = 3$$$.In the second example, the sticks lengths are already almost good for $$$t = 2$$$, so we don't have to do anything."}, "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 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}"}, {"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"} {"nl": {"description": "Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has an array consisting of n numbers. He wants to perform m operations of two types: add l r d \u2014 add an integer d to all elements whose indexes belong to the interval from l to r, inclusive (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009104); count l r \u2014 find and print on the screen how many lucky numbers there are among elements with indexes that belong to the interval from l to r inclusive (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n). Each lucky number should be counted as many times as it appears in the interval. Petya has a list of all operations. The operations are such that after all additions the array won't have numbers that would exceed 104. Help Petya write a program that would perform these operations.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of numbers in the array and the number of operations correspondingly. The second line contains n positive integers, none of which exceeds 104 \u2014 those are the array numbers. Next m lines contain operations, one per line. They correspond to the description given in the statement. It is guaranteed that after all operations are fulfilled each number in the array will not exceed 104.", "output_spec": "For each operation of the second type print the single number on the single line \u2014 the number of lucky numbers in the corresponding interval.", "sample_inputs": ["3 6\n2 3 4\ncount 1 3\ncount 1 2\nadd 1 3 2\ncount 1 3\nadd 2 3 3\ncount 1 3", "4 5\n4 4 4 4\ncount 1 4\nadd 1 4 3\ncount 1 4\nadd 2 3 40\ncount 1 4"], "sample_outputs": ["1\n0\n1\n1", "4\n4\n4"], "notes": "NoteIn the first sample after the first addition the array will look in the following manner:4 5 6After the second addition:4 8 9The second sample after the first addition:7 7 7 7After the second addition:7 47 47 7"}, "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.collection.immutable\nimport scala.collection.Searching._\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 C091E(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 C091E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import fScanner._\n import Main._\n\n def solve(): Unit = {\n val n = ni()\n val m = ni()\n\n val a = na(n)\n\n val luckys: immutable.IndexedSeq[Int] = (1 to 10000).filter(isLucky)\n// out.println(isLucky(4))\n val t = new SegmentTree(n, a, luckys)\n t.build(1)\n REP(m) { _ =>\n ns() match {\n case \"count\" =>\n t.print()\n out.println(t.get(1, l = ni() - 1, r = ni() - 1))\n case \"add\" =>\n t.update(1, l = ni() -1, r= ni() -1, nVal = ni())\n }\n }\n }\n\n def isLucky(u: Int): Boolean = {\n var x = u\n while (x > 0) {\n val y = x % 10\n if(y != 4 && y != 7) return false\n x = x / 10\n }\n true\n }\n\n private class SegmentTree(n: Int, a: Array[Int], luckys: IndexedSeq[Int]) {\n val tree: Array[Int] = Array.ofDim[Int](4 * n)\n val min: Array[Int] = Array.ofDim[Int](4 * n)\n\n val laz: Array[Int] = Array.fill[Int](4 * n)(0)\n\n def print() = {\n// println(laz.length)\n }\n\n def combine(u: Int, c1: Int, c2: Int): Unit = {\n tree(u) = tree(c1) + tree(c2)\n min(u) = Math.min(min(c1), min(c2))\n }\n\n def push(u: Int) = {\n laz(u << 1) += laz(u)\n min(u << 1) -= laz(u)\n laz(u << 1 | 1) += laz(u)\n min(u << 1 | 1) -= laz(u)\n laz(u) = 0\n }\n\n def build(v: Int, tl: Int = 0, tr: Int = n-1): Unit = {\n if(tl == tr) {\n val iP = luckys.search(a(tl))\n if(iP.insertionPoint == luckys.length) {\n tree(v) = 0\n min(v) = Int.MaxValue\n } else {\n min(v) = luckys(iP.insertionPoint) - a(tl)\n tree(v) = if(min(v) == 0) 1 else 0\n }\n } else {\n val tm = tl + (tr - tl) / 2\n build(v << 1, tl, tm)\n build(v << 1 | 1, tm+1, tr)\n combine(v, v << 1, v << 1 | 1)\n }\n }\n\n def update(v: Int, tl: Int = 0, tr: Int = n-1, l: Int, r: Int, nVal: Int): Unit = {\n if(l > r) {}\n else if(l == tl && r == tr && min(v) > nVal) {\n min(v) -= nVal\n laz(v) += nVal\n } else if(tl == tr) {\n a(tl) += laz(v) + nVal\n laz(v) = 0\n val iP = luckys.search(a(tl))\n if(iP.insertionPoint == luckys.length) {\n tree(v) = 0\n min(v) = Int.MaxValue\n } else {\n min(v) = luckys(iP.insertionPoint) - a(tl)\n tree(v) = if(min(v) == 0) 1 else 0\n }\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n update(v << 1, tl, tm, l, Math.min(r, tm), nVal)\n update(v << 1 | 1, tm + 1, tr, Math.max(l, tm + 1), r, nVal)\n combine(v, v << 1, v << 1 | 1)\n }\n }\n\n def get(v: Int, tl: Int = 0, tr: Int = n-1, l: Int, r: Int): Int = {\n if(l > r) 0\n else if(l == tl && r == tr) tree(v)\n else {\n val tm = tl + (tr - tl) / 2\n 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": [{"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 C091E(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 C091E(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 val a = na(n)\n val t = new SegmentTree(n, a)\n t.build(1, 0, n-1)\n REP(m) { _ =>\n ns() match {\n case \"count\" =>\n out.println(t.get(1, 0, n-1, ni()-1, ni()-1).count)\n t.print()\n case \"add\" =>\n t.update(1, 0, n-1, ni()-1, ni()-1, ni())\n t.print()\n }\n }\n }\n\n case class Node(count: Int, add: Int, marked: Boolean)\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val tree: Array[Node] = Array.ofDim[Node](4 * n)\n\n private def isLucky(u: Int): Int = {\n var v = u\n var countI = 0\n var countT = 0\n while (v > 0) {\n val g = v % 10\n if(g == 4 || g == 7) countI += 1\n v = v / 10\n countT += 1;\n }\n if(countI == countT) 1 else 0\n }\n\n def print(): Unit = {\n// a.foreach(out.println)\n }\n\n private def combine(x: Node, y: Node): Node = {\n Node(x.count + y.count, 0, x.marked || y.marked)\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n tree(v) = Node(isLucky(a(tl)), 0, false)\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 push(v: Int): Unit = {\n if(tree(v).marked) {\n val x = tree(v)\n val y = tree(v << 1)\n val z = tree(v << 1 | 1)\n\n tree(v << 1) = Node(y.count, y.add + x.add, true)\n tree(v << 1 | 1) = Node(z.count, z.add + x.add, true)\n tree(v) = Node(x.count, 0, true)\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, l: Int, r: Int, nAdd: Int): Unit = {\n if(l > r) {}\n else if(tl == tr && tree(v).marked) {\n a(tl) += tree(v).add\n tree(v) = Node(isLucky(a(tl)), 0, false)\n }\n else if(l == tl && r == tr) {\n val x = tree(v)\n tree(v) = Node(x.count, x.add + nAdd, marked = true)\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n update(v << 1, tl, tm, l, Math.min(tm, r), nAdd)\n update(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, nAdd)\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(l > r) Node(0, 0, false)\n else if(l == tl && r == tr && !tree(v).marked) {\n tree(v)\n } else if(tl == tr && tree(v).marked) {\n a(tl) += tree(v).add\n tree(v) = Node(isLucky(a(tl)), 0, false)\n tree(v)\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n combine(get(v << 1, tl, tm, l, Math.min(tm, r)),\n get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r))\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 C091E(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 C091E(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 val a = na(n)\n val t = new SegmentTree(n, a)\n t.build(1, 0, n-1)\n REP(m) { _ =>\n ns() match {\n case \"count\" =>\n out.println(t.get(1, 0, n-1, ni()-1, ni()-1).count)\n case \"add\" =>\n t.update(1, 0, n-1, ni()-1, ni()-1, ni())\n }\n }\n }\n\n case class Node(count: Int, add: Int, marked: Boolean)\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val tree: Array[Node] = Array.ofDim[Node](4 * n)\n\n private def isLucky(u: Int): Int = {\n var v = u\n var countI = 0\n var countT = 0\n while (v > 0) {\n val g = v % 10\n if(g == 4 || g == 7) countI += 1\n v = v / 10\n countT += 1;\n }\n if(countI == countT) 1 else 0\n }\n\n private def combine(x: Node, y: Node): Node = {\n Node(x.count + y.count, 0, x.marked || y.marked)\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n tree(v) = Node(isLucky(a(tl)), 0, false)\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 push(v: Int): Unit = {\n if(tree(v).marked) {\n val x = tree(v)\n val y = tree(v << 1)\n val z = tree(v << 1 | 1)\n\n tree(v << 1) = Node(y.count, y.add + x.add, true)\n tree(v << 1 | 1) = Node(z.count, z.add + x.add, true)\n tree(v) = Node(x.count, 0, false)\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, l: Int, r: Int, nAdd: Int): Unit = {\n if(l > r) {}\n else if(tl == tr && tree(v).marked) {\n a(tl) += tree(v).add\n tree(v) = Node(isLucky(a(tl)), 0, false)\n }\n else if(l == tl && r == tr) {\n val x = tree(v)\n tree(v) = Node(x.count, x.add + nAdd, marked = true)\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n update(v << 1, tl, tm, l, Math.min(tm, r), nAdd)\n update(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, nAdd)\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(l > r) Node(0, 0, false)\n else if(l == tl && r == tr && !tree(v).marked) {\n tree(v)\n } else if(tl == tr && tree(v).marked) {\n a(tl) += tree(v).add\n tree(v) = Node(isLucky(a(tl)), 0, false)\n tree(v)\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n combine(get(v << 1, tl, tm, l, Math.min(tm, r)),\n get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r))\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 C091E(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 C091E(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 val a = na(n)\n val t = new SegmentTree(n, a)\n t.build(1, 0, n-1)\n REP(m) { _ =>\n ns() match {\n case \"count\" =>\n out.println(t.get(1, 0, n-1, ni()-1, ni()-1).count)\n t.print()\n case \"add\" =>\n t.update(1, 0, n-1, ni()-1, ni()-1, ni())\n t.print()\n }\n }\n }\n\n case class Node(count: Int, add: Int, marked: Boolean)\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val tree: Array[Node] = Array.ofDim[Node](4 * n)\n\n private def isLucky(u: Int): Int = {\n var v = u\n var countI = 0\n var countT = 0\n while (v > 0) {\n val g = v % 10\n if(g == 4 || g == 7) countI += 1\n v = v / 10\n countT += 1;\n }\n if(countI == countT) 1 else 0\n }\n\n def print(): Unit = {\n// a.foreach(out.println)\n }\n\n private def combine(x: Node, y: Node): Node = {\n Node(x.count + y.count, 0, x.marked || y.marked)\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n tree(v) = Node(isLucky(a(tl)), 0, false)\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 push(v: Int): Unit = {\n if(tree(v).marked) {\n val x = tree(v)\n val y = tree(v << 1)\n val z = tree(v << 1 | 1)\n\n tree(v << 1) = Node(y.count, y.add + x.add, true)\n tree(v << 1 | 1) = Node(z.count, z.add + x.add, true)\n tree(v) = Node(x.count, 0, false)\n }\n }\n\n def update(v: Int, tl: Int, tr: Int, l: Int, r: Int, nAdd: Int): Unit = {\n if(l > r) {}\n else if(tl == tr && tree(v).marked) {\n a(tl) += tree(v).add\n tree(v) = Node(isLucky(a(tl)), 0, false)\n }\n else if(l == tl && r == tr) {\n val x = tree(v)\n tree(v) = Node(x.count, x.add + nAdd, marked = true)\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n update(v << 1, tl, tm, l, Math.min(tm, r), nAdd)\n update(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, nAdd)\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(l > r) Node(0, 0, false)\n else if(l == tl && r == tr && !tree(v).marked) {\n tree(v)\n } else if(tl == tr && tree(v).marked) {\n a(tl) += tree(v).add\n tree(v) = Node(isLucky(a(tl)), 0, false)\n tree(v)\n } else {\n push(v)\n val tm = tl + (tr - tl) / 2\n val x = combine(get(v << 1, tl, tm, l, Math.min(tm, r)),\n get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r))\n tree(v) = combine(tree(v << 1), tree(v << 1 | 1))\n x\n }\n }\n }\n}\n"}], "src_uid": "fc5c03881a7077b33e0f901f521b87df"} {"nl": {"description": "You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.", "input_spec": "The first line contains single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009105)\u00a0\u2014 the number of queries. q lines follow. The (i\u2009+\u20091)-th line contains single integer ni (1\u2009\u2264\u2009ni\u2009\u2264\u2009109)\u00a0\u2014 the i-th query.", "output_spec": "For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.", "sample_inputs": ["1\n12", "2\n6\n8", "3\n1\n2\n3"], "sample_outputs": ["3", "1\n2", "-1\n-1\n-1"], "notes": "Note12\u2009=\u20094\u2009+\u20094\u2009+\u20094\u2009=\u20094\u2009+\u20098\u2009=\u20096\u2009+\u20096\u2009=\u200912, but the first splitting has the maximum possible number of summands.8\u2009=\u20094\u2009+\u20094, 6 can't be split into several composite summands.1,\u20092,\u20093 are less than any composite number, so they do not have valid splittings."}, "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"}, {"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"}], "negative_code": [], "src_uid": "0c2550b2df0849a62969edf5b73e0ac5"} {"nl": {"description": "Ashish has an array $$$a$$$ of consisting of $$$2n$$$ positive integers. He wants to compress $$$a$$$ into an array $$$b$$$ of size $$$n-1$$$. To do this, he first discards exactly $$$2$$$ (any two) elements from $$$a$$$. He then performs the following operation until there are no elements left in $$$a$$$: Remove any two elements from $$$a$$$ and append their sum to $$$b$$$. The compressed array $$$b$$$ has to have a special property. The greatest common divisor ($$$\\mathrm{gcd}$$$) of all its elements should be greater than $$$1$$$.Recall that the $$$\\mathrm{gcd}$$$ of an array of positive integers is the biggest integer that is a divisor of all integers in the array.It can be proven that it is always possible to compress array $$$a$$$ into an array $$$b$$$ of size $$$n-1$$$ such that $$$gcd(b_1, b_2..., b_{n-1}) > 1$$$. Help Ashish find a way to do so.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 1000$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \\ldots, a_{2n}$$$ ($$$1 \\leq a_i \\leq 1000$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case, output $$$n-1$$$ lines\u00a0\u2014 the operations performed to compress the array $$$a$$$ to the array $$$b$$$. The initial discard of the two elements is not an operation, you don't need to output anything about it. The $$$i$$$-th line should contain two integers, the indices ($$$1$$$\u00a0\u2014based) of the two elements from the array $$$a$$$ that are used in the $$$i$$$-th operation. All $$$2n-2$$$ indices should be distinct integers from $$$1$$$ to $$$2n$$$. You don't need to output two initially discarded elements from $$$a$$$. If there are multiple answers, you can find any.", "sample_inputs": ["3\n3\n1 2 3 4 5 6\n2\n5 7 9 10\n5\n1 3 3 4 5 90 100 101 2 3"], "sample_outputs": ["3 6\n4 5\n3 4\n1 9\n2 3\n4 5\n6 10"], "notes": "NoteIn the first test case, $$$b = \\{3+6, 4+5\\} = \\{9, 9\\}$$$ and $$$\\mathrm{gcd}(9, 9) = 9$$$.In the second test case, $$$b = \\{9+10\\} = \\{19\\}$$$ and $$$\\mathrm{gcd}(19) = 19$$$.In the third test case, $$$b = \\{1+2, 3+3, 4+5, 90+3\\} = \\{3, 6, 9, 93\\}$$$ and $$$\\mathrm{gcd}(3, 6, 9, 93) = 3$$$."}, "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 { 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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1,\u2009x2,\u2009...,\u2009xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi\u2009-\u2009hi,\u2009xi] or [xi;xi\u2009+\u2009hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of trees. Next n lines contain pairs of integers xi,\u2009hi (1\u2009\u2264\u2009xi,\u2009hi\u2009\u2264\u2009109) \u2014 the coordinate and the height of the \u0456-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.", "output_spec": "Print a single number \u2014 the maximum number of trees that you can cut down by the given rules.", "sample_inputs": ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"], "sample_outputs": ["3", "4"], "notes": "NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left \u2014 now it occupies segment [\u2009-\u20091;1] fell the 2-nd tree to the right \u2014 now it occupies segment [2;3] leave the 3-rd tree \u2014 it occupies point 5 leave the 4-th tree \u2014 it occupies point 10 fell the 5-th tree to the right \u2014 now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]."}, "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": "/**\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"}, {"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"} {"nl": {"description": "Because of budget cuts one IT company established new non-financial reward system instead of bonuses.Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets \"I fixed a critical bug\" pennant on his table. A man who suggested a new interesting feature gets \"I suggested a new feature\" pennant on his table.Because of the limited budget of the new reward system only 5 \"I fixed a critical bug\" pennants and 3 \"I suggested a new feature\" pennants were bought.In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded \"I fixed a critical bug\" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded \"I suggested a new feature\" pennants is passed on to his table.One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.", "input_spec": "The only line of the input contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500) \u2014 the number of tables in the IT company.", "output_spec": "Output one integer \u2014 the amount of ways to place the pennants on n tables.", "sample_inputs": ["2"], "sample_outputs": ["24"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "d41aebacfd5d16046db7c5d339478115"} {"nl": {"description": "We have a point $$$A$$$ with coordinate $$$x = n$$$ on $$$OX$$$-axis. We'd like to find an integer point $$$B$$$ (also on $$$OX$$$-axis), such that the absolute difference between the distance from $$$O$$$ to $$$B$$$ and the distance from $$$A$$$ to $$$B$$$ is equal to $$$k$$$. The description of the first test case. Since sometimes it's impossible to find such point $$$B$$$, we can, in one step, increase or decrease the coordinate of $$$A$$$ by $$$1$$$. What is the minimum number of steps we should do to make such point $$$B$$$ exist?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 6000$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$0 \\le n, k \\le 10^6$$$)\u00a0\u2014 the initial position of point $$$A$$$ and desirable absolute difference.", "output_spec": "For each test case, print the minimum number of steps to make point $$$B$$$ exist.", "sample_inputs": ["6\n4 0\n5 8\n0 1000000\n0 0\n1 0\n1000000 1000000"], "sample_outputs": ["0\n3\n1000000\n0\n1\n0"], "notes": "NoteIn the first test case (picture above), if we set the coordinate of $$$B$$$ as $$$2$$$ then the absolute difference will be equal to $$$|(2 - 0) - (4 - 2)| = 0$$$ and we don't have to move $$$A$$$. So the answer is $$$0$$$.In the second test case, we can increase the coordinate of $$$A$$$ by $$$3$$$ and set the coordinate of $$$B$$$ as $$$0$$$ or $$$8$$$. The absolute difference will be equal to $$$|8 - 0| = 8$$$, so the answer is $$$3$$$. "}, "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 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"}, {"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"} {"nl": {"description": "Mishka got an integer array $$$a$$$ of length $$$n$$$ as a birthday present (what a surprise!).Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it \"Mishka's Adjacent Replacements Algorithm\". This algorithm can be represented as a sequence of steps: Replace each occurrence of $$$1$$$ in the array $$$a$$$ with $$$2$$$; Replace each occurrence of $$$2$$$ in the array $$$a$$$ with $$$1$$$; Replace each occurrence of $$$3$$$ in the array $$$a$$$ with $$$4$$$; Replace each occurrence of $$$4$$$ in the array $$$a$$$ with $$$3$$$; Replace each occurrence of $$$5$$$ in the array $$$a$$$ with $$$6$$$; Replace each occurrence of $$$6$$$ in the array $$$a$$$ with $$$5$$$; $$$\\dots$$$ Replace each occurrence of $$$10^9 - 1$$$ in the array $$$a$$$ with $$$10^9$$$; Replace each occurrence of $$$10^9$$$ in the array $$$a$$$ with $$$10^9 - 1$$$. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($$$2i - 1, 2i$$$) for each $$$i \\in\\{1, 2, \\ldots, 5 \\cdot 10^8\\}$$$ as described above.For example, for the array $$$a = [1, 2, 4, 5, 10]$$$, the following sequence of arrays represents the algorithm: $$$[1, 2, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$1$$$ with $$$2$$$) $$$\\rightarrow$$$ $$$[2, 2, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$2$$$ with $$$1$$$) $$$\\rightarrow$$$ $$$[1, 1, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$3$$$ with $$$4$$$) $$$\\rightarrow$$$ $$$[1, 1, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$4$$$ with $$$3$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$5$$$ with $$$6$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 6, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$6$$$ with $$$5$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\\rightarrow$$$ $$$\\dots$$$ $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$10$$$ with $$$9$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 9]$$$. The later steps of the algorithm do not change the array.Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.", "input_spec": "The first line of the input contains one integer number $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of elements in Mishka's birthday present (surprisingly, an array). The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the elements of the array.", "output_spec": "Print $$$n$$$ integers \u2014 $$$b_1, b_2, \\dots, b_n$$$, where $$$b_i$$$ is the final value of the $$$i$$$-th element of the array after applying \"Mishka's Adjacent Replacements Algorithm\" to the array $$$a$$$. Note that you cannot change the order of elements in the array.", "sample_inputs": ["5\n1 2 4 5 10", "10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000"], "sample_outputs": ["1 1 3 5 9", "9999 9 50605065 1 5 89 5 999999999 60506055 999999999"], "notes": "NoteThe first example is described in the problem statement."}, "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 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}"}, {"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"} {"nl": {"description": "Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is $$$n$$$. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains $$$2$$$ apartments, every other floor contains $$$x$$$ apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers $$$1$$$ and $$$2$$$, apartments on the second floor have numbers from $$$3$$$ to $$$(x + 2)$$$, apartments on the third floor have numbers from $$$(x + 3)$$$ to $$$(2 \\cdot x + 2)$$$, and so on.Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least $$$n$$$ apartments.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n, x \\le 1000$$$) \u2014 the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).", "output_spec": "For each test case, print the answer: the number of floor on which Petya lives.", "sample_inputs": ["4\n7 3\n1 5\n22 5\n987 13"], "sample_outputs": ["3\n1\n5\n77"], "notes": "NoteConsider the first test case of the example: the first floor contains apartments with numbers $$$1$$$ and $$$2$$$, the second one contains apartments with numbers $$$3$$$, $$$4$$$ and $$$5$$$, the third one contains apartments with numbers $$$6$$$, $$$7$$$ and $$$8$$$. Therefore, Petya lives on the third floor.In the second test case of the example, Petya lives in the apartment $$$1$$$ which is on the first floor."}, "positive_code": [{"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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#\u03a6\u03c9\u03a6 has just got a new maze game on her PC!The game's main puzzle is a maze, in the forms of a $$$2 \\times n$$$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $$$(1, 1)$$$ to the gate at $$$(2, n)$$$ and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only $$$q$$$ such moments: the $$$i$$$-th moment toggles the state of cell $$$(r_i, c_i)$$$ (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the $$$q$$$ moments, whether it is still possible to move from cell $$$(1, 1)$$$ to cell $$$(2, n)$$$ without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?", "input_spec": "The first line contains integers $$$n$$$, $$$q$$$ ($$$2 \\le n \\le 10^5$$$, $$$1 \\le q \\le 10^5$$$). The $$$i$$$-th of $$$q$$$ following lines contains two integers $$$r_i$$$, $$$c_i$$$ ($$$1 \\le r_i \\le 2$$$, $$$1 \\le c_i \\le n$$$), denoting the coordinates of the cell to be flipped at the $$$i$$$-th moment. It is guaranteed that cells $$$(1, 1)$$$ and $$$(2, n)$$$ never appear in the query list.", "output_spec": "For each moment, if it is possible to travel from cell $$$(1, 1)$$$ to cell $$$(2, n)$$$, print \"Yes\", otherwise print \"No\". There should be exactly $$$q$$$ answers, one after every update. You can print the words in any case (either lowercase, uppercase or mixed).", "sample_inputs": ["5 5\n2 3\n1 4\n2 4\n2 3\n1 4"], "sample_outputs": ["Yes\nNo\nNo\nNo\nYes"], "notes": "NoteWe'll crack down the example test here: After the first query, the girl still able to reach the goal. One of the shortest path ways should be: $$$(1,1) \\to (1,2) \\to (1,3) \\to (1,4) \\to (1,5) \\to (2,5)$$$. After the second query, it's impossible to move to the goal, since the farthest cell she could reach is $$$(1, 3)$$$. After the fourth query, the $$$(2, 3)$$$ is not blocked, but now all the $$$4$$$-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. "}, "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"}, {"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"}], "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"} {"nl": {"description": "Innokentiy decides to change the password in the social net \"Contact!\", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: the length of the password must be equal to n, the password should consist only of lowercase Latin letters, the number of distinct symbols in the password must be equal to k, any two consecutive symbols in the password must be distinct. Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions. ", "input_spec": "The first line contains two positive integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 2\u2009\u2264\u2009k\u2009\u2264\u2009min(n,\u200926)) \u2014 the length of the password and the number of distinct symbols in it. Pay attention that a desired new password always exists.", "output_spec": "Print any password which satisfies all conditions given by Innokentiy.", "sample_inputs": ["4 3", "6 6", "5 2"], "sample_outputs": ["java", "python", "phphp"], "notes": "NoteIn the first test there is one of the appropriate new passwords \u2014 java, because its length is equal to 4 and 3 distinct lowercase letters a, j and v are used in it.In the second test there is one of the appropriate new passwords \u2014 python, because its length is equal to 6 and it consists of 6 distinct lowercase letters.In the third test there is one of the appropriate new passwords \u2014 phphp, because its length is equal to 5 and 2 distinct lowercase letters p and h are used in it.Pay attention the condition that no two identical symbols are consecutive is correct for all appropriate passwords in tests. "}, "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 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"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "39f5e934bf293053246bd3faa8061c3b"} {"nl": {"description": "HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1\u2009\u2264\u2009fi\u2009\u2264\u2009n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |a\u2009-\u2009b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of fragments. The second line contains n different integers fi (1\u2009\u2264\u2009fi\u2009\u2264\u2009n) \u2014 the number of the fragment written in the i-th sector.", "output_spec": "Print the only integer \u2014 the number of time units needed to read the file.", "sample_inputs": ["3\n3 1 2", "5\n1 3 5 4 2"], "sample_outputs": ["3", "10"], "notes": "NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4\u2009+\u20093\u2009+\u20092\u2009+\u20091\u2009=\u200910."}, "positive_code": [{"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": "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": "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}"}, {"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) //\u6ca1\u6709new\u65f6\uff0c\u662f\u521d\u59cb\u5316\u503c\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}"}], "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) //\u6ca1\u6709new\u65f6\uff0c\u662f\u521d\u59cb\u5316\u503c\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"} {"nl": {"description": "The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!There are $$$n$$$ snacks flavors, numbered with integers $$$1, 2, \\ldots, n$$$. Bessie has $$$n$$$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.", "input_spec": "The first line contains integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$1 \\le k \\le 10^5$$$), the number of snacks and the number of guests. The $$$i$$$-th of the following $$$k$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$, $$$x_i \\ne y_i$$$), favorite snack flavors of the $$$i$$$-th guest.", "output_spec": "Output one integer, the smallest possible number of sad guests.", "sample_inputs": ["5 4\n1 2\n4 3\n1 4\n3 4", "6 5\n2 3\n2 1\n3 4\n6 5\n4 5"], "sample_outputs": ["1", "0"], "notes": "NoteIn the first example, Bessie can order the guests like this: $$$3, 1, 2, 4$$$. Guest $$$3$$$ goes first and eats snacks $$$1$$$ and $$$4$$$. Then the guest $$$1$$$ goes and eats the snack $$$2$$$ only, because the snack $$$1$$$ has already been eaten. Similarly, the guest $$$2$$$ goes up and eats the snack $$$3$$$ only. All the snacks are gone, so the guest $$$4$$$ will be sad. In the second example, one optimal ordering is $$$2, 1, 3, 5, 4$$$. All the guests will be satisfied."}, "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 case class Entry(x: Int, y: 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\n // toInt\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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 private def merge(node: Int, rt: Int): Int = {\n par(node) = rt\n rank(rt) += rank(node)\n rt\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(y1))\n merge(x1, y1)\n else\n merge(y1, x1)\n }\n }\n\n /**\n * x\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\n */\n def cntNodes(x: Int): Int = rank(find(x))\n }\n\n def solve(): Unit = {\n val N, K = ni()\n val E = mutable.Set[Entry]()\n val uf = new UnionFind(N)\n REP(K) { _ =>\n var x, y = ni() - 1\n // x < y \u306b\u3059\u308b\n if (x > y) {\n val t = x\n x = y\n y = t\n }\n\n if (!E.contains(Entry(x, y))) {\n E += Entry(x, y)\n }\n\n uf.unite(x, y)\n }\n\n var ans = K\n val cnted = Array.ofDim[Boolean](N)\n REP(N) { i =>\n val id = uf.find(i)\n if (!cnted(id)) {\n val cnt = uf.cntNodes(id)\n if (cnt > 1) {\n ans -= cnt - 1\n }\n }\n cnted(id) = true\n }\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "a7d68ecc1a9ee23cf98f51fe6651ae13"} {"nl": {"description": "You are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly ti milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer ai to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than ai problems overall (including problem i).Formally, suppose you solve problems p1,\u2009p2,\u2009...,\u2009pk during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that k\u2009\u2264\u2009apj.You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.", "input_spec": "The first line contains two integers n and T (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105; 1\u2009\u2264\u2009T\u2009\u2264\u2009109)\u00a0\u2014 the number of problems in the exam and the length of the exam in milliseconds, respectively. Each of the next n lines contains two integers ai and ti (1\u2009\u2264\u2009ai\u2009\u2264\u2009n; 1\u2009\u2264\u2009ti\u2009\u2264\u2009104). The problems are numbered from 1 to n.", "output_spec": "In the first line, output a single integer s\u00a0\u2014 your maximum possible final score. In the second line, output a single integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of problems you should solve. In the third line, output k distinct integers p1,\u2009p2,\u2009...,\u2009pk (1\u2009\u2264\u2009pi\u2009\u2264\u2009n)\u00a0\u2014 the indexes of problems you should solve, in any order. If there are several optimal sets of problems, you may output any of them.", "sample_inputs": ["5 300\n3 100\n4 150\n4 80\n2 90\n2 300", "2 100\n1 787\n2 788", "2 100\n2 42\n2 58"], "sample_outputs": ["2\n3\n3 1 4", "0\n0", "2\n2\n1 2"], "notes": "NoteIn the first example, you should solve problems 3, 1, and 4. In this case you'll spend 80\u2009+\u2009100\u2009+\u200990\u2009=\u2009270 milliseconds, falling within the length of the exam, 300 milliseconds (and even leaving yourself 30 milliseconds to have a rest). Problems 3 and 1 will bring you a point each, while problem 4 won't. You'll score two points.In the second example, the length of the exam is catastrophically not enough to solve even a single problem.In the third example, you have just enough time to solve both problems in 42\u2009+\u200958\u2009=\u2009100 milliseconds and hand your solutions to the teacher with a smile."}, "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"}, {"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"}], "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"} {"nl": {"description": " Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters \"a\", \"b\" and \"c\". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string \"abc\" as a substring. A valid replacement of a character is replacing it with \"a\", \"b\" or \"c\".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \\le n, q \\le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters \"a\", \"b\" and \"c\". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \\le i \\le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is \"a\", \"b\" or \"c\".", "output_spec": "For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain \"abc\" as a substring.", "sample_inputs": ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"], "sample_outputs": ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"], "notes": "NoteLet's consider the state of the string after each query: $$$s =$$$ \"abcabcabc\". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bbcaccabb\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bbcabcabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bbcbbcbbc\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bccabcabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bccbbcbbc\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcaabcabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcbbc\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabbcabc\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcabb\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabccabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcabb\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabccaac\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcaac\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabccaab\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcaab\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"ccabccaab\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"ccabbcaab\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"ccaaccaab\". In this case the string does not contain \"abc\" as a substring and no replacements are needed."}, "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\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"}, {"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 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"}, {"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"}], "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"} {"nl": {"description": "Let us define two functions f and g on positive integer numbers. You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x)\u2009=\u2009k. ", "input_spec": "The first line of the input contains an integer Q (1\u2009\u2264\u2009Q\u2009\u2264\u20092\u2009\u00d7\u2009105) representing the number of queries. Q lines follow, each of which contains 3 integers l, r and k (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009106,\u20091\u2009\u2264\u2009k\u2009\u2264\u20099).", "output_spec": "For each query, print a single line containing the answer for that query.", "sample_inputs": ["4\n22 73 9\n45 64 6\n47 55 7\n2 62 4", "4\n82 94 6\n56 67 4\n28 59 9\n39 74 4"], "sample_outputs": ["1\n4\n0\n8", "3\n1\n1\n5"], "notes": "NoteIn the first example: g(33)\u2009=\u20099 as g(33)\u2009=\u2009g(3\u2009\u00d7\u20093)\u2009=\u2009g(9)\u2009=\u20099 g(47)\u2009=\u2009g(48)\u2009=\u2009g(60)\u2009=\u2009g(61)\u2009=\u20096 There are no such integers between 47 and 55. g(4)\u2009=\u2009g(14)\u2009=\u2009g(22)\u2009=\u2009g(27)\u2009=\u2009g(39)\u2009=\u2009g(40)\u2009=\u2009g(41)\u2009=\u2009g(58)\u2009=\u20094 "}, "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 gs = Array.fill(1000003)(-1)\n\n def g(x: Int): Int = {\n if (gs(x) == -1) {\n if (x <= 9) gs(x) = x\n else {\n var prod = 1\n var xx = x\n while (xx > 1) {\n val mod = xx % 10\n if (mod > 0) prod *= mod\n xx /= 10\n }\n gs(x) = g(prod)\n }\n }\n gs(x)\n }\n\n for (i <- gs.indices) g(i)\n\n val xByG = gs.indices.groupBy(gs).map {\n case (g, xs) => g -> xs.toArray.sorted\n }\n \n val Array(n) = readInts(1)\n val result = Array.ofDim[Int](n)\n\n @annotation.tailrec\n def binSearch(as: Array[Int], key: Int, low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (as(mid) >= key) binSearch(as, key, low, mid - 1)\n else binSearch(as, key, mid + 1, hi)\n }\n }\n\n for (i <- 0 until n) {\n val Array(l, r, k) = readInts(3)\n val xs = xByG(k)\n var lPos = binSearch(xs, l, 0, xs.length - 1)\n var rPos = binSearch(xs, r, 0, xs.length - 1)\n if (rPos < xs.length && xs(rPos) == r) rPos += 1\n //println(lPos, rPos, k, xs.slice(lPos, rPos + 1).mkString(\" \"), xs.take(20).mkString(\" \"))\n result(i) = rPos - lPos\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(result.mkString(\"\\n\"))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "7a647a5f10cdcd2b54a1927107edea4f"} {"nl": {"description": "A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.", "input_spec": "The first line of input contains n \u2014 a positive integer number without leading zeroes (1\u2009\u2264\u2009n\u2009<\u200910100000).", "output_spec": "Print one number \u2014 any beautiful number obtained by erasing as few as possible digits. If there is no answer, print \u2009-\u20091.", "sample_inputs": ["1033", "10", "11"], "sample_outputs": ["33", "0", "-1"], "notes": "NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two."}, "positive_code": [{"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val num = readLine()\n def start(char: Char) = (0 to 2).map(i \u21d2 if (i == group(char)) Vector(char) else Vector.empty).toArray\n def group(char: Char) = (char - '0') % 3\n def addChar(c: Char)(v: Vector[Char]) = if (v.isEmpty) v else v :+ c\n def combine(xs: Array[Vector[Char]], ys: Array[Vector[Char]]) = xs.zip(ys).map {\n case (lx, ly) \u21d2 if (lx.size > ly.size) lx else ly\n }\n val opts = num.tail.foldLeft(start(num.head)) {\n case (prev, '0') \u21d2 prev.map(addChar('0'))\n case (prev, char) \u21d2\n val add = prev.map(addChar(char))\n val shift = (3 - group(char)) % 3\n combine(combine(prev, add.drop(shift) ++ add.take(shift)), start(char))\n }\n\n println(opts(0) match {\n case Vector() \u21d2 if (num.contains('0')) \"0\" else \"-1\"\n case vect \u21d2 vect.mkString\n })\n}\n"}], "negative_code": [], "src_uid": "df9942d1eb66b1f3b5c6b665b446cd3e"} {"nl": {"description": "The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?", "input_spec": "The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \\leq n \\leq 99$$$, $$$0 \\leq k \\leq 2\\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively.", "output_spec": "Print \"YES\", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print \"NO\". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is \"#\" if that cell has a hotel on it, or \".\" if not.", "sample_inputs": ["7 2", "5 3"], "sample_outputs": ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Treeland is a country in which there are n towns connected by n\u2009-\u20091 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1. ", "input_spec": "The first line of the input contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009/\u20092)\u00a0\u2014 the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n. The second line contains 2k distinct integers u1,\u2009u2,\u2009...,\u2009u2k (1\u2009\u2264\u2009ui\u2009\u2264\u2009n)\u00a0\u2014 indices of towns in which universities are located. The next n\u2009-\u20091 line contains the description of roads. Each line contains the pair of integers xj and yj (1\u2009\u2264\u2009xj,\u2009yj\u2009\u2264\u2009n), which means that the j-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads. ", "output_spec": "Print the maximum possible sum of distances in the division of universities into k pairs.", "sample_inputs": ["7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6", "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8"], "sample_outputs": ["6", "9"], "notes": "NoteThe figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example. "}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: the graph contains exactly 2n\u2009+\u2009p edges; the graph doesn't contain self-loops and multiple edges; for any integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n), any subgraph consisting of k vertices contains at most 2k\u2009+\u2009p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.", "input_spec": "The first line contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u20095) \u2014 the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5\u2009\u2264\u2009n\u2009\u2264\u200924; p\u2009\u2265\u20090; ) \u2014 the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists.", "output_spec": "For each of the t tests print 2n\u2009+\u2009p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi) \u2014 two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.", "sample_inputs": ["1\n6 0"], "sample_outputs": ["1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6"], "notes": null}, "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 t = readInt\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n \n for (test <- 1 to t) {\n val Array(n, p) = readInts(2)\n var c = 2 * n + p\n var step = 1\n while (c > 0) {\n var u = 0\n while (u < n && c > 0) {\n val v = (u + step) % n\n println(s\"${u + 1} ${v + 1}\")\n u += 1\n c -= 1\n }\n step += 1\n }\n }\n\n Console.flush\n}"}], "negative_code": [], "src_uid": "ddbac4053bd07eada84bc44275367ae2"} {"nl": {"description": "Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn\u2009=\u2009sn\u2009-\u20092\u2009+\u2009sn\u2009-\u20091, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him \u043ef accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.", "input_spec": "The first line contains four integers k,\u2009x,\u2009n,\u2009m (3\u2009\u2264\u2009k\u2009\u2264\u200950;\u00a00\u2009\u2264\u2009x\u2009\u2264\u2009109;\u00a01\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100).", "output_spec": "In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them. If the required pair of strings doesn't exist, print \"Happy new year!\" without the quotes.", "sample_inputs": ["3 2 2 2", "3 3 2 2", "3 0 2 2", "4 3 2 1", "4 2 2 1"], "sample_outputs": ["AC\nAC", "Happy new year!", "AA\nAA", "Happy new year!", "Happy new year!"], "notes": null}, "positive_code": [{"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val List(k0, x0, n0, m0) = input.next().split(\" \").toList\n val k = k0.toInt\n val x = x0.toLong\n val n = n0.toInt\n val m = m0.toInt\n val res = new Array[Long](k)\n for (sc0 <- List(true, false))\n for (sc1 <- List(true, false))\n for (ea0 <- List(true, false))\n for (ea1 <- List(true, false)) {\n if (n > 1 || !(sc0 && ea0))\n if (m > 1 || !(sc1 && ea1)) {\n def calmax(sc: Boolean, ea: Boolean, len: Int) = {\n var a = len\n if (sc) a-= 1\n if (ea) a-= 1\n a.max(0) / 2\n }\n val acn0max = calmax(sc0, ea0, n)\n val acn1max = calmax(sc1, ea1, m)\n for (acn0 <- 0 to acn0max)\n for (acn1 <- 0 to acn1max) {\n res(0) = acn0\n res(1) = acn1\n for (n <- 2 until res.length) {\n res(n) = (if ((if (n == 2) ea0 else ea1) && (if (n % 2 == 0) sc1 else sc0)) 1 else 0) + res(n-1) + res(n-2)\n }\n if (res.last == x) {\n val s0 =\n (if (sc0) \"C\" else \"\") + (0 until acn0).map(_ => \"AC\").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => \"X\").mkString + (if (ea0) \"A\" else \"\")\n val s1 =\n (if (sc1) \"C\" else \"\") + (0 until acn1).map(_ => \"AC\").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => \"X\").mkString + (if (ea1) \"A\" else \"\")\n println(s0)\n println(s1)\n System.exit(0)\n }\n }\n }\n }\n print(\"Happy new year!\")\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 val List(k, x, n, m) = input.next().split(\" \").map(_.toInt).toList\n /*\n\n val sc \"start with c\" = Array[Boolean](k)\n val ea \"end with a\" = Array[Boolean](k)\n\n val acn \"ac number\" = Array[Int](k)\n\n acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]\n sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]\n ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]\n\n\n if (sc[1] && sc[2] && ea[2] && ea[1])\n acn[n] = 1 + acn[n-1] + acn[n-2]\n\n\n n + a n-1 = c(n-1 + a n-2)\n n a-c -ac\n 1 -1 -1\n\n I do not think it will work...\n */\n val res = new Array[Int](k)\n // sc1 sc2 ea2 ea1\n for (sc0 <- List(true, false))\n for (sc1 <- List(true, false))\n for (ea0 <- List(true, false))\n for (ea1 <- List(true, false)) {\n if (n > 1 || !(sc0 && ea0))\n if (m > 1 || !(sc1 && ea1)) {\n def calmax(sc: Boolean, ea: Boolean, len: Int) = {\n var a = len\n if (sc) a-= 1\n if (ea) a-= 1\n a.max(0) / 2\n }\n val acn0max = calmax(sc0, ea0, n)\n val acn1max = calmax(sc1, ea1, m)\n for (acn0 <- 0 to acn0max)\n for (acn1 <- 0 to acn1max) {\n res(0) = acn0\n res(1) = acn1\n for (n <- 2 until res.length) {\n // what is () + + !!!\n res(n) = (if ((if (n == 2) ea0 else ea1) && (if (n % 2 == 0) sc0 else sc1)) 1 else 0) + res(n-1) + res(n-2)\n }\n if (res.last == x) {\n val s0 =\n (if (sc0) \"C\" else \"\") + (0 until acn0).map(_ => \"AC\").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => \"X\").mkString + (if (ea0) \"A\" else \"\")\n val s1 =\n (if (sc1) \"C\" else \"\") + (0 until acn1).map(_ => \"AC\").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => \"X\").mkString + (if (ea1) \"A\" else \"\")\n println(s0)\n println(s1)\n System.exit(0)\n }\n }\n }\n }\n print(\"Happy new year!\")\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val List(k, x, n, m) = input.next().split(\" \").map(_.toInt).toList\n /*\n\n val sc \"start with c\" = Array[Boolean](k)\n val ea \"end with a\" = Array[Boolean](k)\n\n val acn \"ac number\" = Array[Int](k)\n\n acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]\n sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]\n ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]\n\n\n if (sc[1] && sc[2] && ea[2] && ea[1])\n acn[n] = 1 + acn[n-1] + acn[n-2]\n\n\n n + a n-1 = c(n-1 + a n-2)\n n a-c -ac\n 1 -1 -1\n\n I do not think it will work...\n */\n val res = new Array[Int](k)\n // sc1 sc2 ea2 ea1\n for (sc0 <- List(true, false))\n for (sc1 <- List(true, false))\n for (ea0 <- List(true, false))\n for (ea1 <- List(true, false)) {\n if (n > 1 || !(sc0 && ea0))\n if (m > 1 || !(sc1 && ea1)) {\n def calmax(sc: Boolean, ea: Boolean, len: Int) = {\n var a = len\n if (sc) a-= 1\n if (ea) a-= 1\n a.max(0) / 2\n }\n val acn0max = calmax(sc0, ea0, n)\n val acn1max = calmax(sc1, ea1, m)\n for (acn0 <- 0 to acn0max)\n for (acn1 <- 0 to acn1max) {\n res(0) = acn0\n res(1) = acn1\n for (n <- 2 until res.length) {\n // what is () + + !!!\n res(n) = (if ((if (n == 2) ea0 else ea1) && (if (n % 2 == 0) sc1 else sc0)) 1 else 0) + res(n-1) + res(n-2)\n }\n if (res.last == x) {\n val s0 =\n (if (sc0) \"C\" else \"\") + (0 until acn0).map(_ => \"AC\").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => \"X\").mkString + (if (ea0) \"A\" else \"\")\n val s1 =\n (if (sc1) \"C\" else \"\") + (0 until acn1).map(_ => \"AC\").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => \"X\").mkString + (if (ea1) \"A\" else \"\")\n println(s0)\n println(s1)\n System.exit(0)\n }\n }\n }\n }\n print(\"Happy new year!\")\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val List(k, x, n, m) = input.next().split(\" \").map(_.toInt).toList\n /*\n\n val sc \"start with c\" = Array[Boolean](k)\n val ea \"end with a\" = Array[Boolean](k)\n\n val acn \"ac number\" = Array[Int](k)\n\n acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]\n sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]\n ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]\n\n\n if (sc[1] && sc[2] && ea[2] && ea[1])\n acn[n] = 1 + acn[n-1] + acn[n-2]\n\n\n n + a n-1 = c(n-1 + a n-2)\n n a-c -ac\n 1 -1 -1\n\n I do not think it will work...\n */\n val res = new Array[Int](k)\n // sc1 sc2 ea2 ea1\n for (sc0 <- List(true, false))\n for (sc1 <- List(true, false))\n for (ea0 <- List(true, false))\n for (ea1 <- List(true, false)) {\n if (n > 1 || !(sc0 && ea0))\n if (m > 1 || !(sc1 && ea1)) {\n def calmax(sc: Boolean, ea: Boolean, len: Int) = {\n var a = len\n if (sc) a-= 1\n if (ea) a-= 1\n a.max(0) / 2\n }\n val acn0max = calmax(sc0, ea0, n)\n val acn1max = calmax(sc1, ea1, m)\n for (acn0 <- 0 to acn0max)\n for (acn1 <- 0 to acn1max) {\n res(0) = acn0\n res(1) = acn1\n for (n <- 2 until res.length) {\n // what is () + + !!!\n res(n) = (if (ea1 && (if (n % 2 == 0) sc1 else sc0)) 1 else 0) + res(n-1) + res(n-2)\n }\n if (res.last == x) {\n val s0 =\n (if (sc0) \"C\" else \"\") + (0 until acn0).map(_ => \"AC\").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => \"X\").mkString + (if (ea0) \"A\" else \"\")\n val s1 =\n (if (sc1) \"C\" else \"\") + (0 until acn1).map(_ => \"AC\").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => \"X\").mkString + (if (ea1) \"A\" else \"\")\n println(s0)\n println(s1)\n System.exit(0)\n }\n }\n }\n }\n print(\"Happy new year!\")\n }\n}\n"}, {"source_code": "\nobject Main {\n\n def main(args: Array[String]) = {\n val input = scala.io.Source.stdin.getLines()\n val List(k, x, n, m) = input.next().split(\" \").map(_.toInt).toList\n /*\n\n val sc \"start with c\" = Array[Boolean](k)\n val ea \"end with a\" = Array[Boolean](k)\n\n val acn \"ac number\" = Array[Int](k)\n\n acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]\n sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]\n ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]\n\n\n if (sc[1] && sc[2] && ea[2] && ea[1])\n acn[n] = 1 + acn[n-1] + acn[n-2]\n\n\n n + a n-1 = c(n-1 + a n-2)\n n a-c -ac\n 1 -1 -1\n\n I do not think it will work...\n */\n val res = new Array[Int](k)\n // sc1 sc2 ea2 ea1\n for (sc0 <- List(true, false))\n for (sc1 <- List(true, false))\n for (ea0 <- List(true, false))\n for (ea1 <- List(true, false)) {\n if (n > 1 || !(sc0 && ea0))\n if (m > 1 || !(sc1 && ea1)) {\n def calmax(sc: Boolean, ea: Boolean, len: Int) = {\n var a = len\n if (sc) a-= 1\n if (ea) a-= 1\n a.max(0) / 2\n }\n val acn0max = calmax(sc0, ea0, n)\n val acn1max = calmax(sc1, ea1, m)\n for (acn0 <- 0 to acn0max)\n for (acn1 <- 0 to acn1max) {\n res(0) = acn0\n res(1) = acn1\n for (n <- 2 until res.length) {\n // what is () + + !!!\n res(n) = (if (ea1 && (if (n % 2 == 0) sc0 else sc1)) 1 else 0) + res(n-1) + res(n-2)\n }\n if (res.last == x) {\n val s0 =\n (if (sc0) \"C\" else \"\") + (0 until acn0).map(_ => \"AC\").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => \"X\").mkString + (if (ea0) \"A\" else \"\")\n val s1 =\n (if (sc1) \"C\" else \"\") + (0 until acn1).map(_ => \"AC\").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => \"X\").mkString + (if (ea1) \"A\" else \"\")\n println(s0)\n println(s1)\n System.exit(0)\n }\n }\n }\n }\n print(\"Happy new year!\")\n }\n}\n"}], "src_uid": "1d55d31320368ddb1439ee086d40b57c"} {"nl": {"description": "CQXYM wants to create a connected undirected graph with $$$n$$$ nodes and $$$m$$$ edges, and the diameter of the graph must be strictly less than $$$k-1$$$. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).The diameter of a graph is the maximum distance between any two nodes.The distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.CQXYM wonders whether it is possible to create such a graph.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t (1 \\leq t \\leq 10^5)$$$ \u2014 the number of test cases. The description of the test cases follows. Only one line of each test case contains three integers $$$n(1 \\leq n \\leq 10^9)$$$, $$$m$$$, $$$k$$$ $$$(0 \\leq m,k \\leq 10^9)$$$.", "output_spec": "For each test case, print YES if it is possible to create the graph, or print NO if it is impossible. You can print each letter in any case (upper or lower).", "sample_inputs": ["5\n1 0 3\n4 5 3\n4 6 3\n5 4 1\n2 1 1"], "sample_outputs": ["YES\nNO\nYES\nNO\nNO"], "notes": "NoteIn the first test case, the graph's diameter equal to 0.In the second test case, the graph's diameter can only be 2.In the third test case, the graph's diameter can only be 1."}, "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 m = readInt()\n val k = readInt()-2\n val edges = n.toLong*(n.toLong-1L)/2L\n if (m > edges || m < n-1)\n writer.println(\"NO\")\n else if ((k == 0 && n > 1) || (k == 1 && m != edges) || (k < 0))\n writer.println(\"NO\")\n else\n writer.println(\"YES\")\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "f853a61741518cb884c00c8b760692aa"} {"nl": {"description": "You are given three positive integers $$$n$$$, $$$a$$$ and $$$b$$$. You have to construct a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters such that each substring of length $$$a$$$ has exactly $$$b$$$ distinct letters. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.Recall that the substring $$$s[l \\dots r]$$$ is the string $$$s_l, s_{l+1}, \\dots, s_{r}$$$ and its length is $$$r - l + 1$$$. In this problem you are only interested in substrings of length $$$a$$$.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains three space-separated integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \\le a \\le n \\le 2000, 1 \\le b \\le \\min(26, a)$$$), where $$$n$$$ is the length of the required string, $$$a$$$ is the length of a substring and $$$b$$$ is the required number of distinct letters in each substring of length $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\\sum n \\le 2000$$$).", "output_spec": "For each test case, print the answer \u2014 such a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters that each substring of length $$$a$$$ has exactly $$$b$$$ distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.", "sample_inputs": ["4\n7 5 3\n6 1 1\n6 6 1\n5 2 2"], "sample_outputs": ["tleelte\nqwerty\nvvvvvv\nabcde"], "notes": "NoteIn the first test case of the example, consider all the substrings of length $$$5$$$: \"tleel\": it contains $$$3$$$ distinct (unique) letters, \"leelt\": it contains $$$3$$$ distinct (unique) letters, \"eelte\": it contains $$$3$$$ distinct (unique) letters. "}, "positive_code": [{"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"}, {"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": "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 val s = (0 until n).map(i => ('a' + i % b).toChar).mkString(\"\")\n\n println(s)\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"} {"nl": {"description": "Learn, learn and learn again \u2014 Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of n numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by \u2009-\u20091. The second operation is to take some suffix and multiply all numbers in it by \u2009-\u20091. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 amount of elements in the sequence. The second line contains n integers ai (\u2009-\u2009104\u2009\u2264\u2009ai\u2009\u2264\u2009104) \u2014 the sequence itself.", "output_spec": "The first and the only line of the output should contain the answer to the problem.", "sample_inputs": ["3\n-1 -2 -3", "5\n-4 2 0 5 0", "5\n-1 10 -5 10 -2"], "sample_outputs": ["6", "11", "18"], "notes": null}, "positive_code": [{"source_code": "object P033C extends App {\n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n val f = (a: Array[Int]) => a.map(-_*2).scan(0)(_+_).scan(0)(math.max(_,_)).drop(1)\n val pb = f(a)\n val sb = f(a.reverse).reverse\n println(a.fold(0)(_+_) + pb.zip(sb).map(x => x._1+x._2).max)\n}\n"}], "negative_code": [], "src_uid": "89237865c97d64406050fd140d4166f9"} {"nl": {"description": "Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.", "input_spec": "First line of input consists of one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000). Next line consists of n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009n), which stand for coolness factor of each badge.", "output_spec": "Output single integer \u2014 minimum amount of coins the colonel has to pay.", "sample_inputs": ["4\n1 3 1 4", "5\n1 2 3 2 5"], "sample_outputs": ["1", "2"], "notes": "NoteIn first sample test we can increase factor of first badge by 1.In second sample test we can increase factors of the second and the third badge by 1."}, "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": "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}"}, {"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 //\u6700\u521d\u306e\u6574\u6570\u304c\u8aad\u307f\u8fbc\u307e\u308c\u308b\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"} {"nl": {"description": "SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.", "input_spec": "A single line contains four integers .", "output_spec": "Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["1 2 1 2"], "sample_outputs": ["0.666666666667"], "notes": null}, "positive_code": [{"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}"}, {"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 //\u7121\u9650\u7b49\u6bd4\u6570\u5217\u3067\u3057\u305f\u3002\u3002\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"} {"nl": {"description": "Recently, the bear started studying data structures and faced the following problem.You are given a sequence of integers x1,\u2009x2,\u2009...,\u2009xn of length n and m queries, each of them is characterized by two integers li,\u2009ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li,\u2009ri is the sum: , where S(li,\u2009ri) is a set of prime numbers from segment [li,\u2009ri] (both borders are included in the segment).Help the bear cope with the problem.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106). The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (2\u2009\u2264\u2009xi\u2009\u2264\u2009107). The numbers are not necessarily distinct. The third line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u200950000). Each of the following m lines contains a pair of space-separated integers, li and ri (2\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u20092\u00b7109) \u2014 the numbers that characterize the current query.", "output_spec": "Print m integers \u2014 the answers to the queries on the order the queries appear in the input.", "sample_inputs": ["6\n5 5 7 10 14 15\n3\n2 11\n3 12\n4 4", "7\n2 3 5 7 11 4 8\n2\n8 10\n2 123"], "sample_outputs": ["9\n7\n0", "0\n7"], "notes": "NoteConsider the first sample. Overall, the first sample has 3 queries. The first query l\u2009=\u20092, r\u2009=\u200911 comes. You need to count f(2)\u2009+\u2009f(3)\u2009+\u2009f(5)\u2009+\u2009f(7)\u2009+\u2009f(11)\u2009=\u20092\u2009+\u20091\u2009+\u20094\u2009+\u20092\u2009+\u20090\u2009=\u20099. The second query comes l\u2009=\u20093, r\u2009=\u200912. You need to count f(3)\u2009+\u2009f(5)\u2009+\u2009f(7)\u2009+\u2009f(11)\u2009=\u20091\u2009+\u20094\u2009+\u20092\u2009+\u20090\u2009=\u20097. The third query comes l\u2009=\u20094, r\u2009=\u20094. As this interval has no prime numbers, then the sum equals 0. "}, "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}"}, {"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"}], "negative_code": [], "src_uid": "fe42c7f0222497ce3fff51b3676f42d1"} {"nl": {"description": "Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1,\u2009a2,\u2009...,\u2009ak such that ai and ai\u2009+\u20091 are friends for each 1\u2009\u2264\u2009i\u2009<\u2009k, and a1\u2009=\u2009x and ak\u2009=\u2009y. Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.", "input_spec": "The first line contains integers n, m and w (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u20091000, , 1\u2009\u2264\u2009w\u2009\u2264\u20091000)\u00a0\u2014 the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u20091000)\u00a0\u2014 the weights of the Hoses. The third line contains n integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009106)\u00a0\u2014 the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi,\u2009yi) are distinct.", "output_spec": "Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.", "sample_inputs": ["3 1 5\n3 2 5\n2 4 2\n1 2", "4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3"], "sample_outputs": ["6", "7"], "notes": "NoteIn the first sample there are two friendship groups: Hoses {1,\u20092} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1,\u20092,\u20093} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12\u2009>\u200911, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7."}, "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\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"}, {"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"} {"nl": {"description": "Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires \"plus\" and \"minus\". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the \"plus\" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.", "input_spec": "The single line of the input contains a sequence of characters \"+\" and \"-\" of length n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000). The i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) position of the sequence contains the character \"+\", if on the i-th step from the wall the \"plus\" wire runs above the \"minus\" wire, and the character \"-\" otherwise.", "output_spec": "Print either \"Yes\" (without the quotes) if the wires can be untangled or \"No\" (without the quotes) if the wires cannot be untangled.", "sample_inputs": ["-++-", "+-", "++", "-"], "sample_outputs": ["Yes", "No", "Yes", "No"], "notes": "NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the \"plus\" wire lower, thus eliminating the two crosses in the middle, and then draw it under the \"minus\" wire, eliminating also the remaining two crosses.In the second testcase the \"plus\" wire makes one full revolution around the \"minus\" wire. Thus the wires cannot be untangled: In the third testcase the \"plus\" wire simply runs above the \"minus\" wire twice in sequence. The wires can be untangled by lifting \"plus\" and moving it higher: In the fourth testcase the \"minus\" wire runs above the \"plus\" wire once. The wires cannot be untangled without moving the device itself: "}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "For a permutation P[1... N] of integers from 1 to N, function f is defined as follows: Let g(i) be the minimum positive integer j such that f(i,\u2009j)\u2009=\u2009i. We can show such j always exists.For given N,\u2009A,\u2009B, find a permutation P of integers from 1 to N such that for 1\u2009\u2264\u2009i\u2009\u2264\u2009N, g(i) equals either A or B.", "input_spec": "The only line contains three integers N,\u2009A,\u2009B (1\u2009\u2264\u2009N\u2009\u2264\u2009106,\u20091\u2009\u2264\u2009A,\u2009B\u2009\u2264\u2009N).", "output_spec": "If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.", "sample_inputs": ["9 2 5", "3 2 1"], "sample_outputs": ["6 5 8 3 4 1 9 2 7", "1 2 3"], "notes": "NoteIn the first example, g(1)\u2009=\u2009g(6)\u2009=\u2009g(7)\u2009=\u2009g(9)\u2009=\u20092 and g(2)\u2009=\u2009g(3)\u2009=\u2009g(4)\u2009=\u2009g(5)\u2009=\u2009g(8)\u2009=\u20095 In the second example, g(1)\u2009=\u2009g(2)\u2009=\u2009g(3)\u2009=\u20091"}, "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\n val Array(n, a, b) = readInts(3)\n\n var aX = 0\n var bX = (n - aX * a) / b\n while (aX * a <= n && aX * a + bX * b != n) {\n aX += 1\n bX = (n - aX * a) / b\n }\n\n if (aX * a + bX * b != n || bX < 0) println(-1)\n else {\n\n val as = Array.ofDim[Int](aX * a)\n var offset = 0\n\n for (aPos <- 0 until aX) {\n as(aPos * a) = a + offset\n var i = 1\n while (i < a) {\n as(aPos * a + i) = i + offset\n i += 1\n }\n offset += a\n }\n\n val bs = Array.ofDim[Int](bX * b)\n\n for (bPos <- 0 until bX) {\n bs(bPos * b) = b + offset\n var i = 1\n while (i < b) {\n bs(bPos * b + i) = i + offset\n i += 1\n }\n offset += b\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println((as ++ bs).mkString(\" \"))\n\n Console.flush\n }\n}\n"}], "negative_code": [], "src_uid": "138f7db4a858fb1efe817ee6491f83d9"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ ($$$n \\ge 3$$$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $$$[4, 11, 4, 4]$$$ all numbers except one are equal to $$$4$$$).Print the index of the element that does not equal others. The numbers in the array are numbered from one.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 100$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 100$$$). It is guaranteed that all the numbers except one in the $$$a$$$ array are the same.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the index of the element that is not equal to others.", "sample_inputs": ["4\n4\n11 13 11 11\n5\n1 4 4 4 4\n10\n3 3 3 3 10 3 3 3 3 3\n3\n20 20 10"], "sample_outputs": ["2\n1\n5\n3"], "notes": null}, "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.:+\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"}, {"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"} {"nl": {"description": "We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109\u2009+\u20097).", "input_spec": "Input contains several test cases. The first line contains two integers t and k (1\u2009\u2264\u2009t,\u2009k\u2009\u2264\u2009105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009105), describing the i-th test.", "output_spec": "Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["3 2\n1 3\n2 3\n4 4"], "sample_outputs": ["6\n5\n5"], "notes": "Note For K = 2 and length 1 Marmot can eat (R). For K = 2 and length 2 Marmot can eat (RR) and (WW). For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR). For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR). "}, "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": "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"}, {"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 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"}], "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"} {"nl": {"description": "Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $$$n$$$ flowers and so it looks like a pipe with $$$n$$$ holes. Arkady can only use the water that flows from the first hole.Arkady can block some of the holes, and then pour $$$A$$$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $$$s_1, s_2, \\ldots, s_n$$$. In other words, if the sum of sizes of non-blocked holes is $$$S$$$, and the $$$i$$$-th hole is not blocked, $$$\\frac{s_i \\cdot A}{S}$$$ liters of water will flow out of it.What is the minimum number of holes Arkady should block to make at least $$$B$$$ liters of water flow out of the first hole?", "input_spec": "The first line contains three integers $$$n$$$, $$$A$$$, $$$B$$$ ($$$1 \\le n \\le 100\\,000$$$, $$$1 \\le B \\le A \\le 10^4$$$)\u00a0\u2014 the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole. The second line contains $$$n$$$ integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$1 \\le s_i \\le 10^4$$$)\u00a0\u2014 the sizes of the holes.", "output_spec": "Print a single integer\u00a0\u2014 the number of holes Arkady should block.", "sample_inputs": ["4 10 3\n2 2 2 2", "4 80 20\n3 2 1 4", "5 10 10\n1000 1 1 1 1"], "sample_outputs": ["1", "0", "4"], "notes": "NoteIn the first example Arkady should block at least one hole. After that, $$$\\frac{10 \\cdot 2}{6} \\approx 3.333$$$ liters of water will flow out of the first hole, and that suits Arkady.In the second example even without blocking any hole, $$$\\frac{80 \\cdot 3}{10} = 24$$$ liters will flow out of the first hole, that is not less than $$$20$$$.In the third example Arkady has to block all holes except the first to make all water flow out of the first hole."}, "positive_code": [{"source_code": "\nobject WateringSystem extends App {\n import scala.collection.mutable.PriorityQueue\n import scala.io.Source\n\n //val src = Source.fromFile(\"data.txt\")\n val src = Source.stdin\n val lines = src.getLines\n \n def readLongs(): Array[Long] = {\n val line = if (lines.hasNext) lines.next else null\n if (line == null) throw new RuntimeException(\"Premature end of source encountered\")\n line.split(\" \").map(x => x.toLong)\n }\n def calculate(nHoles: Long, volIn: Long, volOut: Long, holeSizes: Array[Long]): Int = {\n var totalSizes = holeSizes.sum\n val firstHoleSize = holeSizes(0)\n var holeSizeQueue = new PriorityQueue[Long]() ++= holeSizes.tail\n var nplugged = 0\n while (volIn * firstHoleSize < volOut * totalSizes) {\n nplugged = nplugged + 1\n totalSizes = totalSizes - holeSizeQueue.dequeue()\n }\n nplugged\n }\n val Array(nHoles, volIn, volOut) = readLongs()\n val holeSizes = readLongs()\n val nplugged = calculate(nHoles, volIn, volOut, holeSizes)\n println(nplugged)\n \n}"}], "negative_code": [], "src_uid": "fd6b73a2c15f5b009fa350eea9bf0c0a"} {"nl": {"description": "Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.", "input_spec": "The first line contains the number n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the length of the glade. The second line contains n numbers a1,\u2009a2,\u2009...,\u2009an\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1,\u2009b2,\u2009...,\u2009bn\u00a0(1\u2009\u2264\u2009bi\u2009\u2264\u2009106) is the growth rate of mushrooms in the second row of the glade.", "output_spec": "Output one number \u2014 the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.", "sample_inputs": ["3\n1 2 3\n6 5 4", "3\n1 1000 10000\n10 100 100000"], "sample_outputs": ["70", "543210"], "notes": "NoteIn the first test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0\u00b71\u2009+\u20091\u00b72\u2009+\u20092\u00b73\u2009+\u20093\u00b74\u2009+\u20094\u00b75\u2009+\u20095\u00b76\u2009=\u200970.In the second test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0\u00b71\u2009+\u20091\u00b710\u2009+\u20092\u00b7100\u2009+\u20093\u00b71000\u2009+\u20094\u00b710000\u2009+\u20095\u00b7100000\u2009=\u2009543210."}, "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, \u3053\u3053\u304b\u3089\u3050\u3050\u3063\u3068\u56de\u3063\u305f\u6642\u306b\u3001\u4fc2\u65700\u30b9\u30bf\u30fc\u30c8\u3067\u7d2f\u7a4d\u3057\u305f\u5024\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] \u6a2a\u306e\u4f4d\u7f6e\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).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"}], "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] \u6a2a\u306e\u4f4d\u7f6e\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, \u3053\u3053\u304b\u3089\u3050\u3050\u3063\u3068\u56de\u3063\u305f\u6642\u306b\u3001\u4fc2\u65700\u30b9\u30bf\u30fc\u30c8\u3067\u7d2f\u7a4d\u3057\u305f\u5024\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, \u3053\u3053\u304b\u3089\u3050\u3050\u3063\u3068\u56de\u3063\u305f\u6642\u306b\u3001\u4fc2\u65700\u30b9\u30bf\u30fc\u30c8\u3067\u7d2f\u7a4d\u3057\u305f\u5024\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] \u6a2a\u306e\u4f4d\u7f6e\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"} {"nl": {"description": "A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \\le i \\le j \\le n$$$)\u00a0\u2014 $$$(p_i \\text{ OR } p_{i+1} \\text{ OR } \\ldots \\text{ OR } p_{j-1} \\text{ OR } p_{j}) \\ge j-i+1$$$, where $$$\\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$).", "output_spec": "For every test, output any good permutation of length $$$n$$$ on a separate line. ", "sample_inputs": ["3\n1\n3\n7"], "sample_outputs": ["1\n3 1 2\n4 3 5 2 7 1 6"], "notes": "NoteFor $$$n = 3$$$, $$$[3,1,2]$$$ is a good permutation. Some of the subarrays are listed below. $$$3\\text{ OR }1 = 3 \\geq 2$$$ $$$(i = 1,j = 2)$$$ $$$3\\text{ OR }1\\text{ OR }2 = 3 \\geq 3$$$ $$$(i = 1,j = 3)$$$ $$$1\\text{ OR }2 = 3 \\geq 2$$$ $$$(i = 2,j = 3)$$$ $$$1 \\geq 1$$$ $$$(i = 2,j = 2)$$$ Similarly, you can verify that $$$[4,3,5,2,7,1,6]$$$ is also good."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "1b3ac752bc9c0b5e20a76f028d4b3c15"} {"nl": {"description": "You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u < v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ \u2014 the labels of vertices it connects ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$) and the weight of the edge ($$$1 \\le w_i \\le 2 \\cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \\dots, q_m$$$ ($$$1 \\le q_i \\le 2 \\cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.", "output_spec": "Print $$$m$$$ integers \u2014 the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u < v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.", "sample_inputs": ["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"], "sample_outputs": ["21 7 15 21 3", "0 0", "1 3 3"], "notes": "NoteThe picture shows the tree from the first example: "}, "positive_code": [{"source_code": "//package codeforces.contest1213\n\nobject PathQueries {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val edgesList = (1 until n)\n .map { _ =>\n val Array(l, r, w) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (l min r, l max r, w)\n }\n .sortBy(_._3)\n .toList\n\n val parent = new Array[Int](n + 1)\n val setSize = new Array[Long](n + 1)\n\n def findParent(i: Int): Int =\n if (i == parent(i))\n i\n else {\n parent(i) = findParent(parent(i))\n parent(i)\n }\n\n (1 to n).foreach { i =>\n parent(i) = i\n setSize(i) = 1\n }\n\n @scala.annotation.tailrec\n def loop(edges: List[(Int, Int, Int)],\n max: Int,\n result: Long): (Long, List[(Int, Int, Int)]) =\n edges match {\n case ::(_ @(l, r, w), tl) if w <= max =>\n val lp = findParent(l)\n val rp = findParent(r)\n\n val newResult = result + setSize(lp) * setSize(rp)\n\n setSize(lp) += setSize(rp)\n parent(rp) = lp\n\n loop(tl, max, newResult)\n\n case _ => (result, edges)\n }\n\n val result = new Array[Long](m)\n\n io.StdIn.readLine\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .sortBy(_._1)\n .foldLeft((0l, edgesList)) {\n case ((acc, ls), (q, i)) =>\n val (r, remaining) = loop(ls, q, acc)\n result(i) = r\n (r, remaining)\n }\n\n println(result.mkString(\" \"))\n }\n\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1213\n\nobject PathQueries {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val edgesList = (1 until n)\n .map { _ =>\n val Array(l, r, w) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (l min r, l max r, w)\n }\n .sortBy(_._3)\n .toList\n\n val parent = new Array[Int](n + 1)\n val setSize = new Array[Int](n + 1)\n\n def findParent(i: Int): Int =\n if (i == parent(i))\n i\n else {\n parent(i) = findParent(i)\n parent(i)\n }\n\n (1 to n).foreach { i =>\n parent(i) = i\n setSize(i) = 1\n }\n\n @scala.annotation.tailrec\n def loop(edges: List[(Int, Int, Int)],\n max: Int,\n result: Int): (Int, List[(Int, Int, Int)]) =\n edges match {\n case ::(_ @(l, r, w), tl) if w <= max =>\n val lp = parent(l)\n val rp = parent(r)\n\n val newResult = result + setSize(lp) * setSize(rp)\n\n setSize(lp) += setSize(rp)\n parent(rp) = lp\n\n loop(tl, max, newResult)\n\n case _ => (result, edges)\n }\n\n val result = new Array[Int](m)\n\n io.StdIn.readLine\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .sortBy(_._1)\n .foldLeft((0, edgesList)) {\n case ((acc, ls), (q, i)) =>\n val (r, remaining) = loop(ls, q, acc)\n result(i) = r\n (r, remaining)\n }\n\n println(result.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject PathQueries {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val edgesList = (1 until n)\n .map { _ =>\n val Array(l, r, w) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (l min r, l max r, w)\n }\n .sortBy(_._3)\n .toList\n\n val parent = new Array[Int](n + 1)\n val setSize = new Array[Long](n + 1)\n\n def findParent(i: Int): Int =\n if (i == parent(i))\n i\n else {\n parent(i) = findParent(i)\n parent(i)\n }\n\n (1 to n).foreach { i =>\n parent(i) = i\n setSize(i) = 1\n }\n\n @scala.annotation.tailrec\n def loop(edges: List[(Int, Int, Int)],\n max: Int,\n result: Long): (Long, List[(Int, Int, Int)]) =\n edges match {\n case ::(_ @(l, r, w), tl) if w <= max =>\n val lp = parent(l)\n val rp = parent(r)\n\n val newResult = result + setSize(lp) * setSize(rp)\n\n setSize(lp) += setSize(rp)\n parent(rp) = lp\n\n loop(tl, max, newResult)\n\n case _ => (result, edges)\n }\n\n val result = new Array[Long](m)\n\n io.StdIn.readLine\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .sortBy(_._1)\n .foldLeft((0l, edgesList)) {\n case ((acc, ls), (q, i)) =>\n val (r, remaining) = loop(ls, q, acc)\n result(i) = r\n (r, remaining)\n }\n\n println(result.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject PathQueries {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val edgesList = (1 until n)\n .map { _ =>\n val Array(l, r, w) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (l min r, l max r, w)\n }\n .sortBy(_._3)\n .toList\n\n val parent = new Array[Int](n + 1)\n val setSize = new Array[Int](n + 1)\n\n def findParent(i: Int): Int =\n if (i == parent(i))\n i\n else {\n parent(i) = findParent(i)\n parent(i)\n }\n\n (1 to n).foreach { i =>\n parent(i) = i\n setSize(i) = 1\n }\n\n @scala.annotation.tailrec\n def loop(edges: List[(Int, Int, Int)],\n max: Int,\n result: Int): (Int, List[(Int, Int, Int)]) =\n edges match {\n case ::(_ @(l, r, w), tl) if w <= max =>\n val lp = parent(l)\n val rp = parent(r)\n\n val newResult = result + setSize(lp) * setSize(rp)\n\n setSize(lp) += setSize(rp)\n parent(rp) = lp\n\n loop(tl, max, newResult)\n\n case _ => (result, edges)\n }\n\n val result = new Array[Long](m)\n\n io.StdIn.readLine\n .split(\" \")\n .map(_.toInt)\n .zipWithIndex\n .sortBy(_._1)\n .foldLeft((0, edgesList)) {\n case ((acc, ls), (q, i)) =>\n val (r, remaining) = loop(ls, q, acc)\n result(i) = r\n (r, remaining)\n }\n\n println(result.mkString(\" \"))\n }\n\n}\n"}], "src_uid": "f94165f37e968442fa7f8be051018ad9"} {"nl": {"description": "Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents\u00a0\u2014 $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$\u00a0\u2014 the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n,m \\le 10^5$$$)\u00a0\u2014 number of riders and taxi drivers. The second line contains $$$n + m$$$ integers $$$x_1, x_2, \\ldots, x_{n+m}$$$ ($$$1 \\le x_1 < x_2 < \\ldots < x_{n+m} \\le 10^9$$$), where $$$x_i$$$ is the coordinate where the $$$i$$$-th resident lives. The third line contains $$$n + m$$$ integers $$$t_1, t_2, \\ldots, t_{n+m}$$$ ($$$0 \\le t_i \\le 1$$$). If $$$t_i = 1$$$, then the $$$i$$$-th resident is a taxi driver, otherwise $$$t_i = 0$$$. It is guaranteed that the number of $$$i$$$ such that $$$t_i = 1$$$ is equal to $$$m$$$.", "output_spec": "Print $$$m$$$ integers $$$a_1, a_2, \\ldots, a_{m}$$$, where $$$a_i$$$ is the answer for the $$$i$$$-th taxi driver. The taxi driver has the number $$$i$$$ if among all the taxi drivers he lives in the $$$i$$$-th smallest coordinate (see examples for better understanding).", "sample_inputs": ["3 1\n1 2 3 10\n0 0 1 0", "3 2\n2 3 4 5 6\n1 0 0 0 1", "1 4\n2 4 6 10 15\n1 1 1 1 0"], "sample_outputs": ["3", "2 1", "0 0 0 1"], "notes": "NoteIn the first example, we have only one taxi driver, which means an order from any of $$$n$$$ riders will go to him.In the second example, the first taxi driver lives at the point with the coordinate $$$2$$$, and the second one lives at the point with the coordinate $$$6$$$. Obviously, the nearest taxi driver to the rider who lives on the $$$3$$$ coordinate is the first one, and to the rider who lives on the coordinate $$$5$$$ is the second one. The rider who lives on the $$$4$$$ coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.In the third example, we have one rider and the taxi driver nearest to him is the fourth one."}, "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 // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\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.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"}, {"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"} {"nl": {"description": "You are given a matrix of size $$$n \\times n$$$ filled with lowercase English letters. You can change no more than $$$k$$$ letters in this matrix.Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $$$2n - 1$$$.Find the lexicographically smallest string that can be associated with a path after changing letters in at most $$$k$$$ cells of the matrix.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$, if the first different letter in $$$a$$$ and $$$b$$$ is smaller in $$$a$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2000$$$, $$$0 \\le k \\le n^2$$$) \u2014 the size of the matrix and the number of letters you can change. Each of the next $$$n$$$ lines contains a string of $$$n$$$ lowercase English letters denoting one row of the matrix.", "output_spec": "Output the lexicographically smallest string that can be associated with some valid path after changing no more than $$$k$$$ letters in the matrix.", "sample_inputs": ["4 2\nabcd\nbcde\nbcad\nbcde", "5 3\nbwwwz\nhrhdh\nsepsp\nsqfaf\najbvw", "7 6\nypnxnnp\npnxonpm\nnxanpou\nxnnpmud\nnhtdudu\nnpmuduh\npmutsnz"], "sample_outputs": ["aaabcde", "aaaepfafw", "aaaaaaadudsnz"], "notes": "NoteIn the first sample test case it is possible to change letters 'b' in cells $$$(2, 1)$$$ and $$$(3, 1)$$$ to 'a', then the minimum path contains cells $$$(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$$$. The first coordinate corresponds to the row and the second coordinate corresponds to the column."}, "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 * \u4e00\u756a\u30a2\u30eb\u30d5\u30a1\u30d9\u30c3\u30c8\u9806\u304c\u5c0f\u3055\u3044\u3082\u306e\u3060\u3051\u3092\u6b8b\u3059\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\u3067\u57cb\u3081\u308c\u308b\u4e00\u756a\u8ddd\u96e2\u304c\u5927\u304d\u304f\u306a\u308b\u5834\u6240\u306e\u6b21\u306b\u884c\u3051\u308b\u5834\u6240\u3092\u8fd4\u3059\n * @return (a\u306e\u500b\u6570, a\u306e\u6b21\u306e\u5019\u88dc)\n */\n def findMaxDist(): (Int, MinCharCoord) = {\n // \u53f3\u4e0b\u307e\u3067a\u3067\u57cb\u3081\u308c\u305f\u5834\u5408\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 // \u6df1\u3055\u3067BFS\u3059\u308b\u611f\u3058\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 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"}], "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 * \u4e00\u756a\u30a2\u30eb\u30d5\u30a1\u30d9\u30c3\u30c8\u9806\u304c\u5c0f\u3055\u3044\u3082\u306e\u3060\u3051\u3092\u6b8b\u3059\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\u3067\u57cb\u3081\u308c\u308b\u4e00\u756a\u8ddd\u96e2\u304c\u5927\u304d\u304f\u306a\u308b\u5834\u6240\u306e\u6b21\u306b\u884c\u3051\u308b\u5834\u6240\u3092\u8fd4\u3059\n * @return (a\u306e\u500b\u6570, a\u306e\u6b21\u306e\u5019\u88dc)\n */\n def findMaxDist(): (Int, MinCharCoord) = {\n // \u53f3\u4e0b\u307e\u3067a\u3067\u57cb\u3081\u308c\u305f\u5834\u5408\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 // \u6df1\u3055\u3067BFS\u3059\u308b\u611f\u3058\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 // \u6df1\u3055\u3067BFS\u3059\u308b\u611f\u3058\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"} {"nl": {"description": "Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length\u00a0$$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 50$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the array that Phoenix currently has. This array may or may not be already beautiful.", "output_spec": "For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \\le m \\le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \\le b_i \\le n$$$)\u00a0\u2014 a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.", "sample_inputs": ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"], "sample_outputs": ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"], "notes": "NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also."}, "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, 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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s,\u2009t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s,\u2009t) can be used to define the function of Vasya distance \u03c1(s,\u2009t): where is obtained from string s, by applying left circular shift i times. For example, \u03c1(\"AGC\",\u2009\"CGT\")\u2009=\u2009 h(\"AGC\",\u2009\"CGT\")\u2009+\u2009h(\"AGC\",\u2009\"GTC\")\u2009+\u2009h(\"AGC\",\u2009\"TCG\")\u2009+\u2009 h(\"GCA\",\u2009\"CGT\")\u2009+\u2009h(\"GCA\",\u2009\"GTC\")\u2009+\u2009h(\"GCA\",\u2009\"TCG\")\u2009+\u2009 h(\"CAG\",\u2009\"CGT\")\u2009+\u2009h(\"CAG\",\u2009\"GTC\")\u2009+\u2009h(\"CAG\",\u2009\"TCG\")\u2009=\u2009 1\u2009+\u20091\u2009+\u20090\u2009+\u20090\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20090\u2009+\u20091\u2009=\u20096Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109\u2009+\u20097.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line of the input contains a single string of length n, consisting of characters \"ACGT\".", "output_spec": "Print a single number\u00a0\u2014 the answer modulo 109\u2009+\u20097.", "sample_inputs": ["1\nC", "2\nAG", "3\nTTT"], "sample_outputs": ["1", "4", "1"], "notes": "NotePlease note that if for two distinct strings t1 and t2 values \u03c1(s,\u2009t1) \u0438 \u03c1(s,\u2009t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is \u03c1(\"C\",\u2009\"C\")\u2009=\u20091, for the remaining strings t of length 1 the value of \u03c1(s,\u2009t) is 0.In the second sample, \u03c1(\"AG\",\u2009\"AG\")\u2009=\u2009\u03c1(\"AG\",\u2009\"GA\")\u2009=\u2009\u03c1(\"AG\",\u2009\"AA\")\u2009=\u2009\u03c1(\"AG\",\u2009\"GG\")\u2009=\u20094.In the third sample, \u03c1(\"TTT\",\u2009\"TTT\")\u2009=\u200927"}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given two integers $$$A$$$ and $$$B$$$, calculate the number of pairs $$$(a, b)$$$ such that $$$1 \\le a \\le A$$$, $$$1 \\le b \\le B$$$, and the equation $$$a \\cdot b + a + b = conc(a, b)$$$ is true; $$$conc(a, b)$$$ is the concatenation of $$$a$$$ and $$$b$$$ (for example, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). $$$a$$$ and $$$b$$$ should not contain leading zeroes.", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Each test case contains two integers $$$A$$$ and $$$B$$$ $$$(1 \\le A, B \\le 10^9)$$$.", "output_spec": "Print one integer \u2014 the number of pairs $$$(a, b)$$$ such that $$$1 \\le a \\le A$$$, $$$1 \\le b \\le B$$$, and the equation $$$a \\cdot b + a + b = conc(a, b)$$$ is true.", "sample_inputs": ["3\n\n1 11\n\n4 2\n\n191 31415926"], "sample_outputs": ["1\n0\n1337"], "notes": "NoteThere is only one suitable pair in the first test case: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \\cdot 9 = 19$$$)."}, "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 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"}, {"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 scala.annotation.tailrec\nimport scala.io.StdIn._\nobject Main extends App {\n\n for (_ \u2190 0 until readInt) {\n val Array(a, b) = readLine.trim.split(' ').map(_.toLong)\n println(\n (1 to digit(b)).map(d \u21d2 power(10, d) - 1).count(_ <= b) * a\n )\n }\n def power(base: Long, exp: Int): Long = {\n exp match {\n case 0 \u21d2 1L\n case 1 \u21d2 base\n case _ \u21d2 power(base, exp & 1) * power(base * base, exp >> 1)\n }\n }\n def digit(value: Long): Int = {\n value match {\n case 0 \u21d2 0\n case _ \u21d2 1 + digit(value / 10)\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"} {"nl": {"description": "Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $$$100$$$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree \u2014 a connected undirected graph consisting of $$$n$$$ vertices connected by $$$n - 1$$$ edges. The tree is rooted at vertex $$$1$$$. A vertex $$$u$$$ is called an ancestor of $$$v$$$ if it lies on the shortest path between the root and $$$v$$$. In particular, a vertex is an ancestor of itself.Each vertex $$$v$$$ is assigned its beauty $$$x_v$$$ \u2014 a non-negative integer not larger than $$$10^{12}$$$. This allows us to define the beauty of a path. Let $$$u$$$ be an ancestor of $$$v$$$. Then we define the beauty $$$f(u, v)$$$ as the greatest common divisor of the beauties of all vertices on the shortest path between $$$u$$$ and $$$v$$$. Formally, if $$$u=t_1, t_2, t_3, \\dots, t_k=v$$$ are the vertices on the shortest path between $$$u$$$ and $$$v$$$, then $$$f(u, v) = \\gcd(x_{t_1}, x_{t_2}, \\dots, x_{t_k})$$$. Here, $$$\\gcd$$$ denotes the greatest common divisor of a set of numbers. In particular, $$$f(u, u) = \\gcd(x_u) = x_u$$$.Your task is to find the sum$$$$$$ \\sum_{u\\text{ is an ancestor of }v} f(u, v). $$$$$$As the result might be too large, please output it modulo $$$10^9 + 7$$$.Note that for each $$$y$$$, $$$\\gcd(0, y) = \\gcd(y, 0) = y$$$. In particular, $$$\\gcd(0, 0) = 0$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100\\,000$$$) \u2014 the number of vertices in the tree. The following line contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$0 \\le x_i \\le 10^{12}$$$). The value $$$x_v$$$ denotes the beauty of vertex $$$v$$$. The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$a, b$$$ ($$$1 \\le a, b \\le n$$$, $$$a \\neq b$$$) \u2014 the vertices connected by a single edge.", "output_spec": "Output the sum of the beauties on all paths $$$(u, v)$$$ such that $$$u$$$ is ancestor of $$$v$$$. This sum should be printed modulo $$$10^9 + 7$$$.", "sample_inputs": ["5\n4 5 6 0 8\n1 2\n1 3\n1 4\n4 5", "7\n0 2 3 0 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"], "sample_outputs": ["42", "30"], "notes": "NoteThe following figure shows all $$$10$$$ possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to $$$42$$$: "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val x = nal(n)\n val (from, to) = na2(n - 1, -1)\n val g = packUGraph(n, from, to)\n val (_, p, q) = traceBfs(g)\n type Value = mutable.Map[Long, Int]\n def zero: Value = mutable.Map().withDefaultValue(0) // \u5909\u66f4\u52a0\u3048\u308b\u306e\u3067def\u306b\u306a\u3063\u3066\u308b\n val dp = Array.fill[Value](n)(zero)\n\n def merge(v: Value, x: Long): Value = {\n val res = zero\n res(x) = 1\n val it = v.iterator\n while(it.hasNext) {\n val (g, cnt) = it.next()\n res(gcd(g, x)) += cnt\n }\n res\n }\n\n var ans = 0L\n REP(n) { i =>\n val v = q(i)\n if (p(v) != -1) {\n dp(v) = merge(dp(p(v)), x(v))\n } else {\n dp(v) = zero + (x(v) -> 1)\n }\n val it = dp(v).iterator\n while(it.hasNext) {\n val (g, cnt) = it.next()\n ans += g % MOD * cnt % MOD\n }\n }\n debug(dp.mkString(\" \"))\n out.println(ans % MOD)\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a\n else gcd(b, a % b)\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": "5179d7554a08d713da7597db41f0ed43"} {"nl": {"description": "Slime has a sequence of positive integers $$$a_1, a_2, \\ldots, a_n$$$.In one operation Orac can choose an arbitrary subsegment $$$[l \\ldots r]$$$ of this sequence and replace all values $$$a_l, a_{l + 1}, \\ldots, a_r$$$ to the value of median of $$$\\{a_l, a_{l + 1}, \\ldots, a_r\\}$$$.In this problem, for the integer multiset $$$s$$$, the median of $$$s$$$ is equal to the $$$\\lfloor \\frac{|s|+1}{2}\\rfloor$$$-th smallest number in it. For example, the median of $$$\\{1,4,4,6,5\\}$$$ is $$$4$$$, and the median of $$$\\{1,7,5,8\\}$$$ is $$$5$$$.Slime wants Orac to make $$$a_1 = a_2 = \\ldots = a_n = k$$$ using these operations.Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.", "input_spec": "The first line of the input is a single integer $$$t$$$: the number of queries. The first line of each query contains two integers $$$n\\ (1\\le n\\le 100\\,000)$$$ and $$$k\\ (1\\le k\\le 10^9)$$$, the second line contains $$$n$$$ positive integers $$$a_1,a_2,\\dots,a_n\\ (1\\le a_i\\le 10^9)$$$ The total sum of $$$n$$$ is at most $$$100\\,000$$$.", "output_spec": "The output should contain $$$t$$$ lines. The $$$i$$$-th line should be equal to 'yes' if it is possible to make all integers $$$k$$$ in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.", "sample_inputs": ["5\n5 3\n1 5 2 6 1\n1 6\n6\n3 2\n1 2 3\n4 3\n3 1 2 3\n10 3\n1 2 3 4 5 6 7 8 9 10"], "sample_outputs": ["no\nyes\nyes\nno\nyes"], "notes": "NoteIn the first query, Orac can't turn all elements into $$$3$$$.In the second query, $$$a_1=6$$$ is already satisfied.In the third query, Orac can select the complete array and turn all elements into $$$2$$$.In the fourth query, Orac can't turn all elements into $$$3$$$.In the fifth query, Orac can select $$$[1,6]$$$ at first and then select $$$[2,10]$$$."}, "positive_code": [{"source_code": "object D 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)\n\n val ans =\n an.contains(k) && an.sliding(3).exists {\n case Array(x, y, z) => x >= k && y <= k && z >= k || x >= k && y >= k || y >= k && z >= k\n case Array(x, y) => x == k && y >= k || y == k && x >= k\n case Array(_) => true\n }\n\n if (ans) println(\"yes\")\n else println(\"no\")\n }\n}\n"}], "negative_code": [{"source_code": "object D 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)\n\n val ans =\n an.contains(k) && an.sliding(3).exists {\n case Array(x, y, z) => x >= k && y <= k && z >= k || x >= k && y >= k || y >= k && z >= k\n case _ => true\n }\n\n if (ans) println(\"yes\")\n else println(\"no\")\n }\n}\n"}], "src_uid": "2d988fe01f91847dcad52111c468c0ba"} {"nl": {"description": "Asya loves animals very much. Recently, she purchased $$$n$$$ kittens, enumerated them from $$$1$$$ and $$$n$$$ and then put them into the cage. The cage consists of one row of $$$n$$$ cells, enumerated with integers from $$$1$$$ to $$$n$$$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $$$n - 1$$$ partitions originally. Initially, each cell contained exactly one kitten with some number.Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $$$i$$$, Asya: Noticed, that the kittens $$$x_i$$$ and $$$y_i$$$, located in neighboring cells want to play together. Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after $$$n - 1$$$ days the cage contained a single cell, having all kittens.For every day, Asya remembers numbers of kittens $$$x_i$$$ and $$$y_i$$$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $$$n$$$ cells.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 150\\,000$$$)\u00a0\u2014 the number of kittens. Each of the following $$$n - 1$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$, $$$x_i \\ne y_i$$$)\u00a0\u2014 indices of kittens, which got together due to the border removal on the corresponding day. It's guaranteed, that the kittens $$$x_i$$$ and $$$y_i$$$ were in the different cells before this day.", "output_spec": "For every cell from $$$1$$$ to $$$n$$$ print a single integer\u00a0\u2014 the index of the kitten from $$$1$$$ to $$$n$$$, who was originally in it. All printed integers must be distinct. It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.", "sample_inputs": ["5\n1 4\n2 5\n3 1\n4 5"], "sample_outputs": ["3 1 4 2 5"], "notes": "NoteThe answer for the example contains one of several possible initial arrangements of the kittens.The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells. "}, "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 uf = new UnionFind(N)\n val sets = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(N) { i =>\n sets(i) += i\n }\n\n def merge(s1: ArrayBuffer[Int], s2: ArrayBuffer[Int]): ArrayBuffer[Int] = {\n if (s1.length > s2.length) {\n s1 ++= s2\n s1\n } else {\n s2 ++= s1\n s2\n }\n }\n\n REP(N - 1) { _ =>\n val v, u = ni() - 1\n val s1 = sets(uf.find(v))\n val s2 = sets(uf.find(u))\n uf.unite(v, u)\n sets(uf.find(u)) = merge(s1, s2)\n }\n\n val ans = sets(uf.find(0))\n out.println(ans.map(_+1).mkString(\" \"))\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 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": [], "src_uid": "2c665f95370058bc7fdec405db7d155d"} {"nl": {"description": "Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase \"how are you\" he can type \"hhoow aaaare yyoouu\". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. ", "input_spec": "The input data consists of a single line to be processed. The length of the line is from 1 to 2\u00b7105 characters inclusive. The string contains only lowercase Latin letters. ", "output_spec": "Print the given string after it is processed. It is guaranteed that the result will contain at least one character.", "sample_inputs": ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"], "sample_outputs": ["wre", "rezy", "a"], "notes": null}, "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.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"}, {"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"} {"nl": {"description": "The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.", "input_spec": "The first line contains space-separated integers n and m \u2014 the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n. It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.", "output_spec": "Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on. If there are multiple correct orders, you are allowed to print any of them.", "sample_inputs": ["2 1\n1 2", "3 3\n1 2\n2 3\n3 1"], "sample_outputs": ["2 1", "2 1 3"], "notes": null}, "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 D 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 val adj = Array.fill(n){ mutable.ArrayBuffer.empty[Int] }\n \n for (i <- 0 until m) {\n val Array(a, b) = readInts(2)\n adj(b - 1) += a - 1\n }\n \n val color = Array.fill(n)(0)\n var res = List[Int]()\n \n for (i <- adj.indices if (color(i) == 0)) dfsVisit(i)\n \n def dfsVisit(u: Int): Unit = {\n \n color(u) = 1\n for (v <- adj(u) if color(v) == 0) dfsVisit(v)\n \n res = (u + 1) :: res\n }\n\n println(res.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "412c9de03713ca8b5d1461d0213b8eec"} {"nl": {"description": "Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000), number of GukiZ's students. The second line contains n numbers a1,\u2009a2,\u2009... an (1\u2009\u2264\u2009ai\u2009\u2264\u20092000) where ai is the rating of i-th student (1\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.", "sample_inputs": ["3\n1 3 3", "1\n1", "5\n3 5 3 4 5"], "sample_outputs": ["3 1 1", "1", "4 1 4 3 1"], "notes": "NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position."}, "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": "\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"}, {"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) 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": "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 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 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"}, {"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"}, {"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 = 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 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\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": "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"}], "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"} {"nl": {"description": "You are given $$$n$$$ strings $$$a_1, a_2, \\ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \\ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \\le n \\le 10$$$) and $$$m$$$ ($$$1 \\le m \\le 10$$$)\u00a0\u2014 the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print \"-1\" (\"minus one\", without quotes).", "sample_inputs": ["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"], "sample_outputs": ["abab\n-1\naaa\nab\nz"], "notes": "NoteThe first test case was explained in the statement.In the second test case, the answer does not exist."}, "positive_code": [{"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 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 m = ni()\n val s = Array.ofDim[Char](n, m)\n REP(n) { i =>\n s(i) = ns(m)\n }\n\n if(m == 1) {\n out.println('z')\n } else {\n var ans: Option[String] = None\n REP(m) { j =>\n REP(26) { c =>\n val S = s(0).clone()\n S(j) = (c + 'a').toChar\n var skip = false\n REP(n) { u =>\n var cnt = 0\n REP(m) { v =>\n if (S(v) != s(u)(v)) cnt += 1\n }\n if(cnt > 1) skip = true\n }\n if(!skip && ans.isEmpty) ans = Some(S.mkString(\"\"))\n }\n }\n if(ans.isEmpty) {\n out.println(-1)\n } else out.println(ans.get)\n }\n }\n }\n}\n"}], "negative_code": [{"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 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 m = ni()\n val s = Array.ofDim[Char](n, m)\n REP(n) { i =>\n s(i) = ns(m)\n }\n\n if(m == 1) {\n out.println('z')\n } else {\n var ans: Option[String] = None\n REP(m) { j =>\n REP(26) { c =>\n val S = s(0)\n S(j) = (c + 'a').toChar\n var skip = false\n REP(n) { u =>\n var cnt = 0\n REP(m) { v =>\n if (S(v) != s(u)(v)) cnt += 1\n }\n if(cnt > 1) skip = true\n }\n if(!skip && ans.isEmpty) ans = Some(S.mkString(\"\"))\n }\n }\n if(ans.isEmpty) {\n out.println(-1)\n } else out.println(ans.get)\n }\n }\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 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 m = ni()\n val s = Array.ofDim[Char](n, m)\n REP(n) { i =>\n s(i) = ns(m)\n }\n\n if(m == 1) {\n out.println('z')\n } else {\n var ans: Option[String] = None\n REP(m) { j =>\n REP(26) { c =>\n val S = s(0)\n S(j) = (c + 'a').toChar\n var skip = false\n REP(n) { u =>\n if(!skip) {\n var cnt = 0\n REP(m) { v =>\n if (S(v) != s(u)(v)) cnt += 1\n }\n if(cnt > 1) skip = true\n }\n }\n if(!skip && ans.isEmpty) ans = Some(S.mkString(\"\"))\n }\n }\n if(ans.isEmpty) {\n out.println(-1)\n } else out.println(ans.get)\n }\n }\n }\n}\n"}], "src_uid": "8d4cdf75f726b59a8fcc374e1417374a"} {"nl": {"description": "Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1,\u2009a2,\u2009...,\u2009an of length n, that the following condition fulfills: a2\u2009-\u2009a1\u2009=\u2009a3\u2009-\u2009a2\u2009=\u2009a4\u2009-\u2009a3\u2009=\u2009...\u2009=\u2009ai\u2009+\u20091\u2009-\u2009ai\u2009=\u2009...\u2009=\u2009an\u2009-\u2009an\u2009-\u20091.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n\u2009+\u20091 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cards. The next line contains the sequence of integers \u2014 the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108.", "output_spec": "If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples).", "sample_inputs": ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"], "sample_outputs": ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string \"aba\" has six substrings: \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.", "input_spec": "The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.", "output_spec": "Print the only integer \u2014 the minimum number of changes that Dr. Moriarty has to make with the string that you choose.", "sample_inputs": ["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"], "sample_outputs": ["0", "1", "7"], "notes": "NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth (\"bca\") or from fifth to sixth (\"bc\"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message."}, "positive_code": [{"source_code": "object C {\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines()\n val src = lines.next\n val target = lines.next\n \n val padding = \"X\" * target.length\n val search = padding + src + padding\n \n var best = Int.MaxValue \n \n for (i <- 0 to src.length + target.length) {\n var score = 0 \n for (j <- 0 to target.length-1)\n if (search.charAt(i+j) != target.charAt(j)) score += 1\n if (score < best)\n best = score\n }\n \n println (best)\n }\n}"}], "negative_code": [], "src_uid": "430486b13b2f3be12cf47fac105056ae"} {"nl": {"description": "Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$) \u2014 the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10\\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.", "output_spec": "Print the index of the day when Polycarp will celebrate the equator.", "sample_inputs": ["4\n1 3 2 1", "6\n2 2 2 2 2 2"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training."}, "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": "\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"}, {"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"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$, both consisting of $$$n$$$ integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$; $$$i \\neq j$$$) and swap $$$a_i$$$ with $$$a_j$$$ and $$$b_i$$$ with $$$b_j$$$. You have to perform the swap in both arrays.You are allowed to perform at most $$$10^4$$$ moves (possibly, zero). Can you make both arrays sorted in a non-decreasing order at the end? If you can, print any sequence of moves that makes both arrays sorted.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the first array. The third line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le n$$$)\u00a0\u2014 the second array.", "output_spec": "For each testcase, print the answer. If it's impossible to make both arrays sorted in a non-decreasing order in at most $$$10^4$$$ moves, print -1. Otherwise, first, print the number of moves $$$k$$$ $$$(0 \\le k \\le 10^4)$$$. Then print $$$i$$$ and $$$j$$$ for each move $$$(1 \\le i, j \\le n$$$; $$$i \\neq j)$$$. If there are multiple answers, then print any of them. You don't have to minimize the number of moves.", "sample_inputs": ["3\n\n2\n\n1 2\n\n1 2\n\n2\n\n2 1\n\n1 2\n\n4\n\n2 3 1 2\n\n2 3 2 3"], "sample_outputs": ["0\n-1\n3\n3 1\n3 2\n4 3"], "notes": null}, "positive_code": [{"source_code": "import java.util\r\nimport scala.io.StdIn\r\n\r\ncase class item(var a:Int,var b:Int)\r\ncase class move(i:Int,j:Int)\r\n\r\nobject Main extends App {\r\n val t = StdIn.readLine().toInt\r\n for (_ <- 0 until t) {\r\n var impossible = false\r\n var moves = new util.ArrayList[move]()\r\n\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toInt)\r\n val b = StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n val c = (0 until n).map(i => item(a(i),b(i)))\r\n for (i<-1 until n) {\r\n var min_i = i-1\r\n var min_v = c(min_i)\r\n for(j<-i until n){\r\n if (c(j).a < min_v.a || (c(j).a == min_v.a && c(j).b < min_v.b)) {\r\n min_i = j\r\n min_v = c(min_i)\r\n }\r\n }\r\n\r\n if (i-1 != min_i) {\r\n moves.add(move(i,min_i+1))\r\n c(i-1).a ^= c(min_i).a\r\n c(min_i).a ^= c(i-1).a\r\n c(i-1).a ^= c(min_i).a\r\n c(i-1).b ^= c(min_i).b\r\n c(min_i).b ^= c(i-1).b\r\n c(i-1).b ^= c(min_i).b\r\n }\r\n if (i-2 >= 0 && c(i-1).b < c(i-2).b) impossible = true\r\n }\r\n if (n-1 >= 0 && c(n-1).b < c(n-2).b) impossible = true\r\n if (impossible) println(-1)\r\n else {\r\n println(moves.size())\r\n moves.forEach(x=>println(x.i + \" \" + x.j))\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import java.util\r\nimport scala.io.StdIn\r\n\r\ncase class item(var a:Int,var b:Int)\r\ncase class move(i:Int,j:Int)\r\n\r\nobject Main extends App {\r\n val t = StdIn.readLine().toInt\r\n for (_ <- 0 until t) {\r\n var impossible = false\r\n var moves = new util.ArrayList[move]()\r\n\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toInt)\r\n val b = StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n val c = (0 until n).map(i => item(a(i),b(i)))\r\n for (i<-1 until n) {\r\n var min_i = i-1\r\n var min_v = c(min_i)\r\n for(j<-i until n){\r\n if (c(j).a < min_v.a || (c(j).a == min_v.a && c(j).b < min_v.b)) {\r\n min_i = j\r\n min_v = c(min_i)\r\n }\r\n }\r\n\r\n if (i-1 != min_i) {\r\n moves.add(move(i,min_i+1))\r\n c(i-1).a ^= c(min_i).a\r\n c(min_i).a ^= c(i-1).a\r\n c(i-1).a ^= c(min_i).a\r\n c(i-1).b ^= c(min_i).b\r\n c(min_i).b ^= c(i-1).b\r\n c(i-1).b ^= c(min_i).b\r\n }\r\n if (i-2 >= 0 && c(i-1).b < c(i-2).b) impossible = true\r\n }\r\n if (n-1 >= 0 && c(n-1).b < c(n-2).b) impossible = true\r\n if (impossible) println(-1)\r\n else {\r\n println(moves.size())\r\n moves.forEach(x=>println(x.i + \" \" + x.j))\r\n println(c)\r\n }\r\n }\r\n}\r\n"}, {"source_code": "import java.util\r\nimport scala.io.StdIn\r\n\r\ncase class item(var a:Int,var b:Int)\r\ncase class move(i:Int,j:Int)\r\n\r\nobject Main extends App {\r\n val t = StdIn.readLine().toInt\r\n for (_ <- 0 until t) {\r\n var impossible = false\r\n var moves = new util.ArrayList[move]()\r\n\r\n val n = StdIn.readLine().toInt\r\n val a = StdIn.readLine().split(\" \").map(_.toInt)\r\n val b = StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n val c = (0 until n).map(i => item(a(i),b(i)))\r\n for (i<-1 until n) {\r\n var min_i = i-1\r\n var min_v = c(min_i)\r\n for(j<-i until n){\r\n if (c(j).a < min_v.a || (c(j).a == min_v.a && c(j).b < min_v.b)) {\r\n min_i = j\r\n min_v = c(min_i)\r\n }\r\n }\r\n\r\n if (i-1 != min_i) {\r\n moves.add(move(i,min_i+1))\r\n c(i-1).a ^= c(min_i).a\r\n c(min_i).a ^= c(i-1).a\r\n c(i-1).a ^= c(min_i).a\r\n c(i-1).b ^= c(min_i).b\r\n c(min_i).b ^= c(i-1).b\r\n c(i-1).b ^= c(min_i).b\r\n }\r\n if (c(i).b < c(i-1).b) impossible = true\r\n }\r\n if (impossible) println(-1)\r\n else {\r\n println(moves.size())\r\n moves.forEach(x=>println(x.i + \" \" + x.j))\r\n }\r\n }\r\n}"}], "src_uid": "c1f13141a70c7b9228015c0382c7ca71"} {"nl": {"description": "Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of streets and avenues in Munhattan. Each of the next n lines contains m integers cij (1\u2009\u2264\u2009cij\u2009\u2264\u2009109) \u2014 the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.", "output_spec": "Print the only integer a \u2014 the cost of the dinner for Jack and Emma.", "sample_inputs": ["3 4\n4 1 3 5\n2 2 2 2\n5 4 5 1", "3 3\n1 2 3\n2 3 1\n3 1 2"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "f2142bc2f44e5d8b77f8561c29038a73"} {"nl": {"description": "Three guys play a game: first, each person writes down $$$n$$$ distinct words of length $$$3$$$. Then, they total up the number of points as follows: if a word was written by one person\u00a0\u2014 that person gets 3 points, if a word was written by two people\u00a0\u2014 each of the two gets 1 point, if a word was written by all\u00a0\u2014 nobody gets any points. In the end, how many points does each player have?", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the number of words written by each person. The following three lines each contain $$$n$$$ distinct strings\u00a0\u2014 the words written by each person. Each string consists of $$$3$$$ lowercase English characters.", "output_spec": "For each test case, output three space-separated integers\u00a0\u2014 the number of points each of the three guys earned. You should output the answers in the same order as the input; the $$$i$$$-th integer should be the number of points earned by the $$$i$$$-th guy.", "sample_inputs": ["3\n\n1\n\nabc\n\ndef\n\nabc\n\n3\n\norz for qaq\n\nqaq orz for\n\ncod for ces\n\n5\n\niat roc hem ica lly\n\nbac ter iol ogi sts\n\nbac roc lly iol iat"], "sample_outputs": ["1 3 1 \n2 2 6 \n9 11 5"], "notes": "NoteIn the first test case: The word $$$\\texttt{abc}$$$ was written by the first and third guys\u00a0\u2014 they each get $$$1$$$ point. The word $$$\\texttt{def}$$$ was written by the second guy only\u00a0\u2014 he gets $$$3$$$ points. "}, "positive_code": [{"source_code": "object _1722C 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 p1, p2, p3 = io.read[List, String](n)\n val tp1 = p1.toSet\n val tp2 = p2.toSet\n val tp3 = p3.toSet\n\n def score(p: List[String], o1: Set[String], o2: Set[String]) = {\n p.map({ x =>\n (o1.contains(x).to[Int] + o2.contains(x).to[Int]) match {\n case 0 => 3\n case 1 => 1\n case 2 => 0\n }\n }).sum\n }\n\n io.write(\n score(p1, tp2, tp3),\n score(p2, tp3, tp1),\n score(p3, tp1, tp2),\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": "f8a89510fefbbc8e5698efe8a0c30927"} {"nl": {"description": "Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $$$n$$$ types of candies, there are $$$a_i$$$ candies of the type $$$i$$$ ($$$1 \\le i \\le n$$$).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of input test cases. The following is a description of $$$t$$$ test cases of input, two lines for each. The first line of the case contains the single number $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of types of candies in the package. The second line of the case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the number of candies of the type $$$i$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer, output \"YES\" if Vlad can eat candy as planned, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["6\n2\n2 3\n1\n2\n5\n1 6 2 4 3\n4\n2 2 2 1\n3\n1 1000000000 999999999\n1\n1"], "sample_outputs": ["YES\nNO\nNO\nYES\nYES\nYES"], "notes": "NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type $$$2$$$, it is the most frequent, now $$$a = [2, 2]$$$; a candy of the type $$$1$$$, there are the same number of candies of the type $$$2$$$, but we just ate one, now $$$a = [1, 2]$$$; a candy of the type $$$2$$$, it is the most frequent, now $$$a = [1, 1]$$$; a candy of the type $$$1$$$, now $$$a = [0, 1]$$$; a candy of the type $$$2$$$, now $$$a = [0, 0]$$$ and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type $$$2$$$ will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type $$$2$$$ again."}, "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 }\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}"}, {"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"} {"nl": {"description": "Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day $$$1$$$, there is one bacterium with mass $$$1$$$.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $$$m$$$ splits, it becomes two bacteria of mass $$$\\frac{m}{2}$$$ each. For example, a bacterium of mass $$$3$$$ can split into two bacteria of mass $$$1.5$$$.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $$$n$$$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$)\u00a0\u2014 the sum of bacteria masses that Phoenix is interested in. ", "output_spec": "For each test case, if there is no way for the bacteria to exactly achieve total mass $$$n$$$, print -1. Otherwise, print two lines. The first line should contain an integer $$$d$$$ \u00a0\u2014 the minimum number of nights needed. The next line should contain $$$d$$$ integers, with the $$$i$$$-th integer representing the number of bacteria that should split on the $$$i$$$-th day. If there are multiple solutions, print any.", "sample_inputs": ["3\n9\n11\n2"], "sample_outputs": ["3\n1 0 2 \n3\n1 1 2\n1\n0"], "notes": "NoteIn the first test case, the following process results in bacteria with total mass $$$9$$$: Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$ each. Night $$$1$$$: All bacteria's mass increases by one. There are now two bacteria with mass $$$1.5$$$. Day $$$2$$$: None split. Night $$$2$$$: There are now two bacteria with mass $$$2.5$$$. Day $$$3$$$: Both bacteria split. There are now four bacteria with mass $$$1.25$$$. Night $$$3$$$: There are now four bacteria with mass $$$2.25$$$. The total mass is $$$2.25+2.25+2.25+2.25=9$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 9 in 3 nights.$$$ $$$In the second test case, the following process results in bacteria with total mass $$$11$$$: Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$. Night $$$1$$$: There are now two bacteria with mass $$$1.5$$$. Day $$$2$$$: One bacterium splits. There are now three bacteria with masses $$$0.75$$$, $$$0.75$$$, and $$$1.5$$$. Night $$$2$$$: There are now three bacteria with masses $$$1.75$$$, $$$1.75$$$, and $$$2.5$$$. Day $$$3$$$: The bacteria with mass $$$1.75$$$ and the bacteria with mass $$$2.5$$$ split. There are now five bacteria with masses $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$, and $$$1.75$$$. Night $$$3$$$: There are now five bacteria with masses $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$, and $$$2.75$$$. The total mass is $$$1.875+1.875+2.25+2.25+2.75=11$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 11 in 3 nights.$$$ $$$In the third test case, the bacterium does not split on day $$$1$$$, and then grows to mass $$$2$$$ during night $$$1$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 3 \\cdot 10^5$$$) \u2014 the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 3 \\cdot 10^5, 0 \\le m \\le 3 \\cdot 10^5$$$) \u2014 the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \\le u_i, v_i \\le n; u_i \\neq v_i$$$) \u2014 indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\\sum\\limits_{i=1}^{t} n \\le 3 \\cdot 10^5$$$ and $$$\\sum\\limits_{i=1}^{t} m \\le 3 \\cdot 10^5$$$.", "output_spec": "For each test print one line, containing one integer \u2014 the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.", "sample_inputs": ["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"], "sample_outputs": ["4\n0"], "notes": "NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers."}, "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 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 // \u5168\u30a8\u30c3\u30b8\u306e\u4e21\u7aef\u306e\u6df1\u3055\u306e\u5076\u5947\u304c\u7570\u306a\u3063\u3066\u3044\u308b\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 \u30ce\u30fc\u30c9\u6570\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": "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 // \u5168\u30a8\u30c3\u30b8\u306e\u4e21\u7aef\u306e\u6df1\u3055\u306e\u5076\u5947\u304c\u7570\u306a\u3063\u3066\u3044\u308b\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 \u30ce\u30fc\u30c9\u6570\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 // \u5168\u30a8\u30c3\u30b8\u306e\u4e21\u7aef\u306e\u6df1\u3055\u306e\u5076\u5947\u304c\u7570\u306a\u3063\u3066\u3044\u308b\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 \u30ce\u30fc\u30c9\u6570\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 // \u5168\u30a8\u30c3\u30b8\u306e\u4e21\u7aef\u306e\u6df1\u3055\u306e\u5076\u5947\u304c\u7570\u306a\u3063\u3066\u3044\u308b\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 \u30ce\u30fc\u30c9\u6570\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 // \u5168\u30a8\u30c3\u30b8\u306e\u4e21\u7aef\u306e\u6df1\u3055\u306e\u5076\u5947\u304c\u7570\u306a\u3063\u3066\u3044\u308b\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 \u30ce\u30fc\u30c9\u6570\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"} {"nl": {"description": "A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally: if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$; otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of queries. Each of the next $$$t$$$ lines contain queries (one query per line). The query is described as three space-separated integers $$$a, b, k$$$ ($$$1 \\le a, b, k \\le 10^9$$$) \u2014 the lengths of two types of jumps and the number of jumps, respectively.", "output_spec": "Print $$$t$$$ integers. The $$$i$$$-th integer should be the answer for the $$$i$$$-th query.", "sample_inputs": ["6\n5 2 3\n100 1 4\n1 10 5\n1000000000 1 6\n1 1 1000000000\n1 1 999999999"], "sample_outputs": ["8\n198\n-17\n2999999997\n0\n1"], "notes": "NoteIn the first query frog jumps $$$5$$$ to the right, $$$2$$$ to the left and $$$5$$$ to the right so the answer is $$$5 - 2 + 5 = 8$$$.In the second query frog jumps $$$100$$$ to the right, $$$1$$$ to the left, $$$100$$$ to the right and $$$1$$$ to the left so the answer is $$$100 - 1 + 100 - 1 = 198$$$.In the third query the answer is $$$1 - 10 + 1 - 10 + 1 = -17$$$.In the fourth query the answer is $$$10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$$$.In the fifth query all frog's jumps are neutralized by each other so the answer is $$$0$$$.The sixth query is the same as the fifth but without the last jump so the answer is $$$1$$$."}, "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 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}"}, {"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"} {"nl": {"description": "A string is binary, if it consists only of characters \"0\" and \"1\".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string \"010\" has six substrings: \"0\", \"1\", \"0\", \"01\", \"10\", \"010\". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters \"1\".", "input_spec": "The first line contains the single integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.", "output_spec": "Print the single number \u2014 the number of substrings of the given string, containing exactly k characters \"1\". Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["1\n1010", "2\n01010", "100\n01010"], "sample_outputs": ["6", "4", "0"], "notes": "NoteIn the first sample the sought substrings are: \"1\", \"1\", \"10\", \"01\", \"10\", \"010\".In the second sample the sought substrings are: \"101\", \"0101\", \"1010\", \"01010\"."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "The GCD table G of size n\u2009\u00d7\u2009n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a\u2009=\u2009{4,\u20093,\u20096,\u20092} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009500) \u2014 the length of array a. The second line contains n2 space-separated numbers \u2014 the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.", "output_spec": "In the single line print n positive integers \u2014 the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.", "sample_inputs": ["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"], "sample_outputs": ["4 3 6 2", "42", "1 1"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "71dc07f0ea8962f23457af1d6509aeee"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $$$a_1 < a_2 < \\dots < a_n$$$ holds.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the elements of the array.", "output_spec": "For each test case, output \"YES\" (without quotes) if the array satisfies the condition, and \"NO\" (without quotes) otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["3\n\n4\n\n1 1 1 1\n\n5\n\n8 7 1 3 4\n\n1\n\n5"], "sample_outputs": ["NO\nYES\nYES"], "notes": "NoteIn the first test case any rearrangement will keep the array $$$[1,1,1,1]$$$, which is not strictly increasing.In the second test case, you can make the array $$$[1,3,4,7,8]$$$."}, "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 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"}, {"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"} {"nl": {"description": "One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: \"How did he do that?\" The answer is simple.Vasya noticed that the yard is a rectangular n\u2009\u00d7\u2009m field. The squares have coordinates (x,\u2009y) (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m), where x is the index of the row and y is the index of the column.Initially Vasya stands in the square with coordinates (xc,\u2009yc). To play, he has got a list of k vectors (dxi,\u2009dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x,\u2009y), and the current vector is (dx,\u2009dy), one step moves Vasya to square (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy). A step is considered valid, if the boy does not go out of the yard if he performs the step.Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.", "input_spec": "The first input line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009109) \u2014 the yard's sizes. The second line contains integers xc and yc \u2014 the initial square's coordinates (1\u2009\u2264\u2009xc\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009yc\u2009\u2264\u2009m). The third line contains an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009104) \u2014 the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|,\u2009|dyi|\u2009\u2264\u2009109,\u2009|dx|\u2009+\u2009|dy|\u2009\u2265\u20091).", "output_spec": "Print the single number \u2014 the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specificator.", "sample_inputs": ["4 5\n1 1\n3\n1 1\n1 1\n0 -2", "10 10\n1 2\n1\n-1 0"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first sample Vasya is initially positioned at square (1,\u20091) and makes 3 steps by the first vector (1,\u20091). So, he consecutively visits the squares (2,\u20092),\u2009(3,\u20093),\u2009(4,\u20094). Then he makes 0 steps by the second vector (1,\u20091). He makes 1 more step by the third vector (0,\u2009\u2009-\u20092) and he ends up in square (4,\u20092). Overall, Vasya makes 4 steps.In the second sample Vasya is initially positioned in square (1,\u20092) and makes 0 steps by vector (\u2009-\u20091,\u20090), as the square with coordinates (0,\u20092) is located outside the yard."}, "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.util.StringTokenizer\n\n/**\n *\n * @author Vladislav Isenbaev (vladislav.isenbaev@odnoklassniki.ru)\n */\n\nobject CF152B extends App {\n\n def main() {\n val n = nextInt()\n val m = nextInt()\n var x: Long = nextInt() - 1\n var y: Long = nextInt() - 1\n var ans = 0L\n for (it <- 0 until nextInt()) {\n val dx = nextInt()\n val dy = nextInt()\n val stepsX = if (dx == 0) Long.MaxValue else if (dx > 0) (n - x - 1) / dx else x / (-dx)\n val stepsY = if (dy == 0) Long.MaxValue else if (dy > 0) (m - y - 1) / dy else y / (-dy)\n val steps = stepsX min stepsY\n ans += steps\n x += dx * steps\n y += dy * steps\n }\n println(ans)\n }\n\n class Tokenizer(in: BufferedReader, pattern: String = \" \\t\\n\\r\\f\") {\n private def tokenizer = new StringTokenizer(_: String, pattern)\n var st: StringTokenizer = tokenizer(\"\")\n def nextLine() = in.readLine()\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 def next[A](f: String => A): A = f(nextToken())\n }\n\n implicit val tokenizer = new Tokenizer(Console.in)\n\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 main()\n}"}], "negative_code": [], "src_uid": "2737d7aa245627b1f7992b1148ed49ce"} {"nl": {"description": "A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class. ", "input_spec": "The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$)\u00a0\u2014 the number of students in the class and the number of questions in the test. Each of the next $$$n$$$ lines contains string $$$s_i$$$ ($$$|s_i| = m$$$), describing an answer of the $$$i$$$-th student. The $$$j$$$-th character represents the student answer (A, B, C, D or E) on the $$$j$$$-th question. The last line contains $$$m$$$ integers $$$a_1, a_2, \\ldots, a_m$$$ ($$$1 \\le a_i \\le 1000$$$)\u00a0\u2014 the number of points for the correct answer for every question.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible total score of the class.", "sample_inputs": ["2 4\nABCD\nABCE\n1 2 3 4", "3 3\nABC\nBCD\nCDE\n5 4 12"], "sample_outputs": ["16", "21"], "notes": "NoteIn the first example, one of the most optimal test answers is \"ABCD\", this way the total number of points will be $$$16$$$.In the second example, one of the most optimal test answers is \"CCC\", this way each question will be answered by exactly one student and the total number of points is $$$5 + 4 + 12 = 21$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject A_1201 extends App {\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val C = Array.ofDim[Int](m, 5)\n\n 0 until n foreach { _ =>\n readLine().toCharArray.zipWithIndex.foreach {\n case (ch, j) =>\n C(j)(ch - 'A') += 1\n }\n }\n\n val W = readLine().split(\" \").map(_.toInt) ++ Array(0, 0, 0, 0, 0)\n\n var counter = 0\n 0 until m foreach { j =>\n counter += C(j).max * W(j)\n }\n\n println(counter)\n}\n"}], "negative_code": [], "src_uid": "2022f53e5a88d5833e133dc3608a122c"} {"nl": {"description": "In Berland, there is the national holiday coming \u2014 the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.", "input_spec": "The first line contains two space-separated integers n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) and m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers \u2014 the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.", "output_spec": "Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.", "sample_inputs": ["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"], "sample_outputs": ["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red\u00a0\u2013\u00a0brown\u00a0\u2013\u00a0yellow\u00a0\u2013\u00a0red\u00a0\u2013\u00a0brown\u00a0\u2013\u00a0yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake\u00a0\u2014 they bought two different chandeliers.Since chandeliers are different, some days they will have the same color, but some days\u00a0\u2014 different. Of course, it looks poor and only annoys Vasya. As a result, at the $$$k$$$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n, m \\le 500\\,000$$$; $$$1 \\le k \\le 10^{12}$$$)\u00a0\u2014 the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya. The second line contains $$$n$$$ different integers $$$a_i$$$ ($$$1 \\le a_i \\le 2 \\cdot \\max(n, m)$$$) that describe the first chandelier's sequence of colors. The third line contains $$$m$$$ different integers $$$b_j$$$ ($$$1 \\le b_i \\le 2 \\cdot \\max(n, m)$$$) that describe the second chandelier's sequence of colors. At the $$$i$$$-th day, the first chandelier has a color $$$a_x$$$, where $$$x = ((i - 1) \\mod n) + 1)$$$ and the second one has a color $$$b_y$$$, where $$$y = ((i - 1) \\mod m) + 1)$$$. It's guaranteed that sequence $$$a$$$ differs from sequence $$$b$$$, so there are will be days when colors of chandeliers differs.", "output_spec": "Print the single integer\u00a0\u2014 the index of day when Vasya will become angry.", "sample_inputs": ["4 2 4\n4 2 3 1\n2 1", "3 8 41\n1 3 2\n1 6 4 3 5 7 2 8", "1 2 31\n1\n1 2"], "sample_outputs": ["5", "47", "62"], "notes": "NoteIn the first example, the chandeliers will have different colors at days $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. That's why the answer is $$$5$$$."}, "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 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"}, {"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"} {"nl": {"description": "Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||. Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$)\u00a0\u2014 the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$)\u00a0\u2014 the number of matches.", "output_spec": "For each test case print one integer in single line\u00a0\u2014 the minimum number of matches which you have to buy for assembling CME. ", "sample_inputs": ["4\n2\n5\n8\n11"], "sample_outputs": ["2\n1\n0\n1"], "notes": "NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||)."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of $$$10^{100}$$$ planks in two colors in the following way (suppose planks are numbered from left to right from $$$0$$$): if the index of the plank is divisible by $$$r$$$ (such planks have indices $$$0$$$, $$$r$$$, $$$2r$$$ and so on) then you must paint it red; if the index of the plank is divisible by $$$b$$$ (such planks have indices $$$0$$$, $$$b$$$, $$$2b$$$ and so on) then you must paint it blue; if the index is divisible both by $$$r$$$ and $$$b$$$ you can choose the color to paint the plank; otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $$$k$$$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of test cases. The next $$$T$$$ lines contain descriptions of test cases \u2014 one per line. Each test case contains three integers $$$r$$$, $$$b$$$, $$$k$$$ ($$$1 \\le r, b \\le 10^9$$$, $$$2 \\le k \\le 10^9$$$) \u2014 the corresponding coefficients.", "output_spec": "Print $$$T$$$ words \u2014 one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.", "sample_inputs": ["4\n1 1 2\n2 10 4\n5 2 3\n3 2 2"], "sample_outputs": ["OBEY\nREBEL\nOBEY\nOBEY"], "notes": null}, "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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n var a, b, k = ni()\n // a <= b\n if (a > b) {\n val t = a\n a = b\n b = t\n }\n val g = gcd(a, b)\n a /= g\n b /= g\n val c = (b - 1 + a - 1) / a // b-1\u306b\u5207\u308a\u4e0a\u3052\u3067a\u304c\u4f55\u500b\u5165\u308b\u304b\n debug(s\"a:$a b:$b c:$c\")\n if (c >= k) out.println(\"REBEL\")\n else out.println(\"OBEY\")\n }\n }\n}"}], "negative_code": [], "src_uid": "be141f316d6e5d9d8f09192913f4be47"} {"nl": {"description": "There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$)\u00a0\u2014 the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^7$$$)\u00a0\u2014 the quantity of candies in each box.", "output_spec": "For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.", "sample_inputs": ["5\n\n5\n\n1 2 3 4 5\n\n6\n\n1000 1000 5 1000 1000 1000\n\n10\n\n1 2 3 5 1 2 7 9 13 5\n\n3\n\n8 8 8\n\n1\n\n10000000"], "sample_outputs": ["10\n4975\n38\n0\n0"], "notes": "NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total."}, "positive_code": [{"source_code": "object EqualCandies {\n def main (args: Array[String]) = {\n val tests = io.StdIn.readInt\n for (_ <- 1 to tests) {\n val n = io.StdIn.readInt\n val a = io.StdIn.readLine.split(\" \").map(Integer.parseInt(_))\n val minimum = a.min\n val out = a.fold(0)(_ + _ - minimum)\n println(out)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "20dd260775ea71b1fb5b42bcac90a6f2"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. Indices of the array start from zero (i.\u2009e. the first element is $$$a_0$$$, the second one is $$$a_1$$$, and so on).You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of $$$a$$$ with borders $$$l$$$ and $$$r$$$ is $$$a[l; r] = a_l, a_{l + 1}, \\dots, a_{r}$$$.Your task is to reverse such a subarray that the sum of elements on even positions of the resulting array is maximized (i.\u2009e. the sum of elements $$$a_0, a_2, \\dots, a_{2k}$$$ for integer $$$k = \\lfloor\\frac{n-1}{2}\\rfloor$$$ should be maximum possible).You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_0, a_1, \\dots, a_{n-1}$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer on the separate line \u2014 the maximum possible sum of elements on even positions after reversing at most one subarray (continuous subsegment) of $$$a$$$.", "sample_inputs": ["4\n8\n1 7 3 4 7 6 2 9\n5\n1 2 1 2 1\n10\n7 8 4 5 7 6 8 9 7 3\n4\n3 1 2 1"], "sample_outputs": ["26\n5\n37\n5"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200922; )\u00a0\u2014 the number of guests at the party (including Arseny) and the number of pairs of people which are friends. Each of the next m lines contains two integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n; u\u2009\u2260\u2009v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected.", "output_spec": "In the first line print the minimum number of steps required to make all pairs of guests friends. In the second line print the ids of guests, who are selected at each step. If there are multiple solutions, you can output any of them.", "sample_inputs": ["5 6\n1 2\n1 3\n2 3\n2 5\n3 4\n4 5", "4 4\n1 2\n1 3\n1 4\n3 4"], "sample_outputs": ["2\n2 3", "1\n1"], "notes": "NoteIn the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4,\u20091) and (4,\u20092) are not friends. Guest 3 or 5 can introduce them.In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step."}, "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"}, {"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"}], "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"} {"nl": {"description": "Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of digits in the phone number. The second line contains n digits \u2014 the phone number to divide into groups.", "output_spec": "Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.", "sample_inputs": ["6\n549871", "7\n1198733"], "sample_outputs": ["54-98-71", "11-987-33"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i,\u2009j between 1 and n, he wrote the number ai,\u2009j\u2009=\u2009min(pi,\u2009pj). He writes ai,\u2009i\u2009=\u20090 for all integer i from 1 to n.Bob gave you all the values of ai,\u2009j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.", "input_spec": "The first line of the input will contain a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u200950). The next n lines will contain the values of ai,\u2009j. The j-th number on the i-th line will represent ai,\u2009j. The i-th number on the i-th line will be 0. It's guaranteed that ai,\u2009j\u2009=\u2009aj,\u2009i and there is at least one solution consistent with the information given.", "output_spec": "Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.", "sample_inputs": ["2\n0 1\n1 0", "5\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"], "sample_outputs": ["2 1", "2 5 4 1 3"], "notes": "NoteIn the first case, the answer can be {1,\u20092} or {2,\u20091}.In the second case, another possible answer is {2,\u20094,\u20095,\u20091,\u20093}."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There is a given sequence of integers a1,\u2009a2,\u2009...,\u2009an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106). The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20093).", "output_spec": "Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal.", "sample_inputs": ["9\n1 3 2 2 2 1 1 2 3"], "sample_outputs": ["5"], "notes": "NoteIn the example all the numbers equal to 1 and 3 should be replaced by 2."}, "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(' ').groupBy(identity).map(_._2.length).max\n println(n - line)\n}"}], "negative_code": [], "src_uid": "fcb6a715dfe302d7ae5a6695ca8976aa"} {"nl": {"description": "Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.Anton's room can be represented as a grid with $$$n$$$ rows and $$$m$$$ columns. Let $$$(i, j)$$$ denote the cell in row $$$i$$$ and column $$$j$$$. Anton is currently standing at position $$$(i, j)$$$ in his room. To annoy Anton, Riley decided to throw exactly two yo-yos in cells of the room (they can be in the same cell).Because Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to $$$(i, j)$$$ by travelling only to adjacent by side cells. That is, if he is in cell $$$(x, y)$$$ then he can travel to the cells $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ and $$$(x, y - 1)$$$ in one step (if a cell with those coordinates exists).Riley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is maximized. But because he is very busy, he asked you to tell him.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of each test case contains four integers $$$n$$$, $$$m$$$, $$$i$$$, $$$j$$$ ($$$1 \\leq n, m \\leq 10^9$$$, $$$1\\le i\\le n$$$, $$$1\\le j\\le m$$$) \u2014 the dimensions of the room, and the cell at which Anton is currently standing.", "output_spec": "For each test case, print four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \\leq x_1, x_2 \\leq n$$$, $$$1\\le y_1, y_2\\le m$$$) \u2014 the coordinates of where the two yo-yos should be thrown. They will be thrown at coordinates $$$(x_1,y_1)$$$ and $$$(x_2,y_2)$$$. If there are multiple answers, you may print any.", "sample_inputs": ["7\n2 3 1 1\n4 4 1 2\n3 5 2 2\n5 1 2 1\n3 1 3 1\n1 1 1 1\n1000000000 1000000000 1000000000 50"], "sample_outputs": ["1 2 2 3\n4 1 4 4\n3 1 1 5\n5 1 1 1\n1 1 2 1\n1 1 1 1\n50 1 1 1000000000"], "notes": "NoteHere is a visualization of the first test case. "}, "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, m, i, j) = readLine().split(\" \").map(_.toInt)\r\n\r\n println(s\"1 1 $n $m\")\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 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"}, {"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"}], "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"} {"nl": {"description": "You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \\ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \\le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "For each test case, print the answer: \"YES\" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or \"NO\" otherwise.", "sample_inputs": ["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"], "sample_outputs": ["YES\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$."}, "positive_code": [{"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 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 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"}, {"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"} {"nl": {"description": "In the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai \u2014 how many people who are taller than him/her and stand in queue in front of him.After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order.When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number ai.Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers hi \u2014 the heights of people in the queue, so that the numbers ai are correct.", "input_spec": "The first input line contains integer n \u2014 the number of people in the queue (1\u2009\u2264\u2009n\u2009\u2264\u20093000). Then n lines contain descriptions of the people as \"namei ai\" (one description on one line), where namei is a non-empty string consisting of lowercase Latin letters whose length does not exceed 10 characters (the i-th person's name), ai is an integer (0\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u20091), that represents the number of people who are higher and stand in the queue in front of person i. It is guaranteed that all names are different.", "output_spec": "If there's no acceptable order of the people in the queue, print the single line containing \"-1\" without the quotes. Otherwise, print in n lines the people as \"namei hi\", where hi is the integer from 1 to 109 (inclusive), the possible height of a man whose name is namei. Print the people in the order in which they stand in the queue, starting from the head of the queue and moving to its tail. Numbers hi are not necessarily unique.", "sample_inputs": ["4\na 0\nb 2\nc 0\nd 0", "4\nvasya 0\npetya 1\nmanya 3\ndunay 3"], "sample_outputs": ["a 150\nc 170\nd 180\nb 160", "-1"], "notes": null}, "positive_code": [{"source_code": "import collection.mutable.ArrayBuffer\n\nobject Main {\n\n def deal() = {\n val tmp = readLine split ' '\n (tmp(1).toInt, tmp(0))\n }\n\n def main(args: Array[String]) {\n val n = readInt()\n val data = (for (i <- 0 until n) yield deal()).sorted\n val order = new ArrayBuffer[String]()\n try {\n for (item <- data)\n order.insert(item _1, item _2)\n val map = new collection.mutable.HashMap[String, Int]\n for (i <- 0 until n)\n map += (order(i) -> (n - i))\n for (item <- data)\n println(item._2 + ' ' + map(item._2))\n }\n catch {\n case ex : Exception => println(\"-1\")\n }\n }\n\n\n}"}], "negative_code": [], "src_uid": "112d5d664b0183d96e55a3c545d9b7d5"} {"nl": {"description": "You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.", "input_spec": "The first line contains a single positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). The following n lines contain coordinates of the points. The i-th of these lines contains two single integers xi and yi (|xi|,\u2009|yi|\u2009\u2264\u2009109, xi\u2009\u2260\u20090). No two points coincide.", "output_spec": "Print \"Yes\" if there is such a point, \"No\" \u2014 otherwise. You can print every letter in any case (upper or lower).", "sample_inputs": ["3\n1 1\n-1 -1\n2 -1", "4\n1 1\n2 2\n-1 1\n-2 2", "3\n1 2\n2 1\n4 60"], "sample_outputs": ["Yes", "No", "Yes"], "notes": "NoteIn the first example the second point can be removed.In the second example there is no suitable for the condition point.In the third example any point can be removed."}, "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": "\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"}, {"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"} {"nl": {"description": "It turns out that the meaning of life is a permutation $$$p_1, p_2, \\ldots, p_n$$$ of the integers $$$1, 2, \\ldots, n$$$ ($$$2 \\leq n \\leq 100$$$). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries.A query consists of an array $$$a_1, a_2, \\ldots, a_n$$$ of integers between $$$1$$$ and $$$n$$$. $$$a$$$ is not required to be a permutation. Omkar will first compute the pairwise sum of $$$a$$$ and $$$p$$$, meaning that he will compute an array $$$s$$$ where $$$s_j = p_j + a_j$$$ for all $$$j = 1, 2, \\ldots, n$$$. Then, he will find the smallest index $$$k$$$ such that $$$s_k$$$ occurs more than once in $$$s$$$, and answer with $$$k$$$. If there is no such index $$$k$$$, then he will answer with $$$0$$$.You can perform at most $$$2n$$$ queries. Figure out the meaning of life $$$p$$$.", "input_spec": null, "output_spec": null, "sample_inputs": ["5\n\n2\n\n0\n\n1"], "sample_outputs": ["? 4 4 2 3 2\n\n? 3 5 1 5 5\n\n? 5 2 4 3 1\n\n! 3 2 1 5 4"], "notes": "NoteIn the sample, the hidden permutation $$$p$$$ is $$$[3, 2, 1, 5, 4]$$$. Three queries were made.The first query is $$$a = [4, 4, 2, 3, 2]$$$. This yields $$$s = [3 + 4, 2 + 4, 1 + 2, 5 + 3, 4 + 2] = [7, 6, 3, 8, 6]$$$. $$$6$$$ is the only number that appears more than once, and it appears first at index $$$2$$$, making the answer to the query $$$2$$$.The second query is $$$a = [3, 5, 1, 5, 5]$$$. This yields $$$s = [3 + 3, 2 + 5, 1 + 1, 5 + 5, 4 + 5] = [6, 7, 2, 10, 9]$$$. There are no numbers that appear more than once here, so the answer to the query is $$$0$$$.The third query is $$$a = [5, 2, 4, 3, 1]$$$. This yields $$$s = [3 + 5, 2 + 2, 1 + 4, 5 + 3, 4 + 1] = [8, 4, 5, 8, 5]$$$. $$$5$$$ and $$$8$$$ both occur more than once here. $$$5$$$ first appears at index $$$3$$$, while $$$8$$$ first appears at index $$$1$$$, and $$$1 < 3$$$, making the answer to the query $$$1$$$.Note that the sample is only meant to provide an example of how the interaction works; it is not guaranteed that the above queries represent a correct strategy with which to determine the answer."}, "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 val rem = 1000000007\n\n val t = 1// readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val d = new Array[Int](n+1)\n var k = 0\n for (i <- 2 to n) {\n writer.print('?')\n for (j <- 2 to n)\n writer.print(\" \" + i)\n writer.println(\" \" + 1)\n writer.flush()\n d(readInt()) = 1 - i\n }\n for (i <- 1 until n) {\n writer.print('?')\n for (j <- 2 to n)\n writer.print(\" \" +i)\n writer.println(\" \" + n)\n writer.flush()\n d(readInt()) = n - i\n }\n var diff = 0\n for (i <- 1 to n)\n diff = min(diff, d(i))\n writer.print('!')\n for (i <- 1 to n) {\n writer.print(\" \" + (d(i) - diff + 1))\n }\n writer.println()\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "2cb5fe3fdff43e104729866cdfa73102"} {"nl": {"description": "You are given two positive integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 100$$$). Represent the number $$$n$$$ as the sum of $$$k$$$ positive integers of the same parity (have the same remainder when divided by $$$2$$$).In other words, find $$$a_1, a_2, \\ldots, a_k$$$ such that all $$$a_i>0$$$, $$$n = a_1 + a_2 + \\ldots + a_k$$$ and either all $$$a_i$$$ are even or all $$$a_i$$$ are odd at the same time.If such a representation does not exist, then report it.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 100$$$).", "output_spec": "For each test case print: YES and the required values $$$a_i$$$, if the answer exists (if there are several answers, print any of them); NO if the answer does not exist. The letters in the words YES and NO can be printed in any case.", "sample_inputs": ["8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9"], "sample_outputs": ["YES\n4 2 4\nYES\n55 5 5 35\nNO\nNO\nYES\n1 1 1 1 1 1 1 1\nNO\nYES\n3 1 1\nYES\n111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120"], "notes": null}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k\u2009=\u20092, the pair of integers x\u2009=\u20095 and y\u2009=\u20093 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i\u2009<\u2009j and the pair of integers ai and aj is k-interesting. Your task is to help Vasya and determine this number.", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u200914) \u2014 the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009104), which Vasya has.", "output_spec": "Print the number of pairs (i, j) so that i\u2009<\u2009j and the pair of integers ai and aj is k-interesting.", "sample_inputs": ["4 1\n0 3 2 1", "6 0\n200 100 100 100 200 200"], "sample_outputs": ["4", "6"], "notes": "NoteIn the first test there are 4 k-interesting pairs: (1, 3), (1, 4), (2, 3), (2, 4). In the second test k\u2009=\u20090. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs: (1, 5), (1, 6), (2, 3), (2, 4), (3, 4), (5, 6). "}, "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"}, {"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}"}], "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"} {"nl": {"description": "Polycarp doesn't like integers that are divisible by $$$3$$$ or end with the digit $$$3$$$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.Polycarp starts to write out the positive (greater than $$$0$$$) integers which he likes: $$$1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \\dots$$$. Output the $$$k$$$-th element of this sequence (the elements are numbered from $$$1$$$).", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \\le k \\le 1000$$$).", "output_spec": "For each test case, output in a separate line one integer $$$x$$$ \u2014 the $$$k$$$-th element of the sequence that was written out by Polycarp.", "sample_inputs": ["10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n1000"], "sample_outputs": ["1\n2\n4\n5\n7\n8\n10\n11\n14\n1666"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems \u2014 the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009|s|) of string s\u2009=\u2009s1s2... s|s| (where |s| is the length of string s) is string slsl\u2009+\u20091... sr.String x\u2009=\u2009x1x2... xp is lexicographically smaller than string y\u2009=\u2009y1y2... yq, if either p\u2009<\u2009q and x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xp\u2009=\u2009yp, or there exists such number r (r\u2009<\u2009p,\u2009r\u2009<\u2009q), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xr\u2009=\u2009yr and xr\u2009+\u20091\u2009<\u2009yr\u2009+\u20091. The string characters are compared by their ASCII codes.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200930) \u2014 the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.", "output_spec": "Print a string, consisting of lowercase English letters \u2014 the lexicographically minimum shortest original title.", "sample_inputs": ["5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear", "4\naa\nbdefghijklmn\nopqrstuvwxyz\nc"], "sample_outputs": ["j", "ab"], "notes": "NoteIn the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $$$1$$$ minute.He was asked to insert one takeoff in the schedule. The takeoff takes $$$1$$$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $$$s$$$ minutes from both sides.Find the earliest time when Arkady can insert the takeoff.", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$s$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le s \\le 60$$$)\u00a0\u2014 the number of landings on the schedule and the minimum allowed time (in minutes) between a landing and a takeoff. Each of next $$$n$$$ lines contains two integers $$$h$$$ and $$$m$$$ ($$$0 \\le h \\le 23$$$, $$$0 \\le m \\le 59$$$)\u00a0\u2014 the time, in hours and minutes, when a plane will land, starting from current moment (i.\u00a0e. the current time is $$$0$$$ $$$0$$$). These times are given in increasing order.", "output_spec": "Print two integers $$$h$$$ and $$$m$$$\u00a0\u2014 the hour and the minute from the current moment of the earliest time Arkady can insert the takeoff.", "sample_inputs": ["6 60\n0 0\n1 20\n3 21\n5 0\n19 30\n23 40", "16 50\n0 30\n1 20\n3 0\n4 30\n6 10\n7 50\n9 30\n11 10\n12 50\n14 30\n16 10\n17 50\n19 30\n21 10\n22 50\n23 59", "3 17\n0 30\n1 0\n12 0"], "sample_outputs": ["6 1", "24 50", "0 0"], "notes": "NoteIn the first example note that there is not enough time between 1:20 and 3:21, because each landing and the takeoff take one minute.In the second example there is no gaps in the schedule, so Arkady can only add takeoff after all landings. Note that it is possible that one should wait more than $$$24$$$ hours to insert the takeoff.In the third example Arkady can insert the takeoff even between the first landing."}, "positive_code": [{"source_code": "\n\nobject CF967A extends App {\n import scala.io.Source\n\n //val src = Source.fromFile(\"data.txt\")\n val src = Source.stdin\n val lines = src.getLines\n \n def readInts(): Array[Int] = {\n val line = if (lines.hasNext) lines.next else null\n if (line == null) throw new RuntimeException(\"Premature end of source encountered\")\n line.split(\" \").map(x => x.toInt)\n }\n \n val Array(nLandingTimes, gap) = readInts()\n val landingTimesMins = (0 until nLandingTimes).map(x => readInts()).map {ar => 60 * ar(0) + ar(1) }\n val interval = landingTimesMins.zip(landingTimesMins.tail).find { case (m,n) => n - m >= 2 * gap + 2}\n \n val takeOffTime = {\n if (gap + 1 <= landingTimesMins(0)) 0\n else interval match {\n case Some((m, n)) => m + gap + 1\n case None => landingTimesMins.last + gap + 1\n }\n }\n println(takeOffTime/60 + \" \" + takeOffTime % 60)\n \n}"}], "negative_code": [{"source_code": "\n\nobject CF967A extends App {\n import scala.io.Source\n\n //val src = Source.fromFile(\"data.txt\")\n val src = Source.stdin\n val lines = src.getLines\n \n def readInts(): Array[Int] = {\n val line = if (lines.hasNext) lines.next else null\n if (line == null) throw new RuntimeException(\"Premature end of source encountered\")\n line.split(\" \").map(x => x.toInt)\n }\n \n val Array(nLandingTimes, gap) = readInts()\n val landingTimesMins = (0 until nLandingTimes).map(x => readInts()).map {ar => 60 * ar(0) + ar(1) }\n val interval = landingTimesMins.zip(landingTimesMins.tail).find { case (m,n) => n - m > 2 * gap + 2}\n \n val takeOffTime = {\n if (gap + 1 <= landingTimesMins(0)) 0\n else interval match {\n case Some((m, n)) => m + gap + 1\n case None => landingTimesMins.last + gap + 1\n }\n }\n println(takeOffTime/60 + \" \" + takeOffTime % 60)\n \n}"}], "src_uid": "dcca7c58ba7111125608f659a577c3a2"} {"nl": {"description": "You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word \"hello\". Determine how long it will take to print the word $$$s$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboard\u00a0\u2014 a string of length $$$26$$$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard. The second line of the description contains the word $$$s$$$. The word has a length from $$$1$$$ to $$$50$$$ letters inclusive and consists of lowercase Latin letters.", "output_spec": "Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $$$s$$$ on the given keyboard.", "sample_inputs": ["5\nabcdefghijklmnopqrstuvwxyz\nhello\nabcdefghijklmnopqrstuvwxyz\ni\nabcdefghijklmnopqrstuvwxyz\ncodeforces\nqwertyuiopasdfghjklzxcvbnm\nqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\nqwertyuiopasdfghjklzxcvbnm\nabacaba"], "sample_outputs": ["13\n0\n68\n0\n74"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line \u2014 the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command \" run.exe one, two . \", we give four lexemes to the Pindows command line: \"run.exe\", \"one,\", \"two\", \".\". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited \u2014 that is, for each occurrence of character \"\"\" we should be able to say clearly that the quotes are opening or closing. For example, as we run the command \"\"run.exe o\" \"\" \" ne, \" two . \" \" \", we give six lexemes to the Pindows command line: \"run.exe o\", \"\" (an empty string), \" ne, \", \"two\", \".\", \" \" (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters \".,?!\"\" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character \"\"\" to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.", "input_spec": "The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the \".,?!\"\" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.", "output_spec": "In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the \"<\" (less) character to the left of your lexemes and the \">\" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.", "sample_inputs": ["\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"", "firstarg second \"\""], "sample_outputs": ["<RUn.exe O>\n<>\n< 2ne, >\n<two!>\n<.>\n< >", "<firstarg>\n<second>\n<>"], "notes": null}, "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. \u0410\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0412 \u0434\u0430\u043d\u043d\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0441\u0432\u043e\u0439\u0441\u0442\u0432 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438, \u0431\u043b\u0438\u0437\u043a\u043e\u0435 \u043a \u0442\u043e\u043c\u0443, \u0447\u0442\u043e \u0432\u044b \u043f\u0440\u0438\u0432\u044b\u043a\u043b\u0438 \u0432\u0438\u0434\u0435\u0442\u044c \u0432 \u043d\u0430\u0441\u0442\u043e\u044f\u0449\u0438\u0445 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0445 \u0441\u0438\u0441\u0442\u0435\u043c\u0430\u0445. \u041e\u0434\u043d\u0430\u043a\u043e, \u0432 \u0434\u0435\u0442\u0430\u043b\u044f\u0445 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044e\u0442 \u043e\u0442\u043b\u0438\u0447\u0438\u044f \u0432 \u043f\u043e\u0432\u0435\u0434\u0435\u043d\u0438\u0438. \u0412\u043d\u0438\u043c\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u0440\u043e\u0447\u0442\u0438\u0442\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u0435, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 \u0435\u0433\u043e \u043a\u0430\u043a \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u043f\u0440\u0438 \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u044f.\n\n\u0412 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u043e\u043d\u043d\u043e\u0439 \u0441\u0438\u0441\u0442\u0435\u043c\u0435 Pindows \u043b\u0435\u043a\u0441\u0435\u043c\u0430\u043c\u0438 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438 \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u0441\u0442\u0440\u043e\u043a\u0438 \u2014 \u043f\u0435\u0440\u0432\u0430\u044f \u0438\u0437 \u043d\u0438\u0445 \u0442\u0440\u0430\u043a\u0442\u0443\u0435\u0442\u0441\u044f \u043a\u0430\u043a \u0438\u043c\u044f \u0437\u0430\u043f\u0443\u0441\u043a\u0430\u0435\u043c\u043e\u0439 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b, \u0430 \u043f\u043e\u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u043a\u0430\u043a \u0435\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u044f \u043a\u043e\u043c\u0430\u043d\u0434\u0443 \u00ab run.exe one, two . \u00bb, \u043c\u044b \u043f\u0435\u0440\u0435\u0434\u0430\u0435\u043c \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 Pindows \u0447\u0435\u0442\u044b\u0440\u0435 \u043b\u0435\u043a\u0441\u0435\u043c\u044b: \u00abrun.exe\u00bb, \u00abone,\u00bb, \u00abtwo\u00bb, \u00ab.\u00bb. \u0411\u043e\u043b\u0435\u0435 \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, \u0435\u0441\u043b\u0438 \u043c\u044b \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043a\u043e\u043c\u0430\u043d\u0434\u0443, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u043c\u0430 \u0441\u0442\u0440\u043e\u043a\u043e\u0439 s (\u0438 \u043d\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043a\u0430\u0432\u044b\u0447\u0435\u043a), \u0442\u043e \u043b\u0435\u043a\u0441\u0435\u043c\u0430\u043c\u0438 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438 \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u043e \u0432\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044e \u043f\u043e\u0434\u0441\u0442\u0440\u043e\u043a\u0438 \u0441\u0442\u0440\u043e\u043a\u0438 s, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043d\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442 \u043f\u0440\u043e\u0431\u0435\u043b\u043e\u0432.\n\n\u0414\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043b\u0435\u043a\u0441\u0435\u043c\u044b \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438 \u0441\u0442\u0440\u043e\u043a\u0443 \u0441 \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c\u0438 \u0438\u043b\u0438 \u043f\u0443\u0441\u0442\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0442\u0441\u044f \u0434\u0432\u043e\u0439\u043d\u044b\u0435 \u043a\u0430\u0432\u044b\u0447\u043a\u0438. \u0411\u043b\u043e\u043a \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0434\u043e\u043b\u0436\u0435\u043d \u0440\u0430\u0441\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0442\u044c\u0441\u044f \u043a\u0430\u043a \u043e\u0434\u043d\u0430 \u043b\u0435\u043a\u0441\u0435\u043c\u0430, \u0431\u0435\u0440\u0435\u0442\u0441\u044f \u0432 \u043a\u0430\u0432\u044b\u0447\u043a\u0438. \u041f\u0440\u0438 \u044d\u0442\u043e\u043c \u0432\u043b\u043e\u0436\u0435\u043d\u043d\u044b\u0435 \u043a\u0430\u0432\u044b\u0447\u043a\u0438 \u0437\u0430\u043f\u0440\u0435\u0449\u0430\u044e\u0442\u0441\u044f \u2014 \u0442\u043e \u0435\u0441\u0442\u044c \u043f\u0440\u043e \u043a\u0430\u0436\u0434\u043e\u0435 \u0432\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u0435 \u0441\u0438\u043c\u0432\u043e\u043b\u0430 \u00ab\"\u00bb \u043c\u043e\u0436\u043d\u043e \u043e\u0434\u043d\u043e\u0437\u043d\u0430\u0447\u043d\u043e \u0441\u043a\u0430\u0437\u0430\u0442\u044c \u2014 \u0447\u0442\u043e \u044d\u0442\u043e, \u043e\u0442\u043a\u0440\u044b\u0432\u0430\u044e\u0449\u0438\u0435 \u043a\u0430\u0432\u044b\u0447\u043a\u0438 \u0438\u043b\u0438 \u0437\u0430\u043a\u0440\u044b\u0432\u0430\u044e\u0449\u0438\u0435. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u044f \u043a\u043e\u043c\u0430\u043d\u0434\u0443 \u00ab\"run.exe o\" \"\" \" ne, \" two . \" \" \u00bb, \u043c\u044b \u043f\u0435\u0440\u0435\u0434\u0430\u0435\u043c \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 Pindows \u0448\u0435\u0441\u0442\u044c \u043b\u0435\u043a\u0441\u0435\u043c: \u00abrun.exe o\u00bb, \u00ab\u00bb (\u043f\u0443\u0441\u0442\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430), \u00ab ne, \u00bb, \u00abtwo\u00bb, \u00ab.\u00bb, \u00ab \u00bb (\u0435\u0434\u0438\u043d\u0438\u0447\u043d\u044b\u0439 \u043f\u0440\u043e\u0431\u0435\u043b).\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043a\u0430\u0436\u0434\u0430\u044f \u0438\u0437 \u043b\u0435\u043a\u0441\u0435\u043c \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438 \u043e\u043a\u0440\u0443\u0436\u0435\u043d\u0430 \u0441 \u043e\u0431\u0435\u0438\u0445 \u0441\u0442\u043e\u0440\u043e\u043d \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c\u0438 \u0438\u043b\u0438 \u0443\u043f\u0438\u0440\u0430\u0435\u0442\u0441\u044f \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0439 \u043a\u0440\u0430\u0439 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438. \u0418\u0437 \u044d\u0442\u043e\u0433\u043e, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0441\u043b\u0435\u0434\u0443\u0435\u0442, \u0447\u0442\u043e \u043e\u0442\u043a\u0440\u044b\u0432\u0430\u044e\u0449\u0438\u0435 \u043a\u0430\u0432\u044b\u0447\u043a\u0438 \u043b\u0438\u0431\u043e \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043f\u0435\u0440\u0432\u044b\u043c \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u043c \u0441\u0442\u0440\u043e\u043a\u0438, \u043b\u0438\u0431\u043e \u0441\u043b\u0435\u0432\u0430 \u043e\u0442 \u043d\u0438\u0445 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u043f\u0440\u043e\u0431\u0435\u043b.\n\n\u0412\u0430\u043c \u0437\u0430\u0434\u0430\u043d\u0430 \u0441\u0442\u0440\u043e\u043a\u0430, \u0441\u043e\u0441\u0442\u043e\u044f\u0449\u0430\u044f \u0438\u0437 \u043f\u0440\u043e\u043f\u0438\u0441\u043d\u044b\u0445, \u0441\u0442\u0440\u043e\u0447\u043d\u044b\u0445 \u0431\u0443\u043a\u0432 \u043b\u0430\u0442\u0438\u043d\u0441\u043a\u043e\u0433\u043e \u0430\u043b\u0444\u0430\u0432\u0438\u0442\u0430, \u0446\u0438\u0444\u0440, \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u00ab.,?!\"\u00bb \u0438 \u043f\u0440\u043e\u0431\u0435\u043b\u043e\u0432. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u044d\u0442\u0430 \u0441\u0442\u0440\u043e\u043a\u0430 \u2014 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u0430\u044f \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 OS Pindows. \u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0432\u0441\u0435 \u043b\u0435\u043a\u0441\u0435\u043c\u044b \u044d\u0442\u043e\u0439 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438. \u0421\u0447\u0438\u0442\u0430\u0439\u0442\u0435, \u0447\u0442\u043e \u0441\u0438\u043c\u0432\u043e\u043b \u00ab\"\u00bb \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0432 \u043a\u043e\u043c\u0430\u043d\u0434\u0435 \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u043b\u044f \u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0435\u0434\u0438\u043d\u043e\u0433\u043e \u0431\u043b\u043e\u043a\u0430 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u0432 \u043e\u0434\u043d\u0443 \u043b\u0435\u043a\u0441\u0435\u043c\u0443 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438, \u0432 \u0447\u0430\u0441\u0442\u043d\u043e\u0441\u0442\u0438, \u0438\u0437 \u044d\u0442\u043e\u0433\u043e \u0441\u043b\u0435\u0434\u0443\u0435\u0442, \u0447\u0442\u043e \u0442\u0430\u043a\u0438\u0445 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u0432 \u0437\u0430\u0434\u0430\u043d\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0442\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d\u0430 \u043d\u0435\u043f\u0443\u0441\u0442\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 s. \u0421\u0442\u0440\u043e\u043a\u0430 s \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u043c 105 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432. \u041a\u0430\u0436\u0434\u044b\u0439 \u0441\u0438\u043c\u0432\u043e\u043b \u2014 \u044d\u0442\u043e \u043b\u0438\u0431\u043e \u043f\u0440\u043e\u043f\u0438\u0441\u043d\u0430\u044f, \u043b\u0438\u0431\u043e \u0441\u0442\u0440\u043e\u0447\u043d\u0430\u044f \u0431\u0443\u043a\u0432\u0430 \u043b\u0430\u0442\u0438\u043d\u0441\u043a\u043e\u0433\u043e \u0430\u043b\u0444\u0430\u0432\u0438\u0442\u0430, \u043b\u0438\u0431\u043e \u0446\u0438\u0444\u0440\u0430, \u043b\u0438\u0431\u043e \u043e\u0434\u0438\u043d \u0438\u0437 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u00ab.,?!\"\u00bb, \u043b\u0438\u0431\u043e \u043f\u0440\u043e\u0431\u0435\u043b.\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0437\u0430\u0434\u0430\u043d\u043d\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u2014 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u0430\u044f \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 OS Pindows. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432 \u0437\u0430\u0434\u0430\u043d\u043d\u043e\u0439 \u043a\u043e\u043c\u0430\u043d\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0435\u0441\u0442\u044c \u0445\u043e\u0442\u044f \u0431\u044b \u043e\u0434\u043d\u0430 \u043b\u0435\u043a\u0441\u0435\u043c\u0430.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043f\u0435\u0440\u0432\u0443\u044e \u043b\u0435\u043a\u0441\u0435\u043c\u0443, \u0432\u043e \u0432\u0442\u043e\u0440\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u2014 \u0432\u0442\u043e\u0440\u0443\u044e, \u0438 \u0442\u0430\u043a \u0434\u0430\u043b\u0435\u0435. \u0414\u043b\u044f \u043d\u0430\u0433\u043b\u044f\u0434\u043d\u043e\u0441\u0442\u0438 \u0441\u043b\u0435\u0432\u0430 \u043e\u0442 \u043a\u0430\u0436\u0434\u043e\u0439 \u043b\u0435\u043a\u0441\u0435\u043c\u044b \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u0438\u043c\u0432\u043e\u043b \u00ab<\u00bb (\u043c\u0435\u043d\u044c\u0448\u0435), \u0430 \u0441\u043f\u0440\u0430\u0432\u0430 \u2014 \u0441\u0438\u043c\u0432\u043e\u043b \u00ab>\u00bb (\u0431\u043e\u043b\u044c\u0448\u0435). \u0412\u044b\u0432\u043e\u0434\u0438\u0442\u0435 \u043b\u0435\u043a\u0441\u0435\u043c\u044b \u0432 \u0442\u043e\u043c \u043f\u043e\u0440\u044f\u0434\u043a\u0435, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043e\u043d\u0438 \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u044e\u0442\u0441\u044f \u0432 \u043a\u043e\u043c\u0430\u043d\u0434\u0435.\n\n\u0421\u0442\u0440\u043e\u0433\u043e \u0441\u043b\u0435\u0434\u0443\u0439\u0442\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u043e\u043c\u0443 \u0444\u043e\u0440\u043c\u0430\u0442\u0443 \u0432\u044b\u0432\u043e\u0434\u0430. \u0414\u043b\u044f \u043b\u0443\u0447\u0448\u0435\u0433\u043e \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u044f \u0444\u043e\u0440\u043c\u0430\u0442\u0430 \u0432\u044b\u0432\u043e\u0434\u0430 \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u0442\u0435 \u0442\u0435\u0441\u0442\u043e\u0432\u044b\u0435 \u043f\u0440\u0438\u043c\u0435\u0440\u044b.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\n<>\n< 2ne, >\n\n<.>\n< >\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n firstarg second \"\" \n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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 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"}, {"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"} {"nl": {"description": "Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.The game involves $$$n$$$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.Find the minimum possible amount of balls that were involved in the game.", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 5 \\cdot 10^4$$$)\u00a0\u2014 the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^5$$$)\u00a0\u2014 the number of players. The second line of the test case contains a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$), where $$$a_i$$$ is the number of passes delivered by the $$$i$$$-th player. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["4\n4\n2 3 3 2\n3\n1 5 2\n2\n0 0\n4\n1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["1\n2\n0\n1"], "notes": "NoteIn the first test case, with the only ball, the game can go like this:$$$2 \\rightarrow 1 \\rightarrow 3 \\rightarrow 4 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4 \\rightarrow 2 \\rightarrow 3 \\rightarrow 2$$$.In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls:$$$2 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 2 \\rightarrow 1$$$.$$$2 \\rightarrow 3 \\rightarrow 2 \\rightarrow 1$$$In the third example, there were no passes, so $$$0$$$ balls are possible."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n\n def f(i: Int, xs: Array[Long]) = {\n val (sum, max) = xs.foldLeft(0L, None:Option[Long])(\n (acc, elem) => acc match {\n case (q, Some(o)) => (q + elem, if (o > elem) Some(o) else Some(elem))\n case (_, None) => (elem, Some(elem))\n }\n )\n\n val rem = sum - max.get\n if (sum == 0) 0\n else if (rem >= max.get - 1) 1\n else max.get - rem\n\n }\n\n def main(args: Array[String]): Unit = {\n val cases = readLine.toInt\n for (\n c <- 0 until cases;\n i = readLine().toInt;\n j = readLine().split(\"\\\\s+\").map(_.toLong)\n ) println(f(i, j))\n\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n\n def f(i: Int, xs: Array[Long]) = {\n val (sum, max) = xs.foldLeft(0L, None:Option[Long])(\n (acc, elem) => acc match {\n case (q, Some(o)) => (q + elem, if (o > elem) Some(o) else Some(elem))\n case (_, None) => (elem, Some(elem))\n }\n )\n\n val rem = sum - max.get\n if (rem > max.get) 1\n else max.get - rem\n\n }\n\n def main(args: Array[String]): Unit = {\n val cases = readLine.toInt\n for (\n c <- 0 until cases;\n i = readLine().toInt;\n j = readLine().split(\"\\\\s+\").map(_.toLong)\n ) println(f(i, j))\n\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n\n def f() = {\n val players = readLine().toInt\n val arr = readLine().split(\"\\\\s+\").map(_.toLong)\n\n val sum = arr.sum\n val fil = arr.filterNot(_ == 0)\n if (fil.length == 0) 0 else {\n val avg = sum / fil.length\n val max = arr.max\n\n if (sum == 0) 0\n else max / avg\n }\n\n }\n\n def main(args: Array[String]): Unit = {\n val cases = readLine.toInt\n for (\n i <- 0 until cases\n ) println(f())\n }\n}\n"}], "src_uid": "98d9c44e460e141f062fcd6c345a4a1d"} {"nl": {"description": "Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy \u2014 she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.", "output_spec": "Output the single number \u2014 the number of Alyona's leaves.", "sample_inputs": ["5\nbirch yellow\nmaple red\nbirch yellow\nmaple yellow\nmaple green", "3\noak yellow\noak yellow\noak yellow"], "sample_outputs": ["4", "1"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n println(in.take(n).toSet.size)\n}"}], "negative_code": [], "src_uid": "07c370b99fe85984f5e20826a3bf5eb9"} {"nl": {"description": "Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).You may perform the following operations until both a and s are empty: Take the first element of a, push it into s and remove it from a (if a is not empty); Take the top element from s, append it to the end of array b and remove it from s (if s is not empty). You can perform these operations in arbitrary order.If there exists a way to perform the operations such that array b is sorted in non-descending order in the end, then array a is called stack-sortable.For example, [3,\u20091,\u20092] is stack-sortable, because b will be sorted if we perform the following operations: Remove 3 from a and push it into s; Remove 1 from a and push it into s; Remove 1 from s and append it to the end of b; Remove 2 from a and push it into s; Remove 2 from s and append it to the end of b; Remove 3 from s and append it to the end of b. After all these operations b\u2009=\u2009[1,\u20092,\u20093], so [3,\u20091,\u20092] is stack-sortable. [2,\u20093,\u20091] is not stack-sortable.You are given k first elements of some permutation p of size n (recall that a permutation of size n is an array of size n where each integer from 1 to n occurs exactly once). You have to restore the remaining n\u2009-\u2009k elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that p is lexicographically maximal (an array q is lexicographically greater than an array p iff there exists some integer k such that for every i\u2009<\u2009k qi\u2009=\u2009pi, and qk\u2009>\u2009pk). You may not swap or change any of first k elements of the permutation.Print the lexicographically maximal permutation p you can obtain.If there exists no answer then output -1.", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009200000, 1\u2009\u2264\u2009k\u2009<\u2009n) \u2014 the size of a desired permutation, and the number of elements you are given, respectively. The second line contains k integers p1, p2, ..., pk (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 the first k elements of p. These integers are pairwise distinct.", "output_spec": "If it is possible to restore a stack-sortable permutation p of size n such that the first k elements of p are equal to elements given in the input, print lexicographically maximal such permutation. Otherwise print -1.", "sample_inputs": ["5 3\n3 2 1", "5 3\n2 3 1", "5 1\n3", "5 2\n3 4"], "sample_outputs": ["3 2 1 5 4", "-1", "3 2 1 5 4", "-1"], "notes": null}, "positive_code": [{"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, k) = readIntLine()\n val prefix = readIntLine()\n var reserve = new mutable.TreeSet[Int]()(Ordering.Int.reverse)\n (1 to n).toSet.diff(prefix.toSet).foreach(reserve.add)\n\n val result = stacksort(prefix.toList, Nil, 1, reserve, Nil, n)\n if (result.isEmpty) {\n println(-1)\n } else {\n println((prefix ++: result.reverse).toArray.mkString(\" \"))\n }\n }\n\n def stacksort(nums : List[Int], stack : List[Int], out : Int, reserve : mutable.TreeSet[Int], result : List[Int], n : Int) : List[Int] = {\n if (out > n) {\n result\n } else if (nums.nonEmpty && nums.head == out) {\n stacksort(nums.tail, stack, out + 1, reserve, result, n)\n } else if (stack.nonEmpty && stack.head == out) {\n stacksort(nums, stack.tail, out + 1, reserve, result, n)\n } else if (nums.nonEmpty && (stack.isEmpty || (stack.head > nums.head))) {\n stacksort(nums.tail, nums.head :: stack, out, reserve, result, n)\n } else if (nums.isEmpty) {\n val bound = stack.headOption.getOrElse(n)\n val desiredIt = reserve.iteratorFrom(bound)\n if (desiredIt.hasNext) {\n val desired = desiredIt.next()\n reserve.remove(desired)\n stacksort(nums, desired :: stack, out, reserve, desired :: result, n)\n } else {\n Nil\n }\n } else {\n Nil\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 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": "848e81bc0aeaec7dbe3ec8e68d7b07ef"} {"nl": {"description": "Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.You are given a connected undirected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. There are $$$k$$$ special vertices: $$$x_1, x_2, \\ldots, x_k$$$.Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\leq k \\leq n \\leq 10^5$$$, $$$n-1 \\leq m \\leq 10^5$$$)\u00a0\u2014 the number of vertices, the number of edges and the number of special vertices. The second line contains $$$k$$$ distinct integers $$$x_1, x_2, \\ldots, x_k$$$ ($$$1 \\leq x_i \\leq n$$$). Each of the following $$$m$$$ lines contains three integers $$$u$$$, $$$v$$$ and $$$w$$$ ($$$1 \\leq u,v \\leq n, 1 \\leq w \\leq 10^9$$$), denoting there is an edge between $$$u$$$ and $$$v$$$ of weight $$$w$$$. The given graph is undirected, so an edge $$$(u, v)$$$ can be used in the both directions. The graph may have multiple edges and self-loops. It is guaranteed, that the graph is connected.", "output_spec": "The first and only line should contain $$$k$$$ integers. The $$$i$$$-th integer is the distance between $$$x_i$$$ and the farthest special vertex from it.", "sample_inputs": ["2 3 2\n2 1\n1 2 3\n1 2 2\n2 2 1", "4 5 3\n1 2 3\n1 2 5\n4 2 1\n2 3 2\n1 4 4\n1 3 3"], "sample_outputs": ["2 2", "3 3 3"], "notes": "NoteIn the first example, the distance between vertex $$$1$$$ and $$$2$$$ equals to $$$2$$$ because one can walk through the edge of weight $$$2$$$ connecting them. So the distance to the farthest node for both $$$1$$$ and $$$2$$$ equals to $$$2$$$.In the second example, one can find that distance between $$$1$$$ and $$$2$$$, distance between $$$1$$$ and $$$3$$$ are both $$$3$$$ and the distance between $$$2$$$ and $$$3$$$ is $$$2$$$.The graph may have multiple edges between and self-loops, as in the first example."}, "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 Edge(v: Int, u: Int, w: Int)\n def solve(): Unit = {\n val N, M, K = ni()\n val X = na(K, -1)\n val E = Array.ofDim[Edge](M)\n REP(M) { i =>\n val u, v = ni() - 1\n val w = ni()\n E(i) = Edge(u, v, w)\n }\n Sorting.quickSort(E)(Ordering.by(_.w))\n\n var ans = -1\n val uf = new UnionFind(N)\n val flg = Array.ofDim[Boolean](N) // \u3053\u306e\u96c6\u5408\u304cspecial\u3092\u542b\u3093\u3067\u3044\u308b\u304b\n REP(K) { i =>\n flg(X(i)) = true\n }\n REP(M) { i =>\n val e = E(i)\n val fu = flg(uf.find(e.u))\n val fv = flg(uf.find(e.v))\n\n // \u5225\u306e\u96c6\u5408\u3067\u3001\u3069\u3063\u3061\u3082special\u3092\u542b\u3093\u3067\u3044\u308b\u306a\u3089\u3053\u306e\u9053\u3092\u901a\u3089\u3056\u308b\u3092\u5f97\u306a\u3044\n if (uf.find(e.u) != uf.find(e.v) && fu && fv) {\n ans = e.w\n }\n uf.unite(e.u, e.v)\n flg(uf.find(e.u)) = fu || fv\n }\n\n out.println(map(K)(_ => ans).mkString(\" \"))\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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "bb38c3a6a0e8b0458a4f5fd27dd3f5d8"} {"nl": {"description": "It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $$$a$$$. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices $$$x, y, z, w$$$ such that $$$a_x + a_y = a_z + a_w$$$.Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?", "input_spec": "The first line contains the single integer $$$n$$$ ($$$4 \\leq n \\leq 200\\,000$$$)\u00a0\u2014 the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 2.5 \\cdot 10^6$$$).", "output_spec": "Print \"YES\" if there are such four indices, and \"NO\" otherwise. If such indices exist, print these indices $$$x$$$, $$$y$$$, $$$z$$$ and $$$w$$$ ($$$1 \\le x, y, z, w \\le n$$$). If there are multiple answers, print any of them.", "sample_inputs": ["6\n2 1 5 2 7 4", "5\n1 3 1 9 20"], "sample_outputs": ["YES\n2 3 1 6", "NO"], "notes": "NoteIn the first example $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Note that there are other answer, for example, 2 3 4 6.In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3$$$"}, "positive_code": [{"source_code": "import java.util.Random\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = nextInts(n).zipWithIndex.sorted\n\n val finish = System.currentTimeMillis() + 1400\n val rnd = new Random()\n\n val aByD, bByD = Array.fill(2600000)(-1)\n\n var done = false\n while (System.currentTimeMillis() < finish && !done) {\n val _a, _b = rnd.nextInt(n)\n if (_a != _b) {\n val a = Math.min(_a, _b)\n val b = Math.max(_a, _b)\n val d = as(b)._1 - as(a)._1\n// println(a, b, d)\n if (aByD(d) >= 0 && aByD(d) != a && aByD(d) != b && bByD(d) != a && bByD(d) != b) {\n done = true\n out.println(\"YES\")\n out.println(s\"${as(a)._2 + 1} ${as(bByD(d))._2 + 1} ${as(b)._2 + 1} ${as(aByD(d))._2 + 1}\")\n } else {\n aByD(d) = a\n bByD(d) = b\n }\n }\n }\n\n// out.println(aByD.take(10).mkString(\" \"))\n// out.println(bByD.take(10).mkString(\" \"))\n if (!done) out.println(\"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": [], "src_uid": "704297bc97528ec27cce5f9388019e29"} {"nl": {"description": "Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word \"helllo\" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words \"helloo\" and \"wwaatt\" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.", "input_spec": "The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.", "output_spec": "Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.", "sample_inputs": ["helloo", "woooooow"], "sample_outputs": ["hello", "woow"], "notes": "NoteThe second valid answer to the test from the statement is \"heloo\"."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: has at least one red bean (or the number of red beans $$$r_i \\ge 1$$$); has at least one blue bean (or the number of blue beans $$$b_i \\ge 1$$$); the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \\le d$$$) Can you distribute all beans?", "input_spec": "The first line contains the single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains three integers $$$r$$$, $$$b$$$, and $$$d$$$ ($$$1 \\le r, b \\le 10^9$$$; $$$0 \\le d \\le 10^9$$$)\u00a0\u2014 the number of red and blue beans and the maximum absolute difference in each packet.", "output_spec": "For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["4\n1 1 0\n2 7 3\n6 1 4\n5 4 0"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first test case, you can form one packet with $$$1$$$ red and $$$1$$$ blue bean. The absolute difference $$$|1 - 1| = 0 \\le d$$$.In the second test case, you can form two packets: $$$1$$$ red and $$$4$$$ blue beans in the first packet and $$$1$$$ red and $$$3$$$ blue beans in the second one.In the third test case, since $$$b = 1$$$, you can form only one packet with $$$6$$$ red and $$$1$$$ blue beans. The absolute difference $$$|6 - 1| = 5 > d$$$.In the fourth test case, since $$$d = 0$$$ so each packet should contain the same number of red and blue beans, but $$$r \\neq b$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "There are two types of burgers in your restaurant \u2014 hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $$$b$$$ buns, $$$p$$$ beef patties and $$$f$$$ chicken cutlets in your restaurant. You can sell one hamburger for $$$h$$$ dollars and one chicken burger for $$$c$$$ dollars. Calculate the maximum profit you can achieve.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2013 the number of queries. The first line of each query contains three integers $$$b$$$, $$$p$$$ and $$$f$$$ ($$$1 \\le b, ~p, ~f \\le 100$$$) \u2014 the number of buns, beef patties and chicken cutlets in your restaurant. The second line of each query contains two integers $$$h$$$ and $$$c$$$ ($$$1 \\le h, ~c \\le 100$$$) \u2014 the hamburger and chicken burger prices in your restaurant.", "output_spec": "For each query print one integer \u2014 the maximum profit you can achieve.", "sample_inputs": ["3\n15 2 3\n5 10\n7 5 2\n10 12\n1 100 100\n100 100"], "sample_outputs": ["40\n34\n0"], "notes": "NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is $$$2 \\cdot 5 + 3 \\cdot 10 = 40$$$.In second query you have to ell one hamburgers and two chicken burgers. Your income is $$$1 \\cdot 10 + 2 \\cdot 12 = 34$$$.In third query you can not create any type of burgers because because you have only one bun. So your income is zero."}, "positive_code": [{"source_code": "object Solution {\n\n\n def main(args: Array[String]): Unit = {\n\n import scala.io.StdIn\n\n\n val t = StdIn.readLine.trim.toInt\n (0 until t).foreach(_ => {\n var arr = StdIn.readLine.trim.split(\" \").map(_.toString.toInt)\n var (b, p, f) = (arr(0), arr(1), arr(2))\n arr = StdIn.readLine.trim.split(\" \").map(_.toString.toInt)\n var (h, c) = (arr(0), arr(1))\n if (h < c) {\n var temp = h\n h = c\n c = temp\n\n temp = p\n p = f\n f = temp\n }\n\n val sum = if (b <= p * 2) b / 2 * h\n else if (b < p * 2 + f * 2) p * h + (b - p * 2) / 2 * c\n else p * h + f * c\n println(sum)\n })\n }\n}"}], "negative_code": [], "src_uid": "92bf30e66f4d5ddebb697d2fa4fa0689"} {"nl": {"description": " William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item \"1\" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items $$$a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\,\\cdots\\, \\,.\\,a_k$$$ and can be one of two types: Add an item $$$a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\cdots \\,.\\, a_k \\,.\\, 1$$$ (starting a list of a deeper level), or Add an item $$$a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\cdots \\,.\\, (a_k + 1)$$$ (continuing the current level). Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the \"Notes\" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the \"Ctrl-S\" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$), which is the number of lines in the list. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$1 \\le a_i \\le n$$$), which is what remains of William's nested list. It is guaranteed that in each test case at least one fitting list exists. It is guaranteed that the sum of values $$$n$$$ across all test cases does not exceed $$$10^3$$$.", "output_spec": "For each test case output $$$n$$$ lines which represent a valid nested list, which could become the data provided to you by William. If there are multiple answers, print any.", "sample_inputs": ["2\n4\n1\n1\n2\n3\n9\n1\n1\n1\n2\n2\n1\n2\n1\n2"], "sample_outputs": ["1\n1.1\n1.2\n1.3\n1\n1.1\n1.1.1\n1.1.2\n1.2\n1.2.1\n2\n2.1\n2.2"], "notes": "NoteIn the second example test case one example of a fitting list is:11.1 1.1.11.1.21.21.2.122.12.2This list can be produced by using the sequence of operations shown below: Original list with a single item $$$1$$$. Insert item $$$2$$$ by using the insertion operation of the second type after item $$$1$$$. Insert item $$$1.1$$$ by using the insertion operation of the first type after item $$$1$$$. Insert item $$$1.2$$$ by using the insertion operation of the second type after item $$$1.1$$$. Insert item $$$1.1.1$$$ by using the insertion operation of the first type after item $$$1.1$$$. Insert item $$$1.1.2$$$ by using the insertion operation of the second type after item $$$1.1.1$$$. Insert item $$$1.2.1$$$ by using the insertion operation of the first type after item $$$1.2$$$. Insert item $$$2.1$$$ by using the insertion operation of the first type after item $$$2$$$. Insert item $$$2.2$$$ by using the insertion operation of the second type after item $$$2.1$$$. "}, "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 n = readInt()\r\n val an = Array.fill(n)(readShort())\r\n\r\n def go(level: List[Short], i: Int): Unit =\r\n if (i == n) ()\r\n else {\r\n val ai = an(i)\r\n val next =\r\n if (ai == 1) (1: Short) :: level\r\n else if (ai == level.head + 1) ai :: level.tail\r\n else ai :: level.dropWhile(_ + 1 != ai).tail\r\n\r\n println(next.reverse.mkString(\".\"))\r\n\r\n go(next, i + 1)\r\n }\r\n\r\n go(Nil, 0)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "c1bf6c8a9a20f377cf2a5dbea2267c88"} {"nl": {"description": "Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $$$n$$$ elements. The $$$i$$$-th element is $$$a_i$$$ ($$$i$$$ = $$$1, 2, \\ldots, n$$$). He gradually takes the first two leftmost elements from the deque (let's call them $$$A$$$ and $$$B$$$, respectively), and then does the following: if $$$A > B$$$, he writes $$$A$$$ to the beginning and writes $$$B$$$ to the end of the deque, otherwise, he writes to the beginning $$$B$$$, and $$$A$$$ writes to the end of the deque. We call this sequence of actions an operation.For example, if deque was $$$[2, 3, 4, 5, 1]$$$, on the operation he will write $$$B=3$$$ to the beginning and $$$A=2$$$ to the end, so he will get $$$[3, 4, 5, 1, 2]$$$.The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $$$q$$$ queries. Each query consists of the singular number $$$m_j$$$ $$$(j = 1, 2, \\ldots, q)$$$. It is required for each query to answer which two elements he will pull out on the $$$m_j$$$-th operation.Note that the queries are independent and for each query the numbers $$$A$$$ and $$$B$$$ should be printed in the order in which they will be pulled out of the deque.Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\leq n \\leq 10^5$$$, $$$0 \\leq q \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the number of elements in the deque and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ $$$(0 \\leq a_i \\leq 10^9)$$$\u00a0\u2014 the deque element in $$$i$$$-th position. The next $$$q$$$ lines contain one number each, meaning $$$m_j$$$ ($$$1 \\leq m_j \\leq 10^{18}$$$).", "output_spec": "For each teacher's query, output two numbers $$$A$$$ and $$$B$$$\u00a0\u2014 the numbers that Valeriy pulls out of the deque for the $$$m_j$$$-th operation.", "sample_inputs": ["5 3\n1 2 3 4 5\n1\n2\n10", "2 0\n0 0"], "sample_outputs": ["1 2\n2 3\n5 2", ""], "notes": "Note Consider all 10 steps for the first test in detail: $$$[1, 2, 3, 4, 5]$$$\u00a0\u2014 on the first operation, $$$A$$$ and $$$B$$$ are $$$1$$$ and $$$2$$$, respectively.So, $$$2$$$ we write to the beginning of the deque, and $$$1$$$\u00a0\u2014 to the end.We get the following status of the deque: $$$[2, 3, 4, 5, 1]$$$. $$$[2, 3, 4, 5, 1] \\Rightarrow A = 2, B = 3$$$. $$$[3, 4, 5, 1, 2]$$$ $$$[4, 5, 1, 2, 3]$$$ $$$[5, 1, 2, 3, 4]$$$ $$$[5, 2, 3, 4, 1]$$$ $$$[5, 3, 4, 1, 2]$$$ $$$[5, 4, 1, 2, 3]$$$ $$$[5, 1, 2, 3, 4]$$$ $$$[5, 2, 3, 4, 1] \\Rightarrow A = 5, B = 2$$$. "}, "positive_code": [{"source_code": "//package round569\n\nimport scala.io.StdIn._\n\nobject TaskC extends App {\n val Array(n, q) = readLine.split(\" \").map(_.toInt)\n\n var maxElement = Integer.MIN_VALUE\n\n val arr = readLine.split(\" \").map(_.toInt)\n\n val copy = arr.clone()\n\n val maxVals = arr.map{x => if(x > maxElement) {maxElement = x; x} else maxElement}\n\n for (i <- 1 to n-1) {\n if (arr(i-1) > arr(i)) {\n val temp = arr(i-1)\n arr(i-1) = arr(i)\n arr(i) = temp\n }\n }\n\n for (_ <- 1 to q) {\n val m = readLong\n if (m < n.toLong) {\n println(s\"${maxVals(m.toInt-1)} ${copy(m.toInt)}\")\n } else {\n val idx = ((m-1) % (n-1)).toInt\n println(s\"${arr(n-1)} ${arr(idx)}\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package round569\n\nimport scala.io.StdIn._\n\nobject TaskC extends App {\n val Array(n, q) = readLine.split(\" \").map(_.toInt)\n\n var maxElement = Integer.MIN_VALUE\n\n val arr = readLine.split(\" \").map(_.toInt)\n\n val copy = arr.clone()\n\n val maxVals = arr.map{x => if(x > maxElement) {maxElement = x; x} else maxElement}\n\n for (i <- 1 to n-1) {\n if (arr(i-1) > arr(i)) {\n val temp = arr(i-1)\n arr(i-1) = arr(i)\n arr(i) = temp\n }\n }\n\n for (_ <- 1 to q) {\n val m = readLong\n if (m < n.toLong) {\n println(s\"${maxVals(m.toInt-1)} ${copy(m.toInt)}\")\n } else {\n val idx = ((m+1) % n).toInt\n println(s\"${arr(n-1)} ${arr(idx)}\")\n }\n }\n}\n"}], "src_uid": "3cb19ef77e9cb919a2f0a1d687b2845d"} {"nl": {"description": "You are given array $$$a_1, a_2, \\dots, a_n$$$. Find the subsegment $$$a_l, a_{l+1}, \\dots, a_r$$$ ($$$1 \\le l \\le r \\le n$$$) with maximum arithmetic mean $$$\\frac{1}{r - l + 1}\\sum\\limits_{i=l}^{r}{a_i}$$$ (in floating-point numbers, i.e. without any rounding).If there are many such subsegments find the longest one.", "input_spec": "The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$) \u2014 the array $$$a$$$.", "output_spec": "Print the single integer \u2014 the length of the longest subsegment with maximum possible arithmetic mean.", "sample_inputs": ["5\n6 1 6 6 0"], "sample_outputs": ["2"], "notes": "NoteThe subsegment $$$[3, 4]$$$ is the longest among all subsegments with maximum arithmetic mean."}, "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 mx = A.max\n var cnt = 0\n var ans = 0\n REP(N) { i =>\n if (A(i) == mx) cnt += 1\n else cnt = 0\n ans = max(ans, cnt)\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": "5db2ae5b2c91b29e4fe4a45ab864e3f1"} {"nl": {"description": "Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \\ne j$$$; $$$1 \\leq i,j \\leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.", "input_spec": "The first line contains a single positive integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 100$$$)\u00a0\u2014 the sequence $$$a$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the minimum number of operations to change all numbers in the sequence to $$$0$$$.", "sample_inputs": ["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"], "sample_outputs": ["4\n3\n2"], "notes": "NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 < a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$."}, "positive_code": [{"source_code": "object Task1 extends App {\r\n\r\n import scala.io.StdIn\r\n\r\n def readLine: String = StdIn.readLine()\r\n\r\n def readNum: Int = StdIn.readLine().toInt\r\n\r\n val testCases = readNum\r\n\r\n for (_ <- 0 until testCases) {\r\n readLine\r\n val nums = readLine.split(\" \").map(_.toInt)\r\n\r\n val numsSet = nums.toSet\r\n\r\n if (numsSet.contains(0)) {\r\n val zerosCount = nums.count(_ == 0)\r\n println(nums.length - zerosCount)\r\n } else {\r\n if (numsSet.size == nums.length) {\r\n println(nums.length + 1)\r\n } else {\r\n println(nums.length)\r\n }\r\n }\r\n }\r\n\r\n}"}], "negative_code": [], "src_uid": "ad242f98f1c8eb8d30789ec672fc95a0"} {"nl": {"description": "You are given a string $$$s$$$. You have to reverse it \u2014 that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal \u2014 and so on. For example, if your goal is to reverse the string \"abddea\", you should get the string \"aeddba\". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 200\\,000$$$) \u2014 the length of $$$s$$$. The second line contains $$$s$$$ \u2014 a string consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "Print one integer \u2014 the minimum number of swaps of neighboring elements you have to perform to reverse the string.", "sample_inputs": ["5\naaaza", "6\ncbaabc", "9\nicpcsguru"], "sample_outputs": ["2", "0", "30"], "notes": "NoteIn the first example, you have to swap the third and the fourth elements, so the string becomes \"aazaa\". Then you have to swap the second and the third elements, so the string becomes \"azaaa\". So, it is possible to reverse the string in two swaps.Since the string in the second example is a palindrome, you don't have to do anything to reverse it."}, "positive_code": [{"source_code": "object E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val s = nextLine\n val s2 = s.reverse\n val pos = Array.fill(n)(-1)\n\n def countInversions(xs: Array[Int]): (Long, Array[Int]) = {\n\n if (xs.size == 1) (0, xs)\n else {\n val mid = xs.size / 2\n val (lInv, ls) = countInversions(xs.take(mid))\n val (rInv, rs) = countInversions(xs.drop(mid))\n val res = Array.ofDim[Int](xs.size)\n var i, j, k = 0\n var mInv = 0L\n while (k < xs.size) {\n if (j == rs.size || (i < ls.size && ls(i) < rs(j))) {\n res(k) = ls(i)\n i += 1\n } else {\n res(k) = rs(j)\n mInv += (ls.size - i)\n j += 1\n }\n k += 1\n }\n (lInv + rInv + mInv, res)\n }\n }\n\n for (c <- 'a' to 'z') {\n var i, j = 0\n while (i < n) {\n while (i < n && s(i) != c) {\n i += 1\n }\n if (i < n) {\n while (s2(j) != c) {\n j += 1\n }\n pos(i) = j\n i += 1\n j += 1\n }\n }\n }\n\n val (res, _) = countInversions(pos)\n\n out.println(res)\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": "c1f50da1fbe797e7c9b982583a3b02d5"} {"nl": {"description": "Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns \u2014 from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x,\u2009y). The table corners are cells: (1,\u20091), (n,\u20091), (1,\u2009m), (n,\u2009m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1,\u2009y1), an arbitrary corner of the table (x2,\u2009y2) and color all cells of the table (p,\u2009q), which meet both inequations: min(x1,\u2009x2)\u2009\u2264\u2009p\u2009\u2264\u2009max(x1,\u2009x2), min(y1,\u2009y2)\u2009\u2264\u2009q\u2009\u2264\u2009max(y1,\u2009y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.", "input_spec": "The first line contains exactly two integers n, m (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1,\u2009ai2,\u2009...,\u2009aim. If aij equals zero, then cell (i,\u2009j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.", "output_spec": "Print a single number \u2014 the minimum number of operations Simon needs to carry out his idea.", "sample_inputs": ["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2,\u20092) and corner (1,\u20091). For the second time you need to choose cell (2,\u20092) and corner (3,\u20093). For the third time you need to choose cell (2,\u20092) and corner (3,\u20091). For the fourth time you need to choose cell (2,\u20092) and corner (1,\u20093). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3,\u20091) and corner (4,\u20093). For the second time you need to choose cell (2,\u20093) and corner (1,\u20091). "}, "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": "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"}, {"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"} {"nl": {"description": "The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310\u2009=\u200911012, so it has 3 bits set and 13 will be reduced to 3 in one operation.He calls a number special if the minimum number of operations to reduce it to 1 is k.He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about to reach his destination!Since the answer can be large, output it modulo 109\u2009+\u20097.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009<\u200921000). The second line contains integer k (0\u2009\u2264\u2009k\u2009\u2264\u20091000). Note that n is given in its binary representation without any leading zeros.", "output_spec": "Output a single integer\u00a0\u2014 the number of special numbers not greater than n, modulo 109\u2009+\u20097.", "sample_inputs": ["110\n2", "111111011\n2"], "sample_outputs": ["3", "169"], "notes": "NoteIn the first sample, the three special numbers are 3, 5 and 6. They get reduced to 2 in one operation (since there are two set bits in each of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2)."}, "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\n val MOD = 1000000007\n val n = readLine\n val nn = n.length\n val Array(k) = readInts(1)\n\n val pascal = Array.ofDim[Long](1001, 1001)\n for (i <- pascal.indices) pascal(i)(0) = 1L\n for (i <- 1 until pascal.length) {\n for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD\n }\n\n val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)\n\n var counts = Array.fill(nn + 1) { 0L }\n counts(1) = 1L\n\n for (_ <- 1 until k) {\n val counts2 = Array.fill(nn + 1) { 0L }\n for (i <- 1 to nn) {\n if (counts(i) > 0) {\n for (b <- byBitCount(i)) if (counts(b) == 0) {\n counts2(b) = (counts2(b) + counts(i)) % MOD\n }\n }\n }\n counts = counts2\n }\n\n var res = counts(n.count(_ == '1'))\n\n for (ones <- counts.indices) {\n if (counts(ones) > 0) {\n var onesUsed = 0\n for (i <- 0 until nn) {\n if (n(i) == '1') {\n val remainingBits = n.length - i - 1\n val remainingOnes = ones - onesUsed\n if (remainingOnes >= 0) {\n res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD\n }\n onesUsed += 1\n }\n }\n }\n }\n\n println(if (k == 0) 1 else if (k == 1) nn - 1L else res)\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\n val MOD = 1000000007\n val n = readLine\n val nn = n.length\n val Array(k) = readInts(1)\n\n val pascal = Array.ofDim[Long](1001, 1001)\n for (i <- pascal.indices) pascal(i)(0) = 1L\n for (i <- 1 until pascal.length) {\n for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD\n }\n\n val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)\n\n var counts = Array.fill(nn + 1) { 0L }\n counts(1) = 1L\n\n for (_ <- 1 until k) {\n val counts2 = Array.fill(nn + 1) { 0L }\n for (i <- 1 to nn) {\n if (counts(i) > 0) {\n for (b <- byBitCount(i)) if (counts(b) == 0) {\n counts2(b) = (counts2(b) + counts(i)) % MOD\n }\n }\n }\n counts = counts2\n }\n\n var res = if (k == 1) 0L else counts(n.count(_ == '1'))\n\n for (ones <- counts.indices) {\n if (counts(ones) > 0) {\n var onesUsed = 0\n for (i <- 0 until nn) {\n if (n(i) == '1') {\n val remainingBits = n.length - i - 1\n val remainingOnes = ones - onesUsed\n if (remainingOnes >= 0) {\n res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD\n }\n onesUsed += 1\n }\n }\n }\n }\n\n println(if (k == 0) 1 else res)\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 MOD = 1000000007\n val n = readLine\n val nn = n.length\n val Array(k) = readInts(1)\n\n val pascal = Array.ofDim[Long](1001, 1001)\n for (i <- pascal.indices) pascal(i)(0) = 1L\n for (i <- 1 until pascal.length) {\n for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD\n }\n\n val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)\n\n var counts = Array.fill(nn + 1) { 0L }\n counts(1) = 1L\n\n for (_ <- 1 until k) {\n val counts2 = Array.fill(nn + 1) { 0L }\n for (i <- 1 to nn) {\n if (counts(i) > 0) {\n for (b <- byBitCount(i)) if (counts(b) == 0) {\n counts2(b) = (counts2(b) + counts(i)) % MOD\n }\n }\n }\n counts = counts2\n }\n\n var res = counts(n.count(_ == '1'))\n\n for (ones <- counts.indices) {\n if (counts(ones) > 0) {\n var onesUsed = 0\n for (i <- 0 until nn) {\n if (n(i) == '1') {\n val remainingBits = n.length - i - 1\n val remainingOnes = ones - onesUsed\n if (remainingOnes >= 0) {\n res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD\n }\n onesUsed += 1\n }\n }\n }\n }\n\n println(if (k == 0) 1 else res)\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 MOD = 1000000007\n val n = readLine\n val nn = n.length\n val Array(k) = readInts(1)\n\n var counts = Array.fill(nn + 1) { 0L }\n counts(1) = 1L\n\n val pascal = Array.ofDim[Long](1001, 1001)\n for (i <- pascal.indices) pascal(i)(0) = 1L\n for (i <- 1 until pascal.length) {\n for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD\n }\n\n val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)\n\n for (_ <- 1 until k) {\n val counts2 = Array.fill(nn + 1) { 0L }\n for (i <- 1 to nn) {\n if (counts(i) > 0) {\n for (b <- byBitCount(i)) if (counts(b) == 0) {\n counts2(b) = (counts2(b) + counts(i)) % MOD\n }\n }\n }\n counts = counts2\n }\n\n var res = counts(n.count(_ == '1'))\n\n for (ones <- counts.indices) {\n if (counts(ones) > 0) {\n var onesUsed = 0\n for (i <- 0 until nn) {\n if (n(i) == '1') {\n val remainingBits = n.length - i - 1\n val remainingOnes = ones - onesUsed\n if (remainingOnes >= 0) {\n res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD\n }\n onesUsed += 1\n }\n }\n }\n }\n\n println(res)\n}\n"}], "src_uid": "e367f5d18b08882ec518b2d4188ccdea"} {"nl": {"description": "Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.For example, suppose Mikhail is suggested to work on three projects and a1\u2009=\u20096, b1\u2009=\u20092, a2\u2009=\u20091, b2\u2009=\u20093, a3\u2009=\u20092, b3\u2009=\u20096. Also, p\u2009=\u200920 and q\u2009=\u200920. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1\u00b72.5\u2009+\u2009a2\u00b70\u2009+\u2009a3\u00b72.5\u2009=\u20096\u00b72.5\u2009+\u20091\u00b70\u2009+\u20092\u00b72.5\u2009=\u200920 and b1\u00b72.5\u2009+\u2009b2\u00b70\u2009+\u2009b3\u00b72.5\u2009=\u20092\u00b72.5\u2009+\u20093\u00b70\u2009+\u20096\u00b72.5\u2009=\u200920.", "input_spec": "The first line of the input contains three integers n, p and q (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009p,\u2009q\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the number of projects and the required number of experience and money. Each of the next n lines contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the daily increase in experience and daily income for working on the i-th project.", "output_spec": "Print a real value\u00a0\u2014 the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 20 20\n6 2\n1 3\n2 6", "4 1 1\n2 3\n3 2\n2 3\n3 2"], "sample_outputs": ["5.000000000000000", "0.400000000000000"], "notes": "NoteFirst sample corresponds to the example in the problem statement."}, "positive_code": [{"source_code": "object E{\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 \n val t0 = System.nanoTime()\n \n \n \n //code starts here\n val (n,p,q)=(nextInt,nextDouble,nextDouble)\n\n val ab=(for(i<-0 until n) yield (nextLong,nextLong)).distinct.sorted\n var maxBi=0\n var maxB:Double=0\n val idx=Array.ofDim[Int](n)\n for(i<-0 until ab.length){\n if(maxB1 && (ab(i)._2-ab(idx(il-1))._2)*(ab(idx(il-1))._1-ab(idx(il-2))._1)>(ab(idx(il-1))._2-ab(idx(il-2))._2)*(ab(i)._1-ab(idx(il-1))._1)){\n il-=1\n }\n idx(il)=i\n il+=1\n }\n if(ab(idx(0))._2*p<=q*ab(idx(0))._1){\n out.println(q/ab(idx(0))._2)\n }else if( (ab(idx(il - 1))._2)*p >= q* (ab(idx(il-1))._1)){\n\n out.println(p/(ab(idx(il-1))._1))\n }\n else{\n var l=0\n var r=il\n while(lq*ab(idx(mid))._1){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=p*b2-q*a2\n val Dy= -p*b1+q*a1\n out.println((Dx+Dy)/D)\n }\n \n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "object E{\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,p,q)=(nextInt,nextDouble,nextDouble)\n val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)\n val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct\n var maxBi=0\n var maxB:Double=0\n val idx=ArrayBuffer[Int]()\n for(i<-0 until ab.length){\n if(maxB1 && (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){\n idx-=idx(idx.length-1)\n \n out.flush\n }\n idx+=i\n }\n \n if(ab(idx(0))._2/ab(idx(0))._1<=q/p){\n if(n==100000){\n out.println(\"1\")\n }\n out.println(q/ab(idx(0))._2)\n }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){\n if(n==100000){\n out.println(\"2\")\n }\n out.println(p/(ab(idx(idx.length-1))._1))\n }\n else{\n var l=0\n var r=idx.length\n while(lq/p){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=q*b2-p*a2\n val Dy= -q*b1+p*a1\n if(n==100000){\n out.println(\"3 \"+l+\" \"+r)\n }\n //out.println(D+\" \"+Dx+\" \"+Dy)\n out.println((Dx+Dy)/D)\n \n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object E{\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,p,q)=(nextInt,nextDouble,nextDouble)\n val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)\n val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct\n var maxBi=0\n var maxB:Double=0\n val idx=ArrayBuffer[Int]()\n for(i<-0 until ab.length){\n if(maxB1 && (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){\n idx-=idx(idx.length-1)\n \n out.flush\n }\n idx+=i\n }\n \n if(ab(idx(0))._2/ab(idx(0))._1<=q/p){\n \n out.println(q/ab(idx(0))._2)\n }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){\n \n out.println(p/(ab(idx(idx.length-1))._1))\n }\n else{\n var l=0\n var r=idx.length\n while(lq/p){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=q*b2-p*a2\n val Dy= -q*b1+p*a1\n if(n==100000){\n out.println(\"3 \"+l+\" \"+r)\n out.println(a1+\" \"+b1)\n out.println(a2+\" \"+b2)\n out.println(D+\" \"+Dx+\" \"+Dy) \n }\n \n out.println((Dx+Dy)/D)\n \n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object E{\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,p,q)=(nextInt,nextDouble,nextDouble)\n val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)\n val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct\n var maxBi=0\n var maxB:Double=0\n val idx=ArrayBuffer[Int]()\n for(i<-0 until ab.length){\n if(maxB1 && (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){\n idx-=idx(idx.length-1)\n \n out.flush\n }\n idx+=i\n }\n //out.println(idx)\n //ab.foreach(m=>out.println(m))\n if(ab(idx(0))._2/ab(idx(0))._1<=q/p){\n out.println(q/ab(idx(0))._2)\n }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){\n out.println(p/(ab(idx(idx.length-1))._1))\n }\n else{\n var l=0\n var r=idx.length\n while(lq/p){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=q*b2-p*a2\n val Dy= -q*b1+p*a1\n //out.println(D+\" \"+Dx+\" \"+Dy)\n out.println((Dx+Dy)/D)\n \n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object E{\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,p,q)=(nextInt,nextDouble,nextDouble)\n val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)\n val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1)\n var maxBi=0\n var maxB:Double=0\n val idx=ArrayBuffer[Int]()\n for(i<-0 until n){\n if(maxB1 && (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){\n idx-=idx(idx.length-1)\n \n out.flush\n }\n idx+=i\n }\n //out.println(idx)\n //ab.foreach(m=>out.println(m))\n if(ab(idx(0))._2/ab(idx(0))._1 q / p){\n out.println(p/(ab(idx(idx.length-1))._1))\n }\n else{\n var l=0\n var r=idx.length\n while(lq/p){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=q*b2-p*a2\n val Dy= -q*b1+p*a1\n //out.println(D+\" \"+Dx+\" \"+Dy)\n out.println((Dx+Dy)/D)\n \n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object E{\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,p,q)=(nextInt,nextDouble,nextDouble)\n val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)\n val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1)\n var maxBi=0\n var maxB:Double=0\n val idx=ArrayBuffer[Int]()\n for(i<-0 until n){\n if(maxB1 && (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){\n idx-=idx(idx.length-1)\n out.println(idx)\n out.flush\n }\n idx+=i\n }\n //out.println(idx)\n //ab.foreach(m=>out.println(m))\n if(ab(idx(0))._2/ab(idx(0))._1 q / p){\n out.println(p/(ab(idx(idx.length-1))._1))\n }\n else{\n var l=0\n var r=idx.length\n while(lq/p){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=q*b2-p*a2\n val Dy= -q*b1+p*a1\n //out.println(D+\" \"+Dx+\" \"+Dy)\n out.println((Dx+Dy)/D)\n \n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object E{\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 \n val t0 = System.nanoTime()\n \n \n \n //code starts here\n val (n,p,q)=(nextInt,nextDouble,nextDouble)\n\n val ab=(for(i<-0 until n) yield (nextLong,nextLong)).distinct.sorted\n var maxBi=0\n var maxB:Double=0\n val idx=Array.ofDim[Int](n)\n for(i<-0 until ab.length){\n if(maxB1 && (ab(i)._2-ab(idx(il-1))._2)*(ab(idx(il-1))._1-ab(idx(il-2))._1)>(ab(idx(il-1))._2-ab(idx(il-2))._2)*(ab(i)._1-ab(idx(il-1))._1)){\n il-=1\n }\n idx(il)=i\n il+=1\n }\n if(n==100000 && p==487300){\n val t1 = System.nanoTime()\n out.println(\"Elapsed time: \" + (t1 - t0) + \"ns\")\n out.flush\n }\n if(ab(idx(0))._2*p<=q*ab(idx(0))._1){\n out.println(q/ab(idx(0))._2)\n }else if( (ab(idx(il - 1))._2)*p >= q* (ab(idx(il-1))._1)){\n\n out.println(p/(ab(idx(il-1))._1))\n }\n else{\n var l=0\n var r=il\n while(lq*ab(idx(mid))._1){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=p*b2-q*a2\n val Dy= -p*b1+q*a1\n if(n==100000 && p==487300 ){\n val t1 = System.nanoTime()\n println(\"Elapsed time: \" + (t1 - t0) + \"ns\")\n out.flush\n }\n out.println((Dx+Dy)/D)\n }\n \n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object E{\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,p,q)=(nextInt,nextDouble,nextDouble)\n val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)\n val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct\n var maxBi=0\n var maxB:Double=0\n val idx=ArrayBuffer[Int]()\n for(i<-0 until ab.length){\n if(maxB1 && (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){\n idx-=idx(idx.length-1)\n \n out.flush\n }\n idx+=i\n }\n if(n==100000){\n out.println(idx)\n ab.foreach(m=>out.println(m))\n }\n if(ab(idx(0))._2/ab(idx(0))._1<=q/p){\n if(n==100000){\n out.println(\"1\")\n }\n out.println(q/ab(idx(0))._2)\n }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){\n if(n==100000){\n out.println(\"2\")\n }\n out.println(p/(ab(idx(idx.length-1))._1))\n }\n else{\n var l=0\n var r=idx.length\n while(lq/p){\n l=mid\n }else{\n r=mid\n }\n }\n val (a1,b1)=ab(idx(l))\n val (a2,b2)=ab(idx(r))\n val D=a1*b2-a2*b1\n val Dx=q*b2-p*a2\n val Dy= -q*b1+p*a1\n if(n==100000){\n out.println(\"3 \"+l+\" \"+r)\n }\n //out.println(D+\" \"+Dx+\" \"+Dy)\n out.println((Dx+Dy)/D)\n \n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "131db180c7afad3e5a3342407408fded"} {"nl": {"description": "Greg has an array a\u2009=\u2009a1,\u2009a2,\u2009...,\u2009an and m operations. Each operation looks as: li, ri, di, (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). To apply operation i to the array means to increase all array elements with numbers li,\u2009li\u2009+\u20091,\u2009...,\u2009ri by value di.Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1\u2009\u2264\u2009xi\u2009\u2264\u2009yi\u2009\u2264\u2009m). That means that one should apply operations with numbers xi,\u2009xi\u2009+\u20091,\u2009...,\u2009yi to the array.Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.", "input_spec": "The first line contains integers n, m, k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u2009105). The second line contains n integers: a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n), (0\u2009\u2264\u2009di\u2009\u2264\u2009105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1\u2009\u2264\u2009xi\u2009\u2264\u2009yi\u2009\u2264\u2009m). The numbers in the lines are separated by single spaces.", "output_spec": "On a single line print n integers a1,\u2009a2,\u2009...,\u2009an \u2014 the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.", "sample_inputs": ["3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3", "1 1 1\n1\n1 1 1\n1 1", "4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3"], "sample_outputs": ["9 18 17", "2", "5 18 31 20"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": " Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $$$7$$$ segments, which can be turned on or off to display different numbers. The picture shows how all $$$10$$$ decimal digits are displayed: After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $$$k$$$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $$$k$$$ sticks (which are off now)? It is allowed that the number includes leading zeros.", "input_spec": "The first line contains integer $$$n$$$ $$$(1 \\leq n \\leq 2000)$$$ \u00a0\u2014 the number of digits on scoreboard and $$$k$$$ $$$(0 \\leq k \\leq 2000)$$$ \u00a0\u2014 the number of segments that stopped working. The next $$$n$$$ lines contain one binary string of length $$$7$$$, the $$$i$$$-th of which encodes the $$$i$$$-th digit of the scoreboard. Each digit on the scoreboard consists of $$$7$$$ segments. We number them, as in the picture below, and let the $$$i$$$-th place of the binary string be $$$0$$$ if the $$$i$$$-th stick is not glowing and $$$1$$$ if it is glowing. Then a binary string of length $$$7$$$ will specify which segments are glowing now. Thus, the sequences \"1110111\", \"0010010\", \"1011101\", \"1011011\", \"0111010\", \"1101011\", \"1101111\", \"1010010\", \"1111111\", \"1111011\" encode in sequence all digits from $$$0$$$ to $$$9$$$ inclusive.", "output_spec": "Output a single number consisting of $$$n$$$ digits \u00a0\u2014 the maximum number that can be obtained if you turn on exactly $$$k$$$ sticks or $$$-1$$$, if it is impossible to turn on exactly $$$k$$$ sticks so that a correct number appears on the scoreboard digits.", "sample_inputs": ["1 7\n0000000", "2 5\n0010010\n0010010", "3 5\n0100001\n1001001\n1010011"], "sample_outputs": ["8", "97", "-1"], "notes": "NoteIn the first test, we are obliged to include all $$$7$$$ sticks and get one $$$8$$$ digit on the scoreboard.In the second test, we have sticks turned on so that units are formed. For $$$5$$$ of additionally included sticks, you can get the numbers $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ and $$$97$$$, of which we choose the maximum \u00a0\u2014 $$$97$$$.In the third test, it is impossible to turn on exactly $$$5$$$ sticks so that a sequence of numbers appears on the scoreboard."}, "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 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"}, {"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"} {"nl": {"description": "In the Bus of Characters there are $$$n$$$ rows of seat, each having $$$2$$$ seats. The width of both seats in the $$$i$$$-th row is $$$w_i$$$ centimeters. All integers $$$w_i$$$ are distinct.Initially the bus is empty. On each of $$$2n$$$ stops one passenger enters the bus. There are two types of passengers: an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$) \u2014 the number of rows in the bus. The second line contains the sequence of integers $$$w_1, w_2, \\dots, w_n$$$ ($$$1 \\le w_i \\le 10^{9}$$$), where $$$w_i$$$ is the width of each of the seats in the $$$i$$$-th row. It is guaranteed that all $$$w_i$$$ are distinct. The third line contains a string of length $$$2n$$$, consisting of digits '0' and '1' \u2014 the description of the order the passengers enter the bus. If the $$$j$$$-th character is '0', then the passenger that enters the bus on the $$$j$$$-th stop is an introvert. If the $$$j$$$-th character is '1', the the passenger that enters the bus on the $$$j$$$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i.\u00a0e. both numbers equal $$$n$$$), and for each extrovert there always is a suitable row.", "output_spec": "Print $$$2n$$$ integers \u2014 the rows the passengers will take. The order of passengers should be the same as in input.", "sample_inputs": ["2\n3 1\n0011", "6\n10 8 9 11 13 5\n010010011101"], "sample_outputs": ["2 1 1 2", "6 6 2 3 3 1 4 4 1 2 5 5"], "notes": "NoteIn the first example the first passenger (introvert) chooses the row $$$2$$$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $$$1$$$, because it is the only empty row now. The third passenger (extrovert) chooses the row $$$1$$$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $$$2$$$, because it is the only row with an empty place."}, "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_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"}, {"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"} {"nl": {"description": "Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \\dots, b_n$$$ is called nondecreasing if $$$b_i\\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \\leq a_{i} \\leq 10^9)$$$\u00a0\u2014 the heights of the supports. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.", "sample_inputs": ["3\n4\n5 3 2 5\n5\n1 2 3 5 3\n3\n1 1 1"], "sample_outputs": ["3\n2\n0"], "notes": "NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \\textbf{2}, 5] \\to [5, 3, \\textbf{3}, 5]$$$Second operation:$$$[5, \\textbf{3}, \\textbf{3}, 5] \\to [5, \\textbf{4}, \\textbf{4}, 5]$$$Third operation:$$$[5, \\textbf{4}, \\textbf{4}, 5] \\to [5, \\textbf{5}, \\textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations."}, "positive_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: 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}"}, {"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"} {"nl": {"description": "Vova promised himself that he would never play computer games... But recently Firestorm \u2014 a well-known game developing company \u2014 published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.", "input_spec": "The first line contains two integer numbers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0\u2009\u2264\u2009ci\u2009\u2264\u2009109) \u2014 the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi,\u2009yi) which represent that characters xi and yi are friends (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi). It is guaranteed that each pair is listed at most once.", "output_spec": "Print one number \u2014 the minimum amount of gold Vova has to spend in order to finish the quest.", "sample_inputs": ["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"], "sample_outputs": ["10", "55", "15"], "notes": "NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters."}, "positive_code": [{"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 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": "\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"}, {"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"} {"nl": {"description": "You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room. Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?", "input_spec": "The first line contains the single integer $$$t$$$ ($$$1 \\le t \\le 5000$$$)\u00a0\u2014 the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \\le W, H \\le 10^8$$$)\u00a0\u2014 the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \\le x_1 < x_2 \\le W$$$; $$$0 \\le y_1 < y_2 \\le H$$$)\u00a0\u2014 the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \\le w \\le W$$$; $$$1 \\le h \\le H$$$)\u00a0\u2014 the width and the height of the second table.", "output_spec": "For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.", "sample_inputs": ["5\n8 5\n2 1 7 4\n4 2\n5 4\n2 2 5 4\n3 3\n1 8\n0 3 1 6\n1 5\n8 1\n3 0 6 1\n5 1\n8 10\n4 5 7 8\n8 5"], "sample_outputs": ["1.000000000\n-1\n2.000000000\n2.000000000\n0.000000000"], "notes": "NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$."}, "positive_code": [{"source_code": "import java.io.PrintWriter\r\nimport java.util.Scanner\r\n\r\ncase class InputB(W: Int, H: Int, x1: Int, y1: Int, x2: Int, y2: Int, w: Int, h: Int)\r\n\r\nobject Solution {\r\n def solve(input: InputB): Int = {\r\n // result is gonna be either: (0 0, w h) or (W 0, W-w h) or (0 H, w, H-h) or (W H, W-w, H-h)\r\n // to avoid intersection you can move either to the left or to the right or up or down\r\n\r\n var ans = Int.MaxValue\r\n\r\n // move to the right\r\n {\r\n val toMove = if (input.x1 < input.w) input.w - input.x1 else 0\r\n val newEnd = input.x2 + toMove\r\n if (newEnd <= input.W) ans = Math.min(ans, toMove)\r\n }\r\n\r\n // move up\r\n {\r\n val toMove = if (input.y1 < input.h) input.h - input.y1 else 0\r\n val newEnd = input.y2 + toMove\r\n if (newEnd <= input.H) ans = Math.min(ans, toMove)\r\n }\r\n\r\n // move to the left\r\n {\r\n val toMove = if (input.x2 > input.W - input.w) input.x2 - (input.W - input.w) else 0\r\n val newEnd = input.x1 - toMove\r\n if (newEnd >= 0) ans = Math.min(ans, toMove)\r\n }\r\n\r\n // move down\r\n {\r\n val toMove = if (input.y2 > input.H - input.h) input.y2 - (input.H-input.h) else 0\r\n val newEnd = input.y1 - toMove\r\n if (newEnd >= 0) ans = Math.min(ans, toMove)\r\n }\r\n\r\n if (ans == Int.MaxValue) -1 else ans\r\n }\r\n\r\n def run(test: Int, input: Scanner, output: PrintWriter): Unit = {\r\n val inputB = InputB(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt())\r\n output.println(solve(inputB))\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": "29fd4c77a2f28478ebce98dfc6496aac"} {"nl": {"description": "We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: The array consists of $$$n$$$ distinct positive (greater than $$$0$$$) integers. The array contains two elements $$$x$$$ and $$$y$$$ (these elements are known for you) such that $$$x < y$$$. If you sort the array in increasing order (such that $$$a_1 < a_2 < \\ldots < a_n$$$), differences between all adjacent (consecutive) elements are equal (i.e. $$$a_2 - a_1 = a_3 - a_2 = \\ldots = a_n - a_{n-1})$$$. It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $$$\\max(a_1, a_2, \\dots, a_n)$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$2 \\le n \\le 50$$$; $$$1 \\le x < y \\le 50$$$) \u2014 the length of the array and two elements that are present in the array, respectively.", "output_spec": "For each test case, print the answer: $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter). It can be proven that such an array always exists under the given constraints.", "sample_inputs": ["5\n2 1 49\n5 20 50\n6 20 50\n5 3 8\n9 13 22"], "sample_outputs": ["1 49 \n20 40 30 50 10\n26 32 20 38 44 50 \n8 23 18 13 3 \n1 10 13 4 19 22 25 16 7"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "ca9d97e731e86cf8223520f39ef5d945"} {"nl": {"description": "Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $$$e_i$$$\u00a0\u2014 his inexperience. Russell decided that an explorer with inexperience $$$e$$$ can only join the group of $$$e$$$ or more people.Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.", "input_spec": "The first line contains the number of independent test cases $$$T$$$($$$1 \\leq T \\leq 2 \\cdot 10^5$$$). Next $$$2T$$$ lines contain description of test cases. The first line of description of each test case contains the number of young explorers $$$N$$$ ($$$1 \\leq N \\leq 2 \\cdot 10^5$$$). The second line contains $$$N$$$ integers $$$e_1, e_2, \\ldots, e_N$$$ ($$$1 \\leq e_i \\leq N$$$), where $$$e_i$$$ is the inexperience of the $$$i$$$-th explorer. It's guaranteed that sum of all $$$N$$$ doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "Print $$$T$$$ numbers, each number on a separate line. In $$$i$$$-th line print the maximum number of groups Russell can form in $$$i$$$-th test case.", "sample_inputs": ["2\n3\n1 1 1\n5\n2 3 1 2 2"], "sample_outputs": ["3\n2"], "notes": "NoteIn the first example we can organize three groups. There will be only one explorer in each group. It's correct because inexperience of each explorer equals to $$$1$$$, so it's not less than the size of his group.In the second example we can organize two groups. Explorers with inexperience $$$1$$$, $$$2$$$ and $$$3$$$ will form the first group, and the other two explorers with inexperience equal to $$$2$$$ will form the second group.This solution is not unique. For example, we can form the first group using the three explorers with inexperience equal to $$$2$$$, and the second group using only one explorer with inexperience equal to $$$1$$$. In this case the young explorer with inexperience equal to $$$3$$$ will not be included in any group."}, "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": "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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city.", "input_spec": "First line of input consists of two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 0\u2009\u2264\u2009m\u2009\u2264\u2009200). Next line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009100). Next line contains n integers b1,\u2009b2,\u2009...,\u2009bn (0\u2009\u2264\u2009bi\u2009\u2264\u2009100). Then m lines follow, each of them consists of two integers p and q (1\u2009\u2264\u2009p,\u2009q\u2009\u2264\u2009n, p\u2009\u2260\u2009q) denoting that there is an undirected road between cities p and q. It is guaranteed that there is at most one road between each pair of cities.", "output_spec": "If the conditions can not be met output single word \"NO\". Otherwise output word \"YES\" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i\u2009\u2260\u2009j) or how many soldiers should stay in city i (if i\u2009=\u2009j). If there are several possible answers you may output any of them.", "sample_inputs": ["4 4\n1 2 6 3\n3 5 3 1\n1 2\n2 3\n3 4\n4 2", "2 0\n1 2\n2 1"], "sample_outputs": ["YES\n1 0 0 0 \n2 0 0 0 \n0 5 1 0 \n0 0 2 1", "NO"], "notes": null}, "positive_code": [{"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) {\n var a = in.nextInt()\n var b = in.nextInt()\n var c = in.nextInt()\n if (a>b) {\n c+=a-b\n a=b\n } else {\n c+=b-a\n b=a\n }\n var ans = 0\n if (a<=c){\n ans+=a\n } else {\n ans+=c\n a-=c\n ans+=(a+a)/3\n }\n println(ans)\n }\n }\n\n\n \n \n}"}], "negative_code": [], "src_uid": "b18dac401b655c06bee331e71eb3e4de"} {"nl": {"description": "Recall that a permutation of length $$$n$$$ is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once.For a fixed positive integer $$$d$$$, let's define the cost of the permutation $$$p$$$ of length $$$n$$$ as the number of indices $$$i$$$ $$$(1 \\le i < n)$$$ such that $$$p_i \\cdot d = p_{i + 1}$$$.For example, if $$$d = 3$$$ and $$$p = [5, 2, 6, 7, 1, 3, 4]$$$, then the cost of such a permutation is $$$2$$$, because $$$p_2 \\cdot 3 = p_3$$$ and $$$p_5 \\cdot 3 = p_6$$$.Your task is the following one: for a given value $$$n$$$, find the permutation of length $$$n$$$ and the value $$$d$$$ with maximum possible cost (over all ways to choose the permutation and $$$d$$$). If there are multiple answers, then print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases. The single line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the value $$$d$$$ in the first line, and $$$n$$$ integers in the second line\u00a0\u2014 the permutation itself. If there are multiple answers, then print any of them.", "sample_inputs": ["2\n\n2\n\n3"], "sample_outputs": ["2\n1 2\n3\n2 1 3"], "notes": null}, "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 = ListBuffer.empty[Int]\r\n for {i <- 1 to n\r\n if ((i % 2 != 0) && (i <= n/2))} {\r\n var t = i\r\n while (t <= n){\r\n A+=t\r\n t = t*2\r\n }\r\n }\r\n for {i <- 1 to n\r\n if ((i % 2 != 0) && (i > n/2))} {\r\n A+=i\r\n }\r\n val B = A.toList\r\n val C = A.mkString(\" \")\r\n output.println(2)\r\n output.println(C)\r\n }\r\n }\r\n}"}], "negative_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 = ListBuffer.empty[Int]\r\n for {i <- 1 to n\r\n if ((i % 2 != 0) && (i <= n/2))} {\r\n var t = i\r\n while (t <= n){\r\n A+=t\r\n t = t*2\r\n }\r\n }\r\n for {i <- 1 to n\r\n if ((i % 2 != 0) && (i > n/2))} {\r\n A+=i\r\n }\r\n val B = A.toList\r\n val C = A.mkString(\" \")\r\n output.println(C)\r\n }\r\n }\r\n}"}], "src_uid": "3b9380ca571dbf3e24fc1b1c8b91790b"} {"nl": {"description": "Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself.\u00a0Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\le t \\le 100$$$) \u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\\le n_r,n_g,n_b\\le 10^5$$$) \u00a0\u2014 the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\\ldots,r_{n_r}$$$ ($$$1\\le r_i \\le 10^9$$$) \u00a0\u2014 $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\\ldots,g_{n_g}$$$ ($$$1\\le g_i \\le 10^9$$$) \u00a0\u2014 $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\\ldots,b_{n_b}$$$ ($$$1\\le b_i \\le 10^9$$$) \u00a0\u2014 $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\\sum n_r \\le 10^5$$$, $$$\\sum n_g \\le 10^5$$$, $$$\\sum n_b \\le 10^5$$$ (the sum for all test cases).", "output_spec": "For each test case, print a line contains one integer \u00a0\u2014 the minimum value which Xenia wants to find. ", "sample_inputs": ["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"], "sample_outputs": ["14\n1999999996000000002\n24\n24\n14"], "notes": "NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$."}, "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"}, {"source_code": "//18:45 - 21:55\nimport scala.io.StdIn.readLine\nobject C1336 {\n\n //it can return a.length if nothing is found\n def moveToNext(a:Array[(Int,String)],letter:String,currIndex:Int):Int ={\n assert(currIndex=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"}], "negative_code": [], "src_uid": "79b58eb781cd73ccf7994866b9a8b695"} {"nl": {"description": "Recently, Masha was presented with a chessboard with a height of $$$n$$$ and a width of $$$m$$$.The rows on the chessboard are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. Therefore, each cell can be specified with the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number, and $$$y$$$ is the row number (do not mix up).Let us call a rectangle with coordinates $$$(a,b,c,d)$$$ a rectangle lower left point of which has coordinates $$$(a,b)$$$, and the upper right one\u00a0\u2014 $$$(c,d)$$$.The chessboard is painted black and white as follows: An example of a chessboard. Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat\u00a0\u2014 they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle $$$(x_1,y_1,x_2,y_2)$$$. Then after him Denis spilled black paint on the rectangle $$$(x_3,y_3,x_4,y_4)$$$.To spill paint of color $$$color$$$ onto a certain rectangle means that all the cells that belong to the given rectangle become $$$color$$$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$)\u00a0\u2014 the number of test cases. Each of them is described in the following format: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n,m \\le 10^9$$$)\u00a0\u2014 the size of the board. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \\le x_1 \\le x_2 \\le m, 1 \\le y_1 \\le y_2 \\le n$$$)\u00a0\u2014 the coordinates of the rectangle, the white paint was spilled on. The third line contains four integers $$$x_3$$$, $$$y_3$$$, $$$x_4$$$, $$$y_4$$$ ($$$1 \\le x_3 \\le x_4 \\le m, 1 \\le y_3 \\le y_4 \\le n$$$)\u00a0\u2014 the coordinates of the rectangle, the black paint was spilled on.", "output_spec": "Output $$$t$$$ lines, each of which contains two numbers\u00a0\u2014 the number of white and black cells after spilling paint, respectively.", "sample_inputs": ["5\n2 2\n1 1 2 2\n1 1 2 2\n3 4\n2 2 3 2\n3 1 4 3\n1 5\n1 1 5 1\n3 1 5 1\n4 4\n1 1 4 2\n1 3 4 4\n3 4\n1 2 4 2\n2 1 3 3"], "sample_outputs": ["0 4\n3 9\n2 3\n8 8\n4 8"], "notes": "NoteExplanation for examples:The first picture of each illustration shows how the field looked before the dyes were spilled. The second picture of each illustration shows how the field looked after Maxim spoiled white dye (the rectangle on which the dye was spilled is highlighted with red). The third picture in each illustration shows how the field looked after Denis spoiled black dye (the rectangle on which the dye was spilled is highlighted with red).In the first test, the paint on the field changed as follows: In the second test, the paint on the field changed as follows: In the third test, the paint on the field changed as follows: In the fourth test, the paint on the field changed as follows: In the fifth test, the paint on the field changed as follows: "}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Diamond Miner is a game that is similar to Gold Miner, but there are $$$n$$$ miners instead of $$$1$$$ in this game.The mining area can be described as a plane. The $$$n$$$ miners can be regarded as $$$n$$$ points on the y-axis. There are $$$n$$$ diamond mines in the mining area. We can regard them as $$$n$$$ points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point $$$(0, 0)$$$). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $$$(a,b)$$$ uses his hook to mine a diamond mine at the point $$$(c,d)$$$, he will spend $$$\\sqrt{(a-c)^2+(b-d)^2}$$$ energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 10$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of miners and mines. Each of the next $$$2n$$$ lines contains two space-separated integers $$$x$$$ ($$$-10^8 \\le x \\le 10^8$$$) and $$$y$$$ ($$$-10^8 \\le y \\le 10^8$$$), which represent the point $$$(x,y)$$$ to describe a miner's or a diamond mine's position. Either $$$x = 0$$$, meaning there is a miner at the point $$$(0, y)$$$, or $$$y = 0$$$, meaning there is a diamond mine at the point $$$(x, 0)$$$. There can be multiple miners or diamond mines at the same point. It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to $$$n$$$ and the number of points on the y-axis is equal to $$$n$$$. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single real number \u2014 the minimal sum of energy that should be spent. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-9}$$$.", "sample_inputs": ["3\n2\n0 1\n1 0\n0 -1\n-2 0\n4\n1 0\n3 0\n-5 0\n6 0\n0 3\n0 1\n0 2\n0 4\n5\n3 0\n0 4\n0 -3\n4 0\n2 0\n1 0\n-3 0\n0 -10\n0 -2\n0 -10"], "sample_outputs": ["3.650281539872885\n18.061819283610362\n32.052255376143336"], "notes": "NoteIn the first test case, the miners are at $$$(0,1)$$$ and $$$(0,-1)$$$, while the diamond mines are at $$$(1,0)$$$ and $$$(-2,0)$$$. If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy $$$\\sqrt2 + \\sqrt5$$$."}, "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.math.sqrt\n\nobject diamond_miner extends App {\n\n @tailrec def solve_case(cases_left: Int): Unit = {\n val n: Int = readInt\n var miners: Array[Long] = Array.fill(n){0L}\n var mines: Array[Long] = Array.fill(n){0L}\n var (i, j): (Int, Int) = (0, 0)\n\n @tailrec def get_pos(positions_left: Int): Unit = {\n val p: Array[Long] = readLine.split(' ').map(_.toLong)\n if(p(0) == 0) {\n miners(i) = p(1).abs\n i += 1\n }\n else {\n mines(j) = p(0).abs\n j += 1\n }\n\n if(positions_left > 0)\n get_pos(positions_left - 1)\n }\n\n get_pos(2 * n - 1)\n \n println(miners.sorted.zip(mines.sorted).map(x => sqrt(x._1 * x._1 + x._2 * x._2)).foldLeft(.0)(_ + _))\n \n if(cases_left > 0)\n solve_case(cases_left - 1)\n }\n\n val t: Int = readInt\n solve_case(t - 1)\n}\n"}], "negative_code": [], "src_uid": "ba27ac62b84705d80fa580567ab64c3b"} {"nl": {"description": "There are $$$n$$$ piranhas with sizes $$$a_1, a_2, \\ldots, a_n$$$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely: The piranha $$$i$$$ can eat the piranha $$$i-1$$$ if the piranha $$$i-1$$$ exists and $$$a_{i - 1} < a_i$$$. The piranha $$$i$$$ can eat the piranha $$$i+1$$$ if the piranha $$$i+1$$$ exists and $$$a_{i + 1} < a_i$$$. When the piranha $$$i$$$ eats some piranha, its size increases by one ($$$a_i$$$ becomes $$$a_i + 1$$$).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if $$$a = [5, 3, 4, 4, 5]$$$, then the third piranha can be dominant. Consider the sequence of its moves: The piranha eats the second piranha and $$$a$$$ becomes $$$[5, \\underline{5}, 4, 5]$$$ (the underlined piranha is our candidate). The piranha eats the third piranha and $$$a$$$ becomes $$$[5, \\underline{6}, 5]$$$. The piranha eats the first piranha and $$$a$$$ becomes $$$[\\underline{7}, 5]$$$. The piranha eats the second piranha and $$$a$$$ becomes $$$[\\underline{8}]$$$. You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 the number of piranhas in the aquarium. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the size of the $$$i$$$-th piranha. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3 \\cdot 10^5$$$ ($$$\\sum n \\le 3 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any.", "sample_inputs": ["6\n5\n5 3 4 4 5\n3\n1 1 1\n5\n4 4 3 4 4\n5\n5 5 4 3 2\n3\n1 1 2\n5\n5 4 3 5 5"], "sample_outputs": ["3\n-1\n4\n3\n3\n1"], "notes": "NoteThe first test case of the example is described in the problem statement.In the second test case of the example, there are no dominant piranhas in the aquarium.In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes $$$[4, 4, 5, 4]$$$, then it can eat any other piranha in the aquarium."}, "positive_code": [{"source_code": "//package codeforces.contests._1433\n\nobject DominantPiranha {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n\n val digits = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val max = digits.max\n\n val result = (0 until n).filter(digits(_) == max).find { i =>\n (i - 1 >= 0 && digits(i - 1) != max) || (i + 1 < n && digits(i + 1) != max)\n }.getOrElse(-2) + 1\n\n println {\n result\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "5598d5954fa3e3cecedb413033259760"} {"nl": {"description": "As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A\u2009=\u2009{a1,\u2009a2,\u2009...,\u2009an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i\u2009\u2260\u2009j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106), that sets the size of set A. The second line contains n distinct positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 elements of subset A. The numbers in the line follow in the ascending order.", "output_spec": "Print a single number \u2014 the maximum size of a clique in a divisibility graph for set A.", "sample_inputs": ["8\n3 4 6 8 10 18 21 24"], "sample_outputs": ["3"], "notes": "NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3,\u20096,\u200918}. A clique of a larger size doesn't exist in this graph."}, "positive_code": [{"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 val Array(n) = readInts(1)\n val as = readInts(n)\n val maxA = as.max\n \n val indexOf = Array.fill(maxA + 1){ -1 }\n for (i <- as.indices) indexOf(as(i)) = i\n \n val res = Array.fill(n){ 1 }\n \n for (i <- as.indices) {\n val a = as(i)\n val resI1 = res(i) + 1\n var aa = a + a\n while (aa <= maxA) {\n val j = indexOf(aa)\n if (j >= 0 && resI1 > res(j)) res(j) = resI1 \n aa += a\n }\n }\n\n println(res.max)\n}\n"}], "negative_code": [], "src_uid": "f33991da3b4a57dd6535af86edeeddc0"} {"nl": {"description": "Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle: its vertices have integer coordinates, the coordinates of vertices are non-negative, and its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line $$$y = 0$$$ walking along some straight line, without crossing the interior of the triangle. In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Description of the test cases follows. Each test case contains three lines, each of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \\le x_i, y_i \\le 10^9$$$)\u00a0\u2014 coordinates of the vertices of the downtown's border.", "output_spec": "For each test case print a single number\u00a0\u2014 the answer to the problem. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally let your answer be $$$a$$$, jury answer be $$$b$$$. Your answer will be considered correct if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-9}$$$.", "sample_inputs": ["5\n8 10\n10 4\n6 2\n4 6\n0 1\n4 2\n14 1\n11 2\n13 2\n0 0\n4 0\n2 4\n0 1\n1 1\n0 0"], "sample_outputs": ["0.0000000\n0\n2.0000\n0.00\n1"], "notes": "NoteIn the picture, the downtowns of the first three test cases are illustrated. Triangles are enumerated according to the indices of test cases they belong to. In the first two test cases, all points on the borders of the downtowns are safe, thus the answers are $$$0$$$.In the following picture unsafe points for the third test case are marked with black color: In the fourth test case, all points on the border of the downtown are safe."}, "positive_code": [{"source_code": "object Solution{\r\n def main(args: Array[String])={\r\n val T = scala.io.StdIn.readLine().toInt\r\n var p1 = new Array[List[Int]](T)\r\n var p2 = new Array[List[Int]](T)\r\n var p3 = new Array[List[Int]](T)\r\n var results = new Array[Int](T)\r\n for(k <- 0 until T)\r\n {\r\n p1(k) = ((scala.io.StdIn.readLine().split(\" \")).map(_.toInt)).toList\r\n p2(k) = ((scala.io.StdIn.readLine().split(\" \")).map(_.toInt)).toList\r\n p3(k) = ((scala.io.StdIn.readLine().split(\" \")).map(_.toInt)).toList\r\n }\r\n for (k <- 0 until T)\r\n {\r\n results(k) = 0\r\n if( p1(k)(1) == p2(k)(1) && p1(k)(1) > p3(k)(1))\r\n {\r\n results(k) = (p1(k)(0) - p2(k)(0)).abs\r\n }\r\n if( p1(k)(1) == p3(k)(1) && p1(k)(1) > p2(k)(1))\r\n {\r\n results(k) = (p1(k)(0) - p3(k)(0)).abs\r\n }\r\n if( p3(k)(1) == p2(k)(1) && p3(k)(1) > p1(k)(1))\r\n {\r\n results(k) = (p2(k)(0) - p3(k)(0)).abs\r\n }\r\n }\r\n for( k <- 0 until T)\r\n {\r\n println(results(k))\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "9f019c3898f27d687c5b3498586644e8"} {"nl": {"description": "The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?", "input_spec": "The first line contains string $$$s$$$ ($$$1 \\leqslant |s| \\leqslant 500\\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \\leqslant |t| \\leqslant 500\\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.", "output_spec": "In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.", "sample_inputs": ["101101\n110", "10010110\n100011", "10\n11100"], "sample_outputs": ["110110", "01100011", "01"], "notes": "NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence."}, "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, T = ns()\n val N = S.length\n val M = T.length\n\n var cs1 = S.count(_ == '1')\n var cs0 = N - cs1\n var ct1 = T.count(_ == '1')\n var ct0 = M - ct1\n\n debug(s\"$ct1 $ct0\")\n\n val kmp = new KMP(T)\n val pos = kmp.kmp(M)\n val ct1_2 = T.drop(pos).count(_ == '1')\n val ct0_2 = M - pos - ct1_2\n\n debug(s\"$ct1_2 $ct0_2\")\n\n var first = true\n var t = T\n while(cs1 >= ct1 && cs0 >= ct0) {\n out.print(t)\n cs1 -= ct1\n cs0 -= ct0\n\n if (first) {\n ct1 = ct1_2\n ct0 = ct0_2\n first = false\n t = T.drop(pos)\n }\n }\n REP(cs0) { _ =>\n out.print(0)\n }\n REP(cs1) { _ =>\n out.print(1)\n }\n out.println()\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 // kmp(i-1)\u4ee5\u4e0b\u3057\u304b\u53c2\u7167\u3055\u308c\u306a\u3044\u304b\u3089OK\n kmp(i) = longestSuffix(kmp(i - 1), word(i - 1))\n }\n\n debug(kmp)\n\n def findFirst(text: String): Int = {\n var j = 0\n REP(text.length) { i =>\n j = longestSuffix(j, text(i))\n if (j == word.length) return i - word.length + 1\n }\n -1\n }\n\n def longestSuffix(matched: Int, c: Char): Int = {\n var j = matched\n var continues = true\n while(continues) {\n if (word(j) == c) {\n j += 1\n continues = false\n } else if (j == 0) continues = false\n else j = kmp(j)\n }\n j\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 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 val S, T = ns()\n val N = S.length\n val M = T.length\n val cntS1 = S.count(_ == '1')\n val cntS0 = N - cntS1\n val cntT1 = T.count(_ == '1')\n val cntT0 = M - cntT1\n\n val r1 = if (cntT1 == 0) 1e9.toInt else cntS1 / cntT1\n val r0 = if (cntT0 == 0) 1e9.toInt else cntS0 / cntT0\n val ts = min(N / M, min(r1, r0))\n debug(s\"ts $ts\")\n val one = cntS1 - cntT1 * ts\n REP(N - ts * M - one) { _ =>\n out.print(0)\n }\n REP(one) { _ =>\n out.print(1)\n }\n REP(ts) { _ =>\n out.print(T)\n }\n out.println()\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 def solve(): Unit = {\n val S, T = ns()\n val N = S.length\n val M = T.length\n\n var cs1 = S.count(_ == '1')\n var cs0 = N - cs1\n val ct1 = T.count(_ == '1')\n val ct0 = M - ct1\n\n while(cs1 >= ct1 && cs0 >= ct0) {\n out.print(T)\n cs1 -= ct1\n cs0 -= ct0\n }\n REP(cs0) { _ =>\n out.print(0)\n }\n REP(cs1) { _ =>\n out.print(1)\n }\n out.println()\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"}], "src_uid": "6ac00fcd4a483f9f446e692d05fd31a4"} {"nl": {"description": "Sengoku still remembers the mysterious \"colourful meteoroids\" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.On that night, Sengoku constructed a permutation p1,\u2009p2,\u2009...,\u2009pn of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a1,\u2009a2,\u2009...,\u2009an and b1,\u2009b2,\u2009...,\u2009bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) exists, such that ai\u2009\u2260\u2009bi holds.Well, she almost had it all \u2014 each of the sequences a and b matched exactly n\u2009-\u20091 elements in Sengoku's permutation. In other words, there is exactly one i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) such that ai\u2009\u2260\u2009pi, and exactly one j (1\u2009\u2264\u2009j\u2009\u2264\u2009n) such that bj\u2009\u2260\u2009pj.For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.", "input_spec": "The first line of input contains a positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000) \u2014 the length of Sengoku's permutation, being the length of both meteor outbursts at the same time. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the sequence of colours in the first meteor outburst. The third line contains n space-separated integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the sequence of colours in the second meteor outburst. At least one i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) exists, such that ai\u2009\u2260\u2009bi holds.", "output_spec": "Output n space-separated integers p1,\u2009p2,\u2009...,\u2009pn, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them. Input guarantees that such permutation exists.", "sample_inputs": ["5\n1 2 3 4 3\n1 2 5 4 5", "5\n4 4 2 3 1\n5 4 5 3 1", "4\n1 1 3 4\n1 4 3 4"], "sample_outputs": ["1 2 5 4 3", "5 4 2 3 1", "1 2 3 4"], "notes": "NoteIn the first sample, both 1,\u20092,\u20095,\u20094,\u20093 and 1,\u20092,\u20093,\u20094,\u20095 are acceptable outputs.In the second sample, 5,\u20094,\u20092,\u20093,\u20091 is the only permutation to satisfy the constraints."}, "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 } // \u043f\u0435\u0440\u0435\u043a\u043e\u0434\u0435\u043d\u043e\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 } //\u043f\u0435\u0440\u0435\u043a\u043e\u0434\u0435\u043d\u043e*/\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}//\u043f\u0435\u0440\u0435\u043a\u043e\u0434\u0435\u043d\u043e\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 } // \u043f\u0435\u0440\u0435\u043a\u043e\u0434\u0435\u043d\u043e\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 } // \u043d\u0430 \u043e\u0447\u0435\u0440\u0435\u0434\u0438*/\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"}, {"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"}], "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"} {"nl": {"description": "You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, \"defor\" is a substring of \"codeforces\" and \"fors\" is not. The length of the substring is the number of letters in it.Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\\frac n 2$$$ times. For example, strings \"abc\" and \"iltlml\" are diverse and strings \"aab\" and \"zz\" are not.Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the length of string $$$s$$$. The second line is the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "Print \"NO\" if there is no diverse substring in the string $$$s$$$. Otherwise the first line should contain \"YES\". The second line should contain any diverse substring of string $$$s$$$.", "sample_inputs": ["10\ncodeforces", "5\naaaaa"], "sample_outputs": ["YES\ncode", "NO"], "notes": "NoteThe first example has lots of correct answers. Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to \"No comments\" answer."}, "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 val cum = Array.ofDim[Int](26, N + 1)\n rep(N) { i =>\n val c = S(i)\n rep(cum.length) { j =>\n cum(j)(i + 1) = cum(j)(i) + (if (c == 'a' + j) 1 else 0)\n }\n }\n\n def calc: Option[String] = {\n rep(N) { l =>\n l + 1 to N foreach { r =>\n var ok = true\n rep(26) { j =>\n val len = r - l\n val cnt = cum(j)(r) - cum(j)(l)\n ok &= cnt * 2 <= len\n }\n if (ok) return Some(S.slice(l, r).mkString)\n }\n }\n None\n }\n\n calc match {\n case Some(s) =>\n out.println(\"YES\")\n out.println(s)\n\n case None =>\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}"}], "negative_code": [], "src_uid": "ce4443581d4ee12db6607695cd567070"} {"nl": {"description": "ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '\u2009+\u2009' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are n\u2009+\u20091 levels in the game and ZS the Coder start at the level 1.When ZS the Coder is at level k, he can : Press the '\u2009+\u2009' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x\u2009+\u2009k. Press the '' button. Let the number on the screen be x. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes k\u2009+\u20091. This button can only be pressed when x is a perfect square, i.e. x\u2009=\u2009m2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.ZS the Coder needs your help in beating the game\u00a0\u2014 he wants to reach level n\u2009+\u20091. In other words, he needs to press the '' button n times. Help him determine the number of times he should press the '\u2009+\u2009' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n\u2009+\u20091, but not necessarily a sequence minimizing the number of presses.", "input_spec": "The first and only line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000), denoting that ZS the Coder wants to reach level n\u2009+\u20091.", "output_spec": "Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the '\u2009+\u2009' button before pressing the '' button at level i. Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.", "sample_inputs": ["3", "2", "4"], "sample_outputs": ["14\n16\n46", "999999999999999998\n44500000000", "2\n17\n46\n97"], "notes": "NoteIn the first sample case:On the first level, ZS the Coder pressed the '\u2009+\u2009' button 14 times (and the number on screen is initially 2), so the number became 2\u2009+\u200914\u00b71\u2009=\u200916. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the '\u2009+\u2009' button 16 times, so the number becomes 4\u2009+\u200916\u00b72\u2009=\u200936. Then, ZS pressed the '' button, levelling up and changing the number into .After that, on the third level, ZS pressed the '\u2009+\u2009' button 46 times, so the number becomes 6\u2009+\u200946\u00b73\u2009=\u2009144. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4.Also, note that pressing the '\u2009+\u2009' button 10 times on the third level before levelling up does not work, because the number becomes 6\u2009+\u200910\u00b73\u2009=\u200936, and when the '' button is pressed, the number becomes and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution.In the second sample case:On the first level, ZS the Coder pressed the '\u2009+\u2009' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2\u2009+\u2009999999999999999998\u00b71\u2009=\u20091018. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the '\u2009+\u2009' button 44500000000 times, so the number becomes 109\u2009+\u200944500000000\u00b72\u2009=\u20099\u00b71010. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3."}, "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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "We get more and more news about DDoS-attacks of popular websites.Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds $$$100 \\cdot t$$$, where $$$t$$$ \u2014 the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence $$$r_1, r_2, \\dots, r_n$$$, where $$$r_i$$$ \u2014 the number of requests in the $$$i$$$-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment $$$[1, n]$$$.", "input_spec": "The first line contains $$$n$$$ ($$$1 \\le n \\le 5000$$$) \u2014 number of seconds since server has been booted. The second line contains sequence of integers $$$r_1, r_2, \\dots, r_n$$$ ($$$0 \\le r_i \\le 5000$$$), $$$r_i$$$ \u2014 number of requests in the $$$i$$$-th second.", "output_spec": "Print the only integer number \u2014 the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.", "sample_inputs": ["5\n100 200 1 1 1", "5\n1 2 3 4 5", "2\n101 99"], "sample_outputs": ["3", "0", "1"], "notes": null}, "positive_code": [{"source_code": "import java.io.FileInputStream\nimport scala.io.StdIn\n\nobject ProblemB extends App {\n// System.setIn(new FileInputStream(\"inputs/test01.in\"))\n val n = StdIn.readLine().trim.toInt\n val r = StdIn.readLine().trim.split(\"\\\\s+\").map(_.toInt)\n val ps = {val (b, c) = ((Vector.empty[Long], 0L) /: r) ((pr, cr) => (pr._1 :+ pr._2, pr._2 + cr)); b :+ c}\n var a = 0\n for (i <- 0.to(n); j <- i.to(n)) {\n val s = ps(j) - ps(i)\n val t = j - i\n if (s > 100L * t) a = math.max(a, t)\n }\n println(a)\n}\n"}], "negative_code": [], "src_uid": "ae531bc4b47e5d31fe71b6de1398b95e"} {"nl": {"description": "Luntik came out for a morning stroll and found an array $$$a$$$ of length $$$n$$$. He calculated the sum $$$s$$$ of the elements of the array ($$$s= \\sum_{i=1}^{n} a_i$$$). Luntik calls a subsequence of the array $$$a$$$ nearly full if the sum of the numbers in that subsequence is equal to $$$s-1$$$.Luntik really wants to know the number of nearly full subsequences of the array $$$a$$$. But he needs to come home so he asks you to solve that problem!A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The next $$$2 \\cdot t$$$ lines contain descriptions of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 60$$$) \u2014 the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$) \u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case print the number of nearly full subsequences of the array.", "sample_inputs": ["5\n5\n1 2 3 4 5\n2\n1000 1000\n2\n1 0\n5\n3 0 2 1 1\n5\n2 1 0 3 0"], "sample_outputs": ["1\n0\n2\n4\n4"], "notes": "NoteIn the first test case, $$$s=1+2+3+4+5=15$$$, only $$$(2,3,4,5)$$$ is a nearly full subsequence among all subsequences, the sum in it is equal to $$$2+3+4+5=14=15-1$$$.In the second test case, there are no nearly full subsequences.In the third test case, $$$s=1+0=1$$$, the nearly full subsequences are $$$(0)$$$ and $$$()$$$ (the sum of an empty subsequence is $$$0$$$)."}, "positive_code": [{"source_code": "object B extends App {\r\n\r\n def numberOfNearlyFull(an: IndexedSeq[Int]): Long = an.foldLeft(0L)(_ + _) match {\r\n case 0L => 0L\r\n case 1L => 1L << (an.length - 1)\r\n case _ =>\r\n val ones = an.count(_ == 1)\r\n val zeros = an.count(_ == 0)\r\n\r\n (1L << zeros) * ones\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 out.println(numberOfNearlyFull(an))\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": "d786585fee251ebfd5c3e8d8b0425791"} {"nl": {"description": "There is a square matrix n\u2009\u00d7\u2009n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least \"round\". In other words, it should end in the least possible number of zeros.", "input_spec": "The first line contains an integer number n (2\u2009\u2264\u2009n\u2009\u2264\u20091000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).", "output_spec": "In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.", "sample_inputs": ["3\n1 2 3\n4 5 6\n7 8 9"], "sample_outputs": ["0\nDDRR"], "notes": null}, "positive_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 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": "\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}"}, {"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 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 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": "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": "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 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 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"}], "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"} {"nl": {"description": "There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights. Fence for n\u2009=\u20097 and h\u2009=\u2009[1,\u20092,\u20096,\u20091,\u20091,\u20097,\u20091] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).", "input_spec": "The first line of the input contains integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20091.5\u00b7105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009100), where hi is the height of the i-th plank of the fence.", "output_spec": "Print such integer j that the sum of the heights of planks j, j\u2009+\u20091, ..., j\u2009+\u2009k\u2009-\u20091 is the minimum possible. If there are multiple such j's, print any of them.", "sample_inputs": ["7 3\n1 2 6 1 1 7 1"], "sample_outputs": ["3"], "notes": "NoteIn the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8."}, "positive_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, 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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by $$$2$$$, $$$4$$$ or $$$8$$$, and division is only allowed if the number is divisible by the chosen divisor. Formally, if the register contains a positive integer $$$x$$$, in one operation it can be replaced by one of the following: $$$x \\cdot 2$$$ $$$x \\cdot 4$$$ $$$x \\cdot 8$$$ $$$x / 2$$$, if $$$x$$$ is divisible by $$$2$$$ $$$x / 4$$$, if $$$x$$$ is divisible by $$$4$$$ $$$x / 8$$$, if $$$x$$$ is divisible by $$$8$$$ For example, if $$$x = 6$$$, in one operation it can be replaced by $$$12$$$, $$$24$$$, $$$48$$$ or $$$3$$$. Value $$$6$$$ isn't divisible by $$$4$$$ or $$$8$$$, so there're only four variants of replacement.Now Johnny wonders how many operations he needs to perform if he puts $$$a$$$ in the register and wants to get $$$b$$$ at the end.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains integers $$$a$$$ and $$$b$$$ ($$$1 \\leq a, b \\leq 10^{18}$$$)\u00a0\u2014 the initial and target value of the variable, respectively.", "output_spec": "Output $$$t$$$ lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get $$$b$$$ at the end, then write $$$-1$$$.", "sample_inputs": ["10\n10 5\n11 44\n17 21\n1 1\n96 3\n2 128\n1001 1100611139403776\n1000000000000000000 1000000000000000000\n7 1\n10 8"], "sample_outputs": ["1\n1\n-1\n0\n2\n2\n14\n0\n-1\n-1"], "notes": "NoteIn the first test case, Johnny can reach $$$5$$$ from $$$10$$$ by using the shift to the right by one (i.e. divide by $$$2$$$).In the second test case, Johnny can reach $$$44$$$ from $$$11$$$ by using the shift to the left by two (i.e. multiply by $$$4$$$).In the third test case, it is impossible for Johnny to reach $$$21$$$ from $$$17$$$.In the fourth test case, initial and target values are equal, so Johnny has to do $$$0$$$ operations.In the fifth test case, Johnny can reach $$$3$$$ from $$$96$$$ by using two shifts to the right: one by $$$2$$$, and another by $$$3$$$ (i.e. divide by $$$4$$$ and by $$$8$$$)."}, "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 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"}, {"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"} {"nl": {"description": "Given an array a1,\u2009a2,\u2009...,\u2009an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x\u2009=\u2009y2.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of elements in the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009106\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the elements of the array. It is guaranteed that at least one element of the array is not a perfect square.", "output_spec": "Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.", "sample_inputs": ["2\n4 2", "8\n1 2 4 8 16 32 64 576"], "sample_outputs": ["2", "32"], "notes": "NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2."}, "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}"}, {"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"}], "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"} {"nl": {"description": "In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.", "input_spec": "The first line of the input contains n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 number of bidders. The second line contains n distinct integer numbers p1,\u2009p2,\u2009... pn, separated by single spaces (1\u2009\u2264\u2009pi\u2009\u2264\u200910000), where pi stands for the price offered by the i-th bidder.", "output_spec": "The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.", "sample_inputs": ["2\n5 7", "3\n10 2 8", "6\n3 8 2 9 4 14"], "sample_outputs": ["2 5", "1 8", "6 9"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject SecondPriceAuction_386A {\n // https://codeforces.com/problemset/problem/386/A?locale=ru\n def main(args: Array[String]): Unit = {\n val numOfMembers = StdIn.readInt()\n val prices = StdIn.readLine().split(\" \").map(_.toInt)\n\n var max = prices.head\n var secondPrice = 0\n var maxIdx = 0\n prices.zipWithIndex.foreach { case (x, i) =>\n if (x > max) {\n secondPrice = max\n max = x\n maxIdx = i\n } else if (x > secondPrice && i > 0) {\n secondPrice = x\n }\n }\n println(s\"${maxIdx + 1} ${secondPrice}\")\n }\n \n}\n"}], "negative_code": [], "src_uid": "1d4aaf15e5c6fcde50515880aae74720"} {"nl": {"description": "Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n\u2009-\u20091 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area? Illustration to the first example. ", "input_spec": "The first and only line of input contains two space-separated integers, n and h (2\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009h\u2009\u2264\u2009105).", "output_spec": "The output should contain n\u2009-\u20091 real numbers x1,\u2009x2,\u2009...,\u2009xn\u2009-\u20091. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0\u2009<\u2009x1\u2009<\u2009x2\u2009<\u2009...\u2009<\u2009xn\u2009-\u20091\u2009<\u2009h must hold. Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10\u2009-\u20096. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .", "sample_inputs": ["3 2", "2 100000"], "sample_outputs": ["1.154700538379 1.632993161855", "70710.678118654752"], "notes": "NoteDefinition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject B 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 h = int().toDouble\n\n val ans = for (i <- 1 until n) yield {\n h * Math.sqrt(i.toDouble / n)\n }\n\n println(ans.mkString(\" \"))\n\n}\n"}], "negative_code": [], "src_uid": "6f8a1a138ea2620f2013f426e29e4d98"} {"nl": {"description": "Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark \"?\". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s=\"ab?b\" as a result, it will appear in t=\"aabrbb\" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol \"?\" should be considered equal to any other symbol.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009m\u2009\u2264\u20091000) \u2014 the length of the string s and the length of the string t correspondingly. The second line contains n lowercase English letters \u2014 string s. The third line contains m lowercase English letters \u2014 string t.", "output_spec": "In the first line print single integer k \u2014 the minimal number of symbols that need to be replaced. In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.", "sample_inputs": ["3 5\nabc\nxaybz", "4 10\nabcd\nebceabazcd"], "sample_outputs": ["2\n2 3", "1\n2"], "notes": null}, "positive_code": [{"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": "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"}, {"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 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"}], "negative_code": [{"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\n for(i<-0 to m-n){\n var chlist:List[Int]=List()\n for(j<-0 to n-1){\n if(str1.charAt(j)!=str2.charAt(i+j)){\n chlist = j::chlist\n }\n }\n if(minlist.length==0 || chlist.length= 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}"}, {"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": "object C479 {\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))).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"}, {"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}"}], "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"} {"nl": {"description": "You have $$$n$$$ chains, the $$$i$$$-th chain consists of $$$c_i$$$ vertices. Vertices in each chain are numbered independently from $$$1$$$ to $$$c_i$$$ along the chain. In other words, the $$$i$$$-th chain is the undirected graph with $$$c_i$$$ vertices and $$$(c_i - 1)$$$ edges connecting the $$$j$$$-th and the $$$(j + 1)$$$-th vertices for each $$$1 \\le j < c_i$$$.Now you decided to unite chains in one graph in the following way: the first chain is skipped; the $$$1$$$-st vertex of the $$$i$$$-th chain is connected by an edge with the $$$a_i$$$-th vertex of the $$$(i - 1)$$$-th chain; the last ($$$c_i$$$-th) vertex of the $$$i$$$-th chain is connected by an edge with the $$$b_i$$$-th vertex of the $$$(i - 1)$$$-th chain. Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph.A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the number of chains you have. The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$2 \\le c_i \\le 10^9$$$)\u00a0\u2014 the number of vertices in the corresponding chains. The third line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$a_1 = -1$$$; $$$1 \\le a_i \\le c_{i - 1}$$$). The fourth line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$b_1 = -1$$$; $$$1 \\le b_i \\le c_{i - 1}$$$). Both $$$a_1$$$ and $$$b_1$$$ are equal to $$$-1$$$, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print the length of the longest simple cycle.", "sample_inputs": ["3\n4\n3 4 3 3\n-1 1 2 2\n-1 2 2 3\n2\n5 6\n-1 5\n-1 1\n3\n3 5 2\n-1 1 1\n-1 3 5"], "sample_outputs": ["7\n11\n8"], "notes": "NoteIn the first test case, the longest simple cycle is shown below: We can't increase it with the first chain, since in such case it won't be simple\u00a0\u2014 the vertex $$$2$$$ on the second chain will break simplicity."}, "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 cs, as, bs = nextLongs(n)\n var max = 0L\n var aPrev, bPrev = -1L\n var current = 0L\n for (i <- 1 until n) {\n val a = as(i)\n val b = bs(i)\n val c = cs(i)\n val sum1 = Math.abs(a - b) + 2 + c - 1\n val sum2 = if (a == b) 0 else current - Math.abs(a - b) + 2 + c -1\n current = Math.max(sum1, sum2)\n if (current > max) max = current\n aPrev = a\n bPrev = b\n }\n if (current > max) max = current\n\n out.println(max)\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": "3d898a45ab89b93e006270a77db49017"} {"nl": {"description": "Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of \u200b\u200bm pieces of paper in the garland. Calculate what the maximum total area of \u200b\u200bthe pieces of paper in the garland Vasya can get.", "input_spec": "The first line contains a non-empty sequence of n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) small English letters (\"a\"...\"z\"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1\u2009\u2264\u2009m\u2009\u2264\u20091000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.", "output_spec": "Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.", "sample_inputs": ["aaabbac\naabbccac", "a\nz"], "sample_outputs": ["6", "-1"], "notes": "NoteIn the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.In the second test sample Vasya cannot make a garland at all \u2014 he doesn't have a sheet of color z."}, "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": "\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"}, {"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"} {"nl": {"description": "One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings \"name1 reposted name2\", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string \"name1 reposted name2\" user \"name1\" didn't have the joke in his feed yet, and \"name2\" already had it in his feed by the moment of repost. Polycarp was registered as \"Polycarp\" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200) \u2014 the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as \"name1 reposted name2\". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.", "output_spec": "Print a single integer \u2014 the maximum length of a repost chain.", "sample_inputs": ["5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya", "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp", "1\nSoMeStRaNgEgUe reposted PoLyCaRp"], "sample_outputs": ["6", "2", "2"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "16d4035b138137bbad247ccd5e560051"} {"nl": {"description": "A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.", "input_spec": "The first line contains five integers n, k, a, b, and q (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009b\u2009<\u2009a\u2009\u2264\u200910 000, 1\u2009\u2264\u2009q\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1\u2009\u2264\u2009di\u2009\u2264\u2009n, 1\u2009\u2264\u2009ai\u2009\u2264\u200910 000), representing an update of ai orders on day di, or 2 pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n\u2009-\u2009k\u2009+\u20091), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.", "output_spec": "For each query of the second type, print a line containing a single integer \u2014 the maximum number of orders that the factory can fill over all n days.", "sample_inputs": ["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"], "sample_outputs": ["3\n6\n4", "7\n1"], "notes": "NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders."}, "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[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}"}, {"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"} {"nl": {"description": "Recently Irina arrived to one of the most famous cities of Berland\u00a0\u2014 the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace n. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than T time units.Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T. It is guaranteed that there is at least one route from showplace 1 to showplace n such that Irina will spend no more than T time units passing it.", "input_spec": "The first line of the input contains three integers n,\u2009m and T (2\u2009\u2264\u2009n\u2009\u2264\u20095000,\u2009\u20091\u2009\u2264\u2009m\u2009\u2264\u20095000,\u2009\u20091\u2009\u2264\u2009T\u2009\u2264\u2009109)\u00a0\u2014 the number of showplaces, the number of roads between them and the time of Irina's stay in Berlatov respectively. The next m lines describes roads in Berlatov. i-th of them contains 3 integers ui,\u2009vi,\u2009ti (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi,\u20091\u2009\u2264\u2009ti\u2009\u2264\u2009109), meaning that there is a road starting from showplace ui and leading to showplace vi, and Irina spends ti time units to pass it. It is guaranteed that the roads do not form cyclic routes. It is guaranteed, that there is at most one road between each pair of showplaces.", "output_spec": "Print the single integer k (2\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the maximum number of showplaces that Irina can visit during her journey from showplace 1 to showplace n within time not exceeding T, in the first line. Print k distinct integers in the second line\u00a0\u2014 indices of showplaces that Irina will visit on her route, in the order of encountering them. If there are multiple answers, print any of them.", "sample_inputs": ["4 3 13\n1 2 5\n2 3 7\n2 4 8", "6 6 7\n1 2 2\n1 3 3\n3 6 3\n2 4 2\n4 6 2\n6 5 1", "5 5 6\n1 3 3\n3 5 3\n1 2 2\n2 4 3\n4 5 2"], "sample_outputs": ["3\n1 2 4", "4\n1 2 4 6", "3\n1 3 5"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m, t) = in.next().split(' ').map(_.toInt)\n val map = Array.fill[List[(Int, Int)]](n)(Nil)\n\n in.take(m).map(_.split(' ').map(_.toInt)).foreach {\n case Array(u1, v1, t1) => map(u1 - 1) ::= (v1 - 1, t1)\n }\n\n def topSort(): List[Int] = {\n var path = 0 :: Nil\n var visited = Set.empty[Int]\n var answer = List.empty[Int]\n\n while (path.nonEmpty) {\n if (path.head == n - 1 || map(path.head).forall(i => visited(i._1))) {\n answer ::= path.head\n visited += path.head\n path = path.tail\n } else {\n path ::= map(path.head).find(i => !visited(i._1)).get._1\n }\n }\n answer\n }\n\n def combine(a: (Int, Int, Int), list: List[(Int, Int, Int)]) = {\n if (a._1 < 0) list\n else {\n if (list.exists(l => a._1 <= l._1 && a._3 <= l._3))\n list\n else\n a :: list\n }\n }\n\n var answer = Array.fill[Array[Int]](n)(Array.fill(n){-1})\n var previous = Array.fill[Array[Int]](n)(Array.fill(n){-1})\n answer(0)(0) = t\n\n topSort().foreach {\n index =>\n answer(index).indices.foreach{\n case j =>\n val left = answer(index)(j)\n if (left != -1)\n map(index).foreach{\n case (to, time) =>\n if (left - time > answer(to)(j + 1)) {\n answer(to)(j + 1) = left - time\n previous(to)(j + 1) = index\n }\n }\n }\n }\n\n var index = n - 1\n var count = (n - 1 to 0 by -1).find(i => answer(index)(i) >= 0).get + 1\n var r = List(n)\n println(count)\n\n while (count != 0) {\n count -= 1\n index = previous(index)(count)\n r ::= (index + 1)\n }\n\n println(r.tail.mkString(\" \"))\n\n}"}], "negative_code": [], "src_uid": "31b929252f7d63cb3654ed367224cc31"} {"nl": {"description": "A permutation is a sequence of integers p1,\u2009p2,\u2009...,\u2009pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1,\u2009p2,\u2009...,\u2009pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) (n is the permutation size) the following equations hold ppi\u2009=\u2009i and pi\u2009\u2260\u2009i. Nickolas asks you to print any perfect permutation of size n for the given n.", "input_spec": "A single line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the permutation size.", "output_spec": "If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1,\u2009p2,\u2009...,\u2009pn \u2014 permutation p, that is perfect. Separate printed numbers by whitespaces.", "sample_inputs": ["1", "2", "4"], "sample_outputs": ["-1", "2 1", "2 1 4 3"], "notes": null}, "positive_code": [{"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"}, {"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": "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"}, {"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}"}], "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"} {"nl": {"description": "DZY loves colors, and he enjoys painting.On a colorful day, DZY gets a colorful ribbon, which consists of n units (they are numbered from 1 to n from left to right). The color of the i-th unit of the ribbon is i at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first.DZY loves painting, we know. He takes up a paintbrush with color x and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit i currently is y. When it is painted by this paintbrush, the color of the unit becomes x, and the colorfulness of the unit increases by |x\u2009-\u2009y|.DZY wants to perform m operations, each operation can be one of the following: Paint all the units with numbers between l and r (both inclusive) with color x. Ask the sum of colorfulness of the units between l and r (both inclusive). Can you help DZY?", "input_spec": "The first line contains two space-separated integers n,\u2009m\u00a0(1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). Each of the next m lines begins with a integer type\u00a0(1\u2009\u2264\u2009type\u2009\u2264\u20092), which represents the type of this operation. If type\u2009=\u20091, there will be 3 more integers l,\u2009r,\u2009x\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009x\u2009\u2264\u2009108) in this line, describing an operation 1. If type\u2009=\u20092, there will be 2 more integers l,\u2009r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) in this line, describing an operation 2.", "output_spec": "For each operation 2, print a line containing the answer \u2014 sum of colorfulness.", "sample_inputs": ["3 3\n1 1 2 4\n1 2 3 5\n2 1 3", "3 4\n1 1 3 4\n2 1 1\n2 2 2\n2 3 3", "10 6\n1 1 5 3\n1 2 7 9\n1 10 10 11\n1 3 8 12\n1 1 10 3\n2 1 10"], "sample_outputs": ["8", "3\n2\n1", "129"], "notes": "NoteIn the first sample, the color of each unit is initially [1,\u20092,\u20093], and the colorfulness is [0,\u20090,\u20090].After the first operation, colors become [4,\u20094,\u20093], colorfulness become [3,\u20092,\u20090].After the second operation, colors become [4,\u20095,\u20095], colorfulness become [3,\u20093,\u20092].So the answer to the only operation of type 2 is 8."}, "positive_code": [{"source_code": "import java.util._\nimport java.io._\n\n/**\n * Created by hama_du on 2014/09/01.\n */\nobject ProblemC extends App {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n val n = in.nextInt()\n val m = in.nextInt()\n val seg = new SegmentTree(n)\n seg.init(n)\n\n for (i <- 0 until m) {\n val t = in.nextInt()\n val l = in.nextInt()-1\n val r = in.nextInt()\n if (t == 1) {\n val x = in.nextInt()\n seg.update(l, r, x)\n } else {\n out.println(seg.range(l, r))\n }\n }\n out.flush()\n\n\n // libraries\n\n class SegmentTree(n: Int) {\n val N = Integer.highestOneBit(n-1)<<1\n val values = new Array[Long](N<<1)\n val color = new Array[Int](N<<1)\n val diff = new Array[Long](N<<1)\n\n def init(n: Int) {\n Arrays.fill(color, -1)\n for (i <- (N-1) to (N-1+n)) {\n color(i) = i-N+2\n }\n }\n\n def update(l: Int, r: Int, value: Int) {\n update(l, r, value, -1, 0, 0, N)\n }\n\n def update(l: Int, r: Int, value: Int, currentColor: Int, idx: Int, fr: Int, to: Int): Long = {\n // update the color\n if (currentColor != -1) {\n color(idx) = currentColor\n }\n val toColor = color(idx)\n\n if (to <= l || r <= fr) {\n // nothing to do\n 0L\n } else {\n var result = 0L\n val med = (fr + to) / 2\n if (l <= fr && to <= r) {\n if (color(idx) == -1) {\n // different color => calculate each of them\n result = update(l, r, value, toColor, (idx<<1)+1, fr, med) + update(l, r, value, toColor, (idx<<1)+2, med, to)\n } else {\n // same color => yeah!!\n val diffColor = Math.abs(value - color(idx)) * 1L\n result = diffColor * (to - fr)\n diff(idx) += diffColor\n }\n color(idx) = value\n } else {\n result = update(l, r, value, toColor, (idx<<1)+1, fr, med) + update(l, r, value, toColor, (idx<<1)+2, med, to)\n color(idx) = -1\n }\n values(idx) += result\n return result\n }\n }\n\n def range(l: Int, r: Int): Long = {\n range(l, r, 0, 0, N)\n }\n\n def range(l: Int, r: Int, idx: Int, fr: Int, to: Int): Long = {\n if (to <= l || r <= fr) {\n 0L\n } else if (l <= fr && to <= r) {\n values(idx)\n } else {\n val med = (fr + to) / 2\n range(l, r, (idx<<1)+1, fr, med) + range(l, r, (idx<<1)+2, med, to) + diff(idx) * (Math.min(r, to) - Math.max(l, fr))\n }\n }\n\n }\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"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\n\n/**\n * Created by hama_du on 2014/09/01.\n */\nobject ProblemC extends App {\n val in = new InputReader(System.in)\n val out = new PrintWriter(System.out)\n\n val n = in.nextInt()\n val m = in.nextInt()\n val seg = new SegmentTree(n)\n seg.init(n)\n\n for (i <- 0 until m) {\n val t = in.nextInt()\n val l = in.nextInt()-1\n val r = in.nextInt()\n if (t == 1) {\n val x = in.nextInt()\n seg.update(l, r, x)\n } else {\n out.println(seg.range(l, r))\n }\n }\n out.flush()\n\n\n // libraries\n\n class SegmentTree(n: Int) {\n val N = Integer.highestOneBit(n-1)<<1\n val values = new Array[Long](N<<1)\n val color = new Array[Int](N<<1)\n val diff = new Array[Long](N<<1)\n\n def init(n: Int) {\n Arrays.fill(color, -1)\n for (i <- (N-1) to (N-1+n)) {\n color(i) = i-N+2\n }\n }\n\n def update(l: Int, r: Int, value: Int) {\n update(l, r, value, -1, 0, 0, N)\n }\n\n def update(l: Int, r: Int, value: Int, currentColor: Int, idx: Int, fr: Int, to: Int) {\n // update the color\n if (currentColor != -1) {\n color(idx) = currentColor\n }\n val toColor = color(idx)\n\n if (to <= l || r <= fr) {\n return\n } else {\n val med = (fr + to) / 2\n if (l <= fr && to <= r) {\n if (color(idx) == -1) {\n update(l, r, value, toColor, (idx<<1)+1, fr, med)\n update(l, r, value, toColor, (idx<<1)+2, med, to)\n values(idx) = values((idx << 1) + 1) + values((idx << 1) + 2)\n } else {\n val diffColor = Math.abs(value - color(idx)) * 1L\n diff(idx) += diffColor\n values(idx) += diffColor * (to - fr)\n }\n color(idx) = value\n } else {\n update(l, r, value, toColor, (idx<<1)+1, fr, med)\n update(l, r, value, toColor, (idx<<1)+2, med, to)\n values(idx) = values((idx << 1) + 1) + values((idx << 1) + 2)\n color(idx) = -1\n }\n }\n }\n\n def range(l: Int, r: Int): Long = {\n range(l, r, 0, 0, N)\n }\n\n def range(l: Int, r: Int, idx: Int, fr: Int, to: Int): Long = {\n if (to <= l || r <= fr) {\n 0L\n } else if (l <= fr && to <= r) {\n values(idx)\n } else {\n val med = (fr + to) / 2\n range(l, r, (idx<<1)+1, fr, med) + range(l, r, (idx<<1)+2, med, to) + diff(idx) * (Math.min(r, to) - Math.max(l, fr))\n }\n }\n\n }\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"}], "src_uid": "562656bfc27b7cf06f7c4a373c6bc029"} {"nl": {"description": "Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print \"Infinity\". If there is no scenario matching the given information, print \"Impossible\".", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000). The i-th of next n lines contains two integers ci and di (\u2009-\u2009100\u2009\u2264\u2009ci\u2009\u2264\u2009100, 1\u2009\u2264\u2009di\u2009\u2264\u20092), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.", "output_spec": "If Limak's current rating can be arbitrarily big, print \"Infinity\" (without quotes). If the situation is impossible, print \"Impossible\" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.", "sample_inputs": ["3\n-7 1\n5 2\n8 2", "2\n57 1\n22 2", "1\n-5 1", "4\n27 2\n13 1\n-50 1\n8 2"], "sample_outputs": ["1907", "Impossible", "Infinity", "1897"], "notes": "NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating: Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7. With rating 1894 Limak is in the division 2. His rating increases by 5. Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets \u2009+\u20098 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest."}, "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"}, {"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"}], "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"} {"nl": {"description": "A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $$$7$$$ days!In detail, she can choose any integer $$$k$$$ which satisfies $$$1 \\leq k \\leq r$$$, and set $$$k$$$ days as the number of days in a week.Alice is going to paint some $$$n$$$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has $$$4$$$ days and Alice paints $$$5$$$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes. Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $$$n$$$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains two integers $$$n$$$, $$$r$$$ ($$$1 \\le n \\le 10^9, 1 \\le r \\le 10^9$$$).", "output_spec": "For each test case, print a single integer \u00a0\u2014 the answer to the problem. Please note, that the answer for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.", "sample_inputs": ["5\n3 4\n3 2\n3 1\n13 7\n1010000 9999999"], "sample_outputs": ["4\n3\n1\n28\n510049495001"], "notes": "NoteIn the first test case, Alice can set $$$1,2,3$$$ or $$$4$$$ days as the number of days in a week.There are $$$6$$$ possible paintings shown in the picture, but there are only $$$4$$$ different shapes. So, the answer is $$$4$$$. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides. In the last test case, be careful with the overflow issue, described in the output format."}, "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"}, {"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"}], "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"} {"nl": {"description": "Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).You are given an $$$n \\times m$$$ grid of \"R\", \"W\", and \".\" characters. \"R\" is red, \"W\" is white and \".\" is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 100$$$), the number of test cases. In each test case, the first line will contain $$$n$$$ ($$$1 \\le n \\le 50$$$) and $$$m$$$ ($$$1 \\le m \\le 50$$$), the height and width of the grid respectively. The next $$$n$$$ lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'.", "output_spec": "For each test case, output \"YES\" if there is a valid grid or \"NO\" if there is not. If there is, output the grid on the next $$$n$$$ lines. If there are multiple answers, print any. In the output, the \"YES\"s and \"NO\"s are case-insensitive, meaning that outputs such as \"yEs\" and \"nO\" are valid. However, the grid is case-sensitive.", "sample_inputs": ["3\n4 6\n.R....\n......\n......\n.W....\n4 4\n.R.W\n....\n....\n....\n5 1\nR\nW\nR\nW\nR"], "sample_outputs": ["YES\nWRWRWR\nRWRWRW\nWRWRWR\nRWRWRW\nNO\nYES\nR\nW\nR\nW\nR"], "notes": "NoteThe answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid."}, "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 = (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"}, {"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"} {"nl": {"description": "Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009|s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.", "input_spec": "The first line of the input contains a string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.", "output_spec": "If there is no way of replacing '#' characters which leads to a beautiful string print \u2009-\u20091. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.", "sample_inputs": ["(((#)((#)", "()((#((#(#()", "#", "(#)"], "sample_outputs": ["1\n2", "2\n2\n1", "-1", "-1"], "notes": "Note|s| denotes the length of the string s."}, "positive_code": [{"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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "We start with a string $$$s$$$ consisting only of the digits $$$1$$$, $$$2$$$, or $$$3$$$. The length of $$$s$$$ is denoted by $$$|s|$$$. For each $$$i$$$ from $$$1$$$ to $$$|s|$$$, the $$$i$$$-th character of $$$s$$$ is denoted by $$$s_i$$$. There is one cursor. The cursor's location $$$\\ell$$$ is denoted by an integer in $$$\\{0, \\ldots, |s|\\}$$$, with the following meaning: If $$$\\ell = 0$$$, then the cursor is located before the first character of $$$s$$$. If $$$\\ell = |s|$$$, then the cursor is located right after the last character of $$$s$$$. If $$$0 < \\ell < |s|$$$, then the cursor is located between $$$s_\\ell$$$ and $$$s_{\\ell+1}$$$. We denote by $$$s_\\text{left}$$$ the string to the left of the cursor and $$$s_\\text{right}$$$ the string to the right of the cursor. We also have a string $$$c$$$, which we call our clipboard, which starts out as empty. There are three types of actions: The Move action. Move the cursor one step to the right. This increments $$$\\ell$$$ once. The Cut action. Set $$$c \\leftarrow s_\\text{right}$$$, then set $$$s \\leftarrow s_\\text{left}$$$. The Paste action. Append the value of $$$c$$$ to the end of the string $$$s$$$. Note that this doesn't modify $$$c$$$. The cursor initially starts at $$$\\ell = 0$$$. Then, we perform the following procedure: Perform the Move action once. Perform the Cut action once. Perform the Paste action $$$s_\\ell$$$ times. If $$$\\ell = x$$$, stop. Otherwise, return to step 1. You're given the initial string $$$s$$$ and the integer $$$x$$$. What is the length of $$$s$$$ when the procedure stops? Since this value may be very large, only find it modulo $$$10^9 + 7$$$. It is guaranteed that $$$\\ell \\le |s|$$$ at any time.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer $$$x$$$ ($$$1 \\le x \\le 10^6$$$). The second line of each test case consists of the initial string $$$s$$$ ($$$1 \\le |s| \\le 500$$$). It is guaranteed, that $$$s$$$ consists of the characters \"1\", \"2\", \"3\". It is guaranteed that the sum of $$$x$$$ in a single file is at most $$$10^6$$$. It is guaranteed that in each test case before the procedure will stop it will be true that $$$\\ell \\le |s|$$$ at any time.", "output_spec": "For each test case, output a single line containing a single integer denoting the answer for that test case modulo $$$10^9 + 7$$$. ", "sample_inputs": ["4\n5\n231\n7\n2323\n6\n333\n24\n133321333"], "sample_outputs": ["25\n1438\n1101\n686531475"], "notes": "NoteLet's illustrate what happens with the first test case. Initially, we have $$$s = $$$ 231. Initially, $$$\\ell = 0$$$ and $$$c = \\varepsilon$$$ (the empty string). The following things happen if we follow the procedure above: Step 1, Move once: we get $$$\\ell = 1$$$. Step 2, Cut once: we get $$$s = $$$ 2 and $$$c = $$$ 31. Step 3, Paste $$$s_\\ell = $$$ 2 times: we get $$$s = $$$ 23131. Step 4: $$$\\ell = 1 \\not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\\ell = 2$$$. Step 2, Cut once: we get $$$s = $$$ 23 and $$$c = $$$ 131. Step 3, Paste $$$s_\\ell = $$$ 3 times: we get $$$s = $$$ 23131131131. Step 4: $$$\\ell = 2 \\not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\\ell = 3$$$. Step 2, Cut once: we get $$$s = $$$ 231 and $$$c = $$$ 31131131. Step 3, Paste $$$s_\\ell = $$$ 1 time: we get $$$s = $$$ 23131131131. Step 4: $$$\\ell = 3 \\not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\\ell = 4$$$. Step 2, Cut once: we get $$$s = $$$ 2313 and $$$c = $$$ 1131131. Step 3, Paste $$$s_\\ell = $$$ 3 times: we get $$$s = $$$ 2313113113111311311131131. Step 4: $$$\\ell = 4 \\not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\\ell = 5$$$. Step 2, Cut once: we get $$$s = $$$ 23131 and $$$c = $$$ 13113111311311131131. Step 3, Paste $$$s_\\ell = $$$ 1 times: we get $$$s = $$$ 2313113113111311311131131. Step 4: $$$\\ell = 5 = x$$$, so we stop. At the end of the procedure, $$$s$$$ has length $$$25$$$. "}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val x = ni()\n val s = ns()\n var slen: Long = s.length\n val prefix = ArrayBuffer[Int]()\n s.foreach { c =>\n prefix += c-'0'\n }\n\n// val aa = ArrayBuffer[Int]()\n var i = 0\n while(i < x) {\n val times = prefix(i) - 1\n// aa += times + 1\n val t = prefix.length\n if (prefix.length < x) {\n REP(times) { _ =>\n REP(t - i - 1, i + 1) { j =>\n prefix += prefix(j)\n }\n }\n }\n slen += (MOD + slen-i-1) % MOD * times % MOD\n slen %= MOD\n i += 1\n\n// debug(s\"slen:$slen\")\n// debug(prefix.mkString)\n }\n// debug(s\"times: ${aa.mkString}\")\n out.println(slen)\n }\n }\n}"}], "negative_code": [], "src_uid": "592e219abe72054c3de1b6823a1d049d"} {"nl": {"description": "Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\\left\\lfloor\\frac{x}{a}\\right\\rfloor + x \\bmod a$$$, where $$$\\left\\lfloor\\frac{x}{a}\\right\\rfloor$$$ is $$$\\frac{x}{a}$$$, rounded down, $$$x \\bmod a$$$ \u2014 the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \\left\\lfloor\\frac{11}{3}\\right\\rfloor + 11 \\bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \\le x \\le r$$$).", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^9, 1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the left and right boundaries of the segment and the fixed value of $$$a$$$.", "output_spec": "For each test case, output one number on a separate line\u00a0\u2014 the maximum value of the function on a given segment for a given $$$a$$$.", "sample_inputs": ["5\n\n1 4 3\n\n5 8 4\n\n6 10 6\n\n1 1000000000 1000000000\n\n10 12 8"], "sample_outputs": ["2\n4\n5\n999999999\n5"], "notes": "NoteIn the first sample: $$$f_3(1) = \\left\\lfloor\\frac{1}{3}\\right\\rfloor + 1 \\bmod 3 = 0 + 1 = 1$$$, $$$f_3(2) = \\left\\lfloor\\frac{2}{3}\\right\\rfloor + 2 \\bmod 3 = 0 + 2 = 2$$$, $$$f_3(3) = \\left\\lfloor\\frac{3}{3}\\right\\rfloor + 3 \\bmod 3 = 1 + 0 = 1$$$, $$$f_3(4) = \\left\\lfloor\\frac{4}{3}\\right\\rfloor + 4 \\bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n def f(nums: Array[Long]) = {\n val l: Long = nums(0)\n val r: Long = nums(1)\n val a: Long = nums(2)\n\n val q = r / a\n if (l < q * a) Math.max(q - 1 + a - 1, r / a + r % a)\n else r / a + r % a\n\n\n }\n\n val cases = readLine().toInt\n for (\n i <- 0 until cases;\n s = readLine().split(\"\\\\s+\").map(_.toLong)\n ) println(f(s))\n\n }\n}\n\n"}], "negative_code": [], "src_uid": "681ee82880ddd0de907aac2ccad8fc04"} {"nl": {"description": "This is the easy version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.", "input_spec": "The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 10^5)$$$\u00a0\u2014 the number of ice spheres in the shop. The second line contains $$$n$$$ different integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$\u00a0\u2014 the prices of ice spheres.", "output_spec": "In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.", "sample_inputs": ["5\n1 2 3 4 5"], "sample_outputs": ["2\n3 1 4 2 5"], "notes": "NoteIn the example it's not possible to place ice spheres in any order so that Sage would buy $$$3$$$ of them. If the ice spheres are placed like this $$$(3, 1, 4, 2, 5)$$$, then Sage will buy two spheres: one for $$$1$$$ and one for $$$2$$$, because they are cheap."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example: Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example: $$$7 \\mod 3=1$$$, because $$$7 = 3 \\cdot 2 + 1$$$, $$$15 \\mod 4=3$$$, because $$$15 = 4 \\cdot 3 + 3$$$. ", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t (t \\geq 1)$$$ \u2014 the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \\leq n \\leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$", "output_spec": "For each test case, print the answer in a single line.", "sample_inputs": ["4\n1\n2\n9\n91234"], "sample_outputs": ["1\n12\n830455698\n890287984"], "notes": "Note$$$n=1$$$, there is only one permutation that satisfies the condition: $$$[1,2].$$$In permutation $$$[1,2]$$$, $$$p_1<p_2$$$, and there is one $$$i=1$$$ satisfy the condition. Since $$$1 \\geq n$$$, this permutation should be counted. In permutation $$$[2,1]$$$, $$$p_1>p_2$$$. Because $$$0<n$$$, this permutation should not be counted.$$$n=2$$$, there are $$$12$$$ permutations: $$$[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3].$$$"}, "positive_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 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"}, {"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"} {"nl": {"description": "Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2\u00b7ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.", "input_spec": "The first line contains two integers n and f (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009f\u2009\u2264\u2009n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out. Each line of the following n subsequent lines contains two integers ki,\u2009li (0\u2009\u2264\u2009ki,\u2009li\u2009\u2264\u2009109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.", "output_spec": "Print a single integer denoting the maximal number of products that shop can sell.", "sample_inputs": ["4 2\n2 1\n3 5\n2 3\n1 5", "4 1\n0 2\n0 3\n3 5\n0 6"], "sample_outputs": ["10", "5"], "notes": "NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2,\u20096,\u20092,\u20092] respectively. So on the first day shop will sell 1 product, on the second\u00a0\u2014 5, on the third\u00a0\u2014 2, on the fourth\u00a0\u2014 2. In total 1\u2009+\u20095\u2009+\u20092\u2009+\u20092\u2009=\u200910 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out."}, "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, 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"}, {"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 _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"}, {"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"}], "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"} {"nl": {"description": "Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of p\u00b7ai\u2009+\u2009q\u00b7aj\u2009+\u2009r\u00b7ak for given p,\u2009q,\u2009r and array a1,\u2009a2,\u2009... an such that 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009k\u2009\u2264\u2009n. Help Snape find the value of x. Do note that the value of x may be negative.", "input_spec": "First line of input contains 4 integers n,\u2009p,\u2009q,\u2009r (\u2009-\u2009109\u2009\u2264\u2009p,\u2009q,\u2009r\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009n\u2009\u2264\u2009105). Next line of input contains n space separated integers a1,\u2009a2,\u2009... an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Output a single integer the maximum value of p\u00b7ai\u2009+\u2009q\u00b7aj\u2009+\u2009r\u00b7ak that can be obtained provided 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009k\u2009\u2264\u2009n.", "sample_inputs": ["5 1 2 3\n1 2 3 4 5", "5 1 2 -3\n-1 -2 -3 -4 -5"], "sample_outputs": ["30", "12"], "notes": "NoteIn the first sample case, we can take i\u2009=\u2009j\u2009=\u2009k\u2009=\u20095, thus making the answer as 1\u00b75\u2009+\u20092\u00b75\u2009+\u20093\u00b75\u2009=\u200930.In second sample case, selecting i\u2009=\u2009j\u2009=\u20091 and k\u2009=\u20095 gives the answer 12."}, "positive_code": [{"source_code": "//http://codeforces.com/contest/855/problem/B\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\n val Array(_n, p, q, r) = readLongs(4)\n val n = _n.toInt\n val as = readInts(n)\n\n var dp, dq, dr = Long.MinValue\n\n for (a <- as) {\n dp = dp max (p * a)\n dq = dq max (dp + q * a)\n dr = dr max (dq + r * a)\n }\n\n println(dr)\n}\n"}], "negative_code": [], "src_uid": "a8e56ad4de6f0eecbe5521226c0335ab"} {"nl": {"description": "In an ICPC contest, balloons are distributed as follows: Whenever a team solves a problem, that team gets a balloon. The first team to solve a problem gets an additional balloon. A contest has 26 problems, labelled $$$\\textsf{A}$$$, $$$\\textsf{B}$$$, $$$\\textsf{C}$$$, ..., $$$\\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$)\u00a0\u2014 the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the total number of balloons that the teams received.", "sample_inputs": ["6\n\n3\n\nABA\n\n1\n\nA\n\n3\n\nORZ\n\n5\n\nBAAAA\n\n4\n\nBKPT\n\n10\n\nCODEFORCES"], "sample_outputs": ["5\n2\n6\n7\n8\n17"], "notes": "NoteIn the first test case, $$$5$$$ balloons are given out: Problem $$$\\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\\textsf{A}$$$. Problem $$$\\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\\textsf{B}$$$. Problem $$$\\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\\textsf{A}$$$. The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\\textsf{A}$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn._\r\nobject Main extends App{\r\n var x=readInt()\r\n Range(0,x).foreach{_=>\r\n val y=readInt()\r\n val z=readLine()\r\n println(z.length+z.distinct.length)\r\n }\r\n}"}], "negative_code": [], "src_uid": "66777b8719b1756bf4b6bf93feb2e439"} {"nl": {"description": "Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Polo the Penguin have two positive integers l and r (l\u2009<\u2009r), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.Let's assume that n is the number of distinct lucky numbers, each of them cannot be greater than r or less than l, and ai is the i-th (in increasing order) number of them. Find a1\u00b7a2\u2009+\u2009a2\u00b7a3\u2009+\u2009...\u2009+\u2009an\u2009-\u20091\u00b7an. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109\u2009+\u20097).", "input_spec": "The first line contains a positive integer l, and the second line contains a positive integer r (1\u2009\u2264\u2009l\u2009<\u2009r\u2009\u2264\u200910100000). The numbers are given without any leading zeroes. It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers.", "output_spec": "In the single line print a single integer \u2014 the answer to the problem modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["4\n7", "474\n777"], "sample_outputs": ["28", "2316330"], "notes": null}, "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\n\nobject CF288E {\n\n val MOD = 1000000007L\n\n case class D(u: Long, v: Long, w: Long, first: Long, last: Long) {\n def combine(o: D) = {\n D(\n (u + o.u + 1) % MOD,\n (v + o.v + last + o.first) % MOD,\n (w + o.w + last * o.first) % MOD,\n first,\n o.last\n )\n }\n\n def shift(add: Long) = {\n D(u, (v + 2 * (u * add % MOD)) % MOD, (w + (u * (add * add % MOD) % MOD) + v * add) % MOD, (first + add) % MOD, (last + add) % MOD)\n }\n }\n\n def solve(in: In, out: PrintWriter) {\n val s1, s2 = in()\n if (s1 == s2) {\n out.println(0)\n return\n }\n val n = s1.size\n val d = Array.ofDim[D](n)\n d(0) = D(0, 0, 0, 0, 0)\n val pow10 = Array.ofDim[Long](n + 1)\n pow10(0) = 1\n for (i <- 1 to n) {\n pow10(i) = (pow10(i - 1) * 10) % MOD\n }\n for (i <- 1 until n) {\n d(i) = d(i - 1).shift((4 * pow10(i - 1)) % MOD).combine(d(i - 1).shift((7 * pow10(i - 1)) % MOD))\n }\n def ss(s: String) = {\n val r = Array.ofDim[Long](n + 1)\n for (i <- 0 until n) {\n r(i + 1) = (r(i) * 10 + s(i) - '0') % MOD\n }\n for (i <- 0 to n) {\n r(i) = (r(i) * pow10(n - i)) % MOD\n }\n r\n }\n val s1s = ss(s1)\n val s2s = ss(s2)\n var ans: D = D(0, 0, 0, s1s(n), s1s(n))\n var fd = 0\n while (s1(fd) == s2(fd)) {\n fd += 1\n }\n// out.println(d.deep, s1s.deep, s2s.deep, ans)\n assert(s1(fd) == '4' && s2(fd) == '7')\n for (i <- (n - 1).until(fd, -1)) {\n if (s1(i) == '4') {\n val shift: D = d(n - i - 1).shift((s1s(i) + 7 * pow10(n - i - 1)) % MOD)\n ans = ans.combine(shift)\n// out.println(shift, ans)\n }\n }\n val it4 = Array.ofDim[Long](n + 1)\n it4(0) = 0\n for (i <- 1 to n) {\n it4(i) = (it4(i - 1) * 10 + 4) % MOD\n }\n for (i <- (fd + 1) until n) {\n if (s2(i) == '7') {\n val shift: D = d(n - i - 1).shift((s2s(i) + 4 * pow10(n - i - 1)) % MOD)\n ans = ans.combine(shift)\n// out.println(shift, ans)\n }\n }\n val shift: D = D(0, 0, 0, s2s(n), s2s(n))\n ans = ans.combine(shift)\n// out.println(shift, ans)\n out.println(ans.w)\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": "import io.Source\nimport java.io.PrintWriter\n\nobject CF288E {\n\n val MOD = 1000000007L\n\n case class D(u: Long, v: Long, w: Long, count: Long, first: Long, last: Long) {\n def combine(o: D) = {\n D(\n (u + o.u + 1) % MOD,\n (v + o.v + last + o.first) % MOD,\n (w + o.w + last * o.first) % MOD,\n (count + o.count) % MOD,\n first,\n o.last\n )\n }\n\n def shift(add: Long) = {\n D(u, (v + 2 * u * add) % MOD, (w + u * (add * add % MOD) + v * add) % MOD, count, (first + add) % MOD, (last + add) % MOD)\n }\n }\n\n def solve(in: In, out: PrintWriter) {\n val s1, s2 = in()\n if (s1 == s2) {\n out.println(0)\n return\n }\n val n = s1.size\n val d = Array.ofDim[D](n)\n d(0) = D(0, 0, 0, 1, 0, 0)\n val pow10 = Array.ofDim[Long](n + 1)\n pow10(0) = 1\n for (i <- 1 to n) {\n pow10(i) = (pow10(i - 1) * 10) % MOD\n }\n for (i <- 1 until n) {\n d(i) = d(i - 1).shift(4 * pow10(i - 1)).combine(d(i - 1).shift(7 * pow10(i - 1)))\n }\n def ss(s: String) = {\n val r = Array.ofDim[Long](n + 1)\n for (i <- 0 until n) {\n r(i + 1) = (r(i) * 10 + s(i) - '0') % MOD\n }\n for (i <- 0 to n) {\n r(i) = (r(i) * pow10(n - i)) % MOD\n }\n r\n }\n val s1s = ss(s1)\n val s2s = ss(s2)\n var ans: D = D(0, 0, 0, 1, s1s(n), s1s(n))\n var fd = 0\n while (s1(fd) == s2(fd)) {\n fd += 1\n }\n// out.println(d.deep, s1s.deep, s2s.deep, ans)\n assert(s1(fd) == '4' && s2(fd) == '7')\n for (i <- (n - 1).until(fd, -1)) {\n if (s1(i) == '4') {\n val shift: D = d(n - i - 1).shift((s1s(i) + 7 * pow10(n - i - 1)) % MOD)\n ans = ans.combine(shift)\n// out.println(shift, ans)\n }\n }\n val it4 = Array.ofDim[Long](n + 1)\n it4(0) = 0\n for (i <- 1 to n) {\n it4(i) = (it4(i - 1) * 10 + 4) % MOD\n }\n for (i <- (fd + 1) until n) {\n if (s2(i) == '7') {\n val shift: D = d(n - i - 1).shift((s2s(i) + 4 * pow10(n - i - 1)) % MOD)\n ans = ans.combine(shift)\n// out.println(shift, ans)\n }\n }\n val shift: D = D(0, 0, 0, 1, s2s(n), s2s(n))\n ans = ans.combine(shift)\n// out.println(shift, ans)\n out.println(ans.w)\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": "cc221a44b6915a941bdc7b4b634fa86d"} {"nl": {"description": "A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game: the game may result in a tie, then both teams get $$$1$$$ point; one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow. Each test case is described by one line containing one integer $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 the number of teams.", "output_spec": "For each test case, print $$$\\frac{n(n - 1)}{2}$$$ integers describing the results of the games in the following order: the first integer should correspond to the match between team $$$1$$$ and team $$$2$$$, the second \u2014 between team $$$1$$$ and team $$$3$$$, then $$$1$$$ and $$$4$$$, ..., $$$1$$$ and $$$n$$$, $$$2$$$ and $$$3$$$, $$$2$$$ and $$$4$$$, ..., $$$2$$$ and $$$n$$$, and so on, until the game between the team $$$n - 1$$$ and the team $$$n$$$. The integer corresponding to the game between the team $$$x$$$ and the team $$$y$$$ should be $$$1$$$ if $$$x$$$ wins, $$$-1$$$ if $$$y$$$ wins, or $$$0$$$ if the game results in a tie. All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.", "sample_inputs": ["2\n2\n3"], "sample_outputs": ["0 \n1 -1 1"], "notes": "NoteIn the first test case of the example, both teams get $$$1$$$ point since the game between them is a tie.In the second test case of the example, team $$$1$$$ defeats team $$$2$$$ (team $$$1$$$ gets $$$3$$$ points), team $$$1$$$ loses to team $$$3$$$ (team $$$3$$$ gets $$$3$$$ points), and team $$$2$$$ wins against team $$$3$$$ (team $$$2$$$ gets $$$3$$$ points)."}, "positive_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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.How many actions should Fangy perform to get a number one from number x?", "input_spec": "The first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.", "output_spec": "Print the required number of actions.", "sample_inputs": ["1", "1001001", "101110"], "sample_outputs": ["0", "12", "8"], "notes": "NoteLet's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1."}, "positive_code": [{"source_code": "import scala.collection.mutable\nobject BinaryNumber extends App {\n val input = io.Source.stdin.getLines.next\n\n var numOps = 0\n var tail = 0\n var specialOnes = -1\n input foreach { char =>\n if(char == '0') {\n if(specialOnes == 0) specialOnes = 1 // we are in the first thing of zeros after single 1\n numOps += 2\n tail += 1\n } else {\n if(specialOnes == -1) specialOnes = 0 // we have processed a single 1, that's all\n else if(specialOnes == 0) specialOnes = -2 // fail: more than one 1 at beginning\n else if(specialOnes == 1) specialOnes = -2 // fail: more ones after zeros\n numOps += 1\n tail = 0\n }\n }\n numOps -= (tail - 1)\n if(specialOnes != -2) numOps -= 2\n println(numOps)\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\nobject BinaryNumber extends App {\n val input = io.Source.stdin.getLines.next\n var numOps = -1\n var tail = -1\n input foreach { char =>\n numOps += 2\n if(char == '0') tail = math.max(tail + 1, 1)\n else {\n if(tail == 0) numOps -= 1\n tail = 0\n }\n }\n numOps -= math.max(1, tail)\n println(numOps)\n}"}, {"source_code": "import scala.collection.mutable\nobject BinaryNumber extends App {\n val input = io.Source.stdin.getLines.next\n\n var numOps = 0\n var tail = 0\n var moreOnes = -1\n input foreach { char =>\n if(char == '0') {\n if(moreOnes == -1) moreOnes = 0\n numOps += 2\n tail += 1\n } else {\n if(moreOnes == 0) moreOnes = 1\n numOps += 1\n tail = 0\n }\n }\n numOps -= (tail - 1)\n if(moreOnes != 1) numOps -= 2\n println(numOps)\n}"}, {"source_code": "import scala.collection.mutable\nobject BinaryNumber extends App {\n val input = io.Source.stdin.getLines.next\n\n var numOps = -1\n var tail = -1\n var hasZero = false\n input foreach { char =>\n numOps += 2\n if(char == '0') {\n tail = math.max(tail + 1, 1)\n hasZero = true\n } else {\n if(tail == 0) numOps -= 1\n tail = 0\n }\n }\n numOps -= math.max(1, tail)\n if(!hasZero) numOps += 2\n println(numOps)\n}"}, {"source_code": "import scala.collection.mutable\nobject BinaryNumber extends App {\n val input = io.Source.stdin.getLines.next\n\n if(input == \"1\") println(\"0\")\n else {\n var numOps = 0\n var tail = 0\n input foreach { char =>\n if(char == '0') {\n numOps += 2\n tail += 1\n } else {\n numOps += 1\n tail = 0\n }\n }\n numOps -= (tail - 1)\n println(numOps)\n }\n}"}], "src_uid": "e46c6406d19e8679fd282d72882ae78d"} {"nl": {"description": "And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0,\u20090), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following: during one run the minibus makes n stops, the i-th stop is in point (xi,\u20090) coordinates of all the stops are different the minibus drives at a constant speed, equal to vb it can be assumed the passengers get on and off the minibus at a bus stop momentarily Student can get off the minibus only at a bus stop Student will have to get off the minibus at a terminal stop, if he does not get off earlier the University, where the exam will be held, is in point (xu,\u2009yu) Student can run from a bus stop to the University at a constant speed vs as long as needed a distance between two points can be calculated according to the following formula: Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.", "input_spec": "The first line contains three integer numbers: 2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009vb,\u2009vs\u2009\u2264\u20091000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn\u2009\u2264\u2009105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value. ", "output_spec": "In the only line output the answer to the problem \u2014 index of the optimum bus stop.", "sample_inputs": ["4 5 2\n0 2 4 6\n4 1", "2 1 1\n0 100000\n100000 100000"], "sample_outputs": ["3", "2"], "notes": "NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus."}, "positive_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 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 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": "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"}, {"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": "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"}], "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"} {"nl": {"description": "It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?", "input_spec": "The first line of input will contain integers N and S (1\u2009\u2264\u2009N\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009S\u2009\u2264\u2009105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1\u2009\u2264\u2009si\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009ai\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009bi\u2009\u2264\u2009105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.", "output_spec": "Print the maximum total happiness that can be achieved.", "sample_inputs": ["3 12\n3 5 7\n4 6 7\n5 9 5", "6 10\n7 4 7\n5 8 8\n12 5 8\n6 11 6\n3 3 7\n5 9 6"], "sample_outputs": ["84", "314"], "notes": "NoteIn the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3\u00b75\u2009+\u20094\u00b76\u2009+\u20095\u00b79\u2009=\u200984, and if you buy a type 2 pizza, the total happiness will be 3\u00b77\u2009+\u20094\u00b77\u2009+\u20095\u00b75\u2009=\u200974."}, "positive_code": [{"source_code": "//package codeforce.c0867\n\nimport scala.io.StdIn\n\nobject C {\n def main(args: Array[String]): Unit = {\n val Array(eaters, slices) = StdIn.readLine().split(' ').map(_.toInt)\n val eater = Array.ofDim[Eater](eaters)\n for {\n e <- 0 until eaters\n } {\n eater(e) = Eater(StdIn.readLine().split(' ').map(_.toInt))\n }\n println(new Greedy(slices, eater).maxValue())\n }\n\n case class Eater(slices: Int, value1: Int, value2: Int) extends Ordered[Eater] {\n override def compare(that: Eater): Int = that.diff() compare diff()\n def diff(): Int = Math.abs(value1 - value2)\n }\n\n object Eater {\n def apply(input: Array[Int]): Eater = Eater(input(0), input(1), input(2))\n }\n\n class Greedy(slices: Int, eaters: Array[Eater]) {\n def maxValue(): Long = {\n var maxValue: Long = 0L\n var slices1: Long = 0L\n var slices2: Long = 0L\n val pq1 = collection.mutable.PriorityQueue[Eater]()\n val pq2 = collection.mutable.PriorityQueue[Eater]()\n\n eaters.foreach(e => if (e.value1 > e.value2) {\n maxValue += 1L * e.slices * e.value1\n slices1 += e.slices\n pq1.enqueue(e)\n } else {\n maxValue += 1L * e.slices * e.value2\n slices2 += e.slices\n pq2.enqueue(e)\n })\n\n val incomplete1 = slices1 % slices\n val incomplete2 = slices2 % slices\n\n if (incomplete1 + incomplete2 <= slices) {\n val diff1 = diff(pq1, incomplete1)\n val diff2 = diff(pq2, incomplete2)\n maxValue -= Math.min(diff1, diff2)\n }\n maxValue\n }\n\n def diff(pq: collection.mutable.PriorityQueue[Eater], n: Long): Long = {\n var diff: Long = 0\n var i = n\n while (i > 0) {\n val e = pq.dequeue()\n diff += Math.min(e.slices, i) * e.diff()\n i -= e.slices\n }\n diff\n }\n }\n}"}], "negative_code": [], "src_uid": "769859d86a3ceb2d89a444cd64c9a73b"} {"nl": {"description": "Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring \"abbcb\", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c\" three times, so that the resulting string is \"abbbbcccbb\", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\\leq n\\leq 100\\,000$$$, $$$1\\leq q \\leq 100\\,000$$$)\u00a0\u2014 the length of the song and the number of questions. The second line contains one string $$$s$$$\u00a0\u2014 the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\leq l \\leq r \\leq n$$$)\u00a0\u2014 the bounds of the question.", "output_spec": "Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.", "sample_inputs": ["7 3\nabacaba\n1 3\n2 5\n1 7", "7 4\nabbabaa\n1 3\n5 7\n6 6\n2 4", "13 7\nsonoshikumiwo\n1 5\n2 10\n7 7\n1 13\n4 8\n2 5\n3 9"], "sample_outputs": ["4\n7\n11", "5\n4\n1\n5", "82\n125\n9\n191\n62\n63\n97"], "notes": "NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring \"aba\", that transforms to \"abba\", so the answer is equal to $$$4$$$. In the second question Vasya considers \"baca\", that transforms to \"bbaccca\", so the answer is $$$7$$$. In the third question Vasya considers the string \"abacaba\",that transforms to \"abbacccabba\" of length $$$11$$$."}, "positive_code": [{"source_code": "object B extends App {\r\n import scala.io.StdIn._\r\n\r\n val Array(n, q) = readLine().split(\" \").map(_.toInt)\r\n val s = readLine()\r\n val ps = s.scanLeft(0L) { case (p, c) => p + c - 'a' + 1 }\r\n (0 until q).foreach { _ =>\r\n val Array(l, r) = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = ps(r) - ps(l - 1)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "461378e9179c9de454674ea9dc49c56c"} {"nl": {"description": "You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.", "input_spec": "The only line of the input contains seven integers: k,\u2009n1,\u2009n2,\u2009n3,\u2009t1,\u2009t2,\u2009t3 (1\u2009\u2264\u2009k\u2009\u2264\u2009104;\u00a01\u2009\u2264\u2009n1,\u2009n2,\u2009n3,\u2009t1,\u2009t2,\u2009t3\u2009\u2264\u20091000).", "output_spec": "Print one integer \u2014 smallest number of minutes to do all your laundry.", "sample_inputs": ["1 1 1 1 5 5 5", "8 4 3 2 10 5 2"], "sample_outputs": ["15", "32"], "notes": "NoteIn the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0,\u20090,\u20092,\u20095,\u200910,\u200910,\u200912 and 15 minutes respectively. The last piece of laundry will be ready after 15\u2009+\u200910\u2009+\u20095\u2009+\u20092\u2009=\u200932 minutes."}, "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport java.lang.Math\n\nobject D extends App {\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n \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(k, nX, nY, nZ, tX, tY, tZ) = readInts(7)\n\n val g = gcd(gcd(tX, tY), tZ)\n\n val T = k * (tX + tY + tZ) / g\n val availX = Array.ofDim[Short](T - k * (tY + tZ) / g + 3) // { nZ.toShort }\n val availY = Array.ofDim[Short](T - k * tZ / g + 3) // { nY.toShort }\n val availZ = Array.ofDim[Short](T + 3) // { nX.toShort }\n \n var t = 0\n var remain = k.toShort\n\n while (remain > 0) {\n val t2 = t + tX / g\n val t3 = t2 + tY / g\n val take = Math.min(Math.min(availX(t) + nX,\n availY(t2) + nY), \n Math.min(availZ(t3) + nZ, remain)).toShort\n if (take > 0) {\n\n var i = t\n var to = t2\n while (i < to) {\n availX(i) = (availX(i) - take).toShort\n i += 1\n }\n\n i = t2\n to = t3\n while (i < to) {\n availY(i) = (availY(i) - take).toShort\n i += 1\n }\n\n i = t3\n to = i + tZ / g\n while (i < to) {\n availZ(i) = (availZ(i) - take).toShort\n i += 1\n }\n\n }\n\n t += 1\n remain = (remain - take).toShort\n }\n\n println((t - 1) * g + tX + tY + tZ)\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 java.lang.Math\n\nobject D extends App {\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n \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(k, nX, nY, nZ, tX, tY, tZ) = readInts(7)\n\n val g = gcd(gcd(tX, tY), tZ)\n\n val T = k * (tX + tY + tZ) / g\n val availX = Array.ofDim[Short](T - k * (tY + tZ) / g + 3) // { nZ.toShort }\n val availY = Array.ofDim[Short](T - k * tZ / g + 3) // { nY.toShort }\n val availZ = Array.ofDim[Short](T + 3) // { nX.toShort }\n \n var t = 0\n var remain = k.toShort\n\n while (remain > 0) {\n val t2 = t + tX / g\n val t3 = t2 + tY / g\n val take = Math.min(Math.min(availX(t) + nX,\n availY(t2) + nY), \n Math.min(availZ(t3) + nZ, remain)).toShort\n if (take > 0) {\n\n var i = t\n var to = t2\n while (i < to) {\n availX(i) = (availX(i) - take).toByte\n i += 1\n }\n\n i = t2\n to = t3\n while (i < to) {\n availY(i) = (availY(i) - take).toShort\n i += 1\n }\n\n i = t3\n to = i + tZ / g\n while (i < to) {\n availZ(i) = (availZ(i) - take).toShort\n i += 1\n }\n\n }\n\n t += 1\n remain = (remain - take).toShort\n }\n\n println((t - 1) * g + tX + tY + tZ)\n}\n"}, {"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport java.lang.Math\n\nobject D extends App {\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n \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(k, nX, nY, nZ, tX, tY, tZ) = readInts(7)\n\n val g = gcd(gcd(tX, tY), tZ)\n\n val T = k * (tX + tY + tZ) / g\n val availX = Array.fill(T - k * (tY + tZ) / g + 3){ nX.toShort }\n val availY = Array.fill(T - k * tZ / g + 3){ nY.toShort }\n val availZ = Array.fill(T + 3){ nZ.toShort }\n \n var t = 0\n var remain = k.toShort\n\n while (remain > 0) {\n val t2 = t + tX / g\n val t3 = t2 + tY / g\n val take = Math.min(Math.min(availX(t),\n availY(t2)), \n Math.min(availZ(t3), remain)).toShort\n if (take > 0) {\n\n var i = t\n var to = t2\n while (i < to) {\n availX(i) = (availX(i) - take).toByte\n i += 1\n }\n\n i = t2\n to = t3\n while (i < to) {\n availY(i) = (availY(i) - take).toShort\n i += 1\n }\n\n i = t3\n to = i + tZ / g\n while (i < to) {\n availZ(i) = (availZ(i) - take).toShort\n i += 1\n }\n\n }\n\n t += 1\n remain = (remain - take).toShort\n }\n\n println((t - 1) * g + tX + tY + tZ)\n}\n"}], "src_uid": "dd1d166772ee06b383d4ceb94b530fd1"} {"nl": {"description": "A permutation of length n is an integer sequence such that each integer from 0 to (n\u2009-\u20091) appears exactly once in it. For example, sequence [0,\u20092,\u20091] is a permutation of length 3 while both [0,\u20092,\u20092] and [1,\u20092,\u20093] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 if and only if ai\u2009=\u2009i. For example, permutation [0,\u20092,\u20091] has 1 fixed point and permutation [0,\u20091,\u20092] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 \u2014 the given permutation.", "output_spec": "Print a single integer \u2014 the maximum possible number of fixed points in the permutation after at most one swap operation.", "sample_inputs": ["5\n0 1 3 4 2"], "sample_outputs": ["3"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 50$$$)\u00a0\u2014 the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \\le x_i, y_i \\le 10^4$$$)\u00a0\u2014 the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.", "output_spec": "Print a single integer\u00a0\u2014 the number of pairs of wires that are intersecting.", "sample_inputs": ["4\n0 0\n1 1\n0 3\n1 2", "4\n0 0\n0 2\n0 4\n2 0", "3\n-1 -1\n1 0\n3 1"], "sample_outputs": ["14", "6", "0"], "notes": "NoteIn the first example: In the second example: Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example: "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n case class Coord(x: Int, y: Int)\n case class Line(a: Int, b: Int, c: Int) {\n def slope: Slope = Slope(a, b)\n }\n case class Slope(a: Int, b: Int)\n\n def toLine(c1: Coord, c2: Coord): Line = {\n var a = c2.y - c1.y\n var b = c1.x - c2.x\n\n if (a < 0) {\n a *= -1\n b *= -1\n }\n\n if (a != 0 && b != 0) {\n val g = gcd(a, b)\n a /= g\n b /= g\n }\n\n if (a == 0) b = 1\n else if (b == 0) a = 1\n\n val c = -(c1.x * a + c1.y * b)\n Line(a, b, c)\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(): Unit = {\n val N = ni()\n val P = Array.ofDim[Coord](N)\n REP(N) { i =>\n val x, y = ni()\n P(i) = Coord(x, y)\n }\n\n val lines = mutable.Set[Line]()\n\n REP(N - 1) { i =>\n TO(i + 1, N - 1) { j =>\n lines += toLine(P(i), P(j))\n }\n }\n\n val slope = mutable.Map[Slope, Int]().withDefaultValue(0)\n lines.foreach { l =>\n val s = l.slope\n slope(s) = slope(s) + 1\n }\n\n val lineNum = lines.size\n var ans = 0L\n slope.foreach { case (_, num) =>\n ans += num.toLong * (lineNum - num)\n }\n out.println(ans / 2)\n }\n}"}], "negative_code": [], "src_uid": "8c2e0cd780cf9390e933e28e57643cba"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$ and an array $$$b_1, b_2, \\dots, b_n$$$.For one operation you can sort in non-decreasing order any subarray $$$a[l \\dots r]$$$ of the array $$$a$$$.For example, if $$$a = [4, 2, 2, 1, 3, 1]$$$ and you choose subbarray $$$a[2 \\dots 5]$$$, then the array turns into $$$[4, 1, 2, 2, 3, 1]$$$. You are asked to determine whether it is possible to obtain the array $$$b$$$ by applying this operation any number of times (possibly zero) to the array $$$a$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 3 \\cdot 10^5$$$) \u2014 the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \\le n \\le 3 \\cdot 10^5$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$). The third line of each query contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le n$$$). It is guaranteed that $$$\\sum n \\le 3 \\cdot 10^5$$$ over all queries in a test.", "output_spec": "For each query print YES (in any letter case) if it is possible to obtain an array $$$b$$$ and NO (in any letter case) otherwise.", "sample_inputs": ["4\n7\n1 7 1 4 4 5 6\n1 1 4 4 5 7 6\n5\n1 1 3 3 5\n1 1 3 3 5\n2\n1 1\n1 2\n3\n1 2 3\n3 2 1"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn first test case the can sort subarray $$$a_1 \\dots a_5$$$, then $$$a$$$ will turn into $$$[1, 1, 4, 4, 7, 5, 6]$$$, and then sort subarray $$$a_5 \\dots a_6$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A, B = na(N)\n val INF = 1e9.toInt\n val t = new SegmentTree(N, INF)(min)\n REP(N) { i =>\n t.update(i, A(i))\n }\n val ix = Array.fill[java.util.ArrayDeque[Int]](N + 1)(new java.util.ArrayDeque)\n REP(N) { i =>\n ix(A(i)).add(i)\n }\n\n var ok = true\n REP(N) { i =>\n val j = ix(B(i)).poll()\n ok &&= t.query(0, j + 1) == B(i)\n t.update(j, INF)\n }\n if (ok) out.println(\"YES\")\n else out.println(\"NO\")\n }\n }\n\n /**\n * @param n \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\n * type A = Int\n */\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\n }\n }\n}"}], "negative_code": [], "src_uid": "0bc73dfd5745b00c24e3553b161d75a4"} {"nl": {"description": "Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \\dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \\dots, i$$$ by $$$1$$$. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \\dots, n$$$ by $$$1$$$. Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u00a0\u2014 the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 200\\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$) \u2014 the initial levels of trees moisture. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\\,000$$$.", "output_spec": "For each test case output a single integer \u2014 the minimum number of actions. It can be shown that the answer exists.", "sample_inputs": ["4\n3\n-2 -2 -2\n3\n10 4 7\n4\n4 -4 4 -4\n5\n1 -2 3 -4 5"], "sample_outputs": ["2\n13\n36\n33"], "notes": "NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$. "}, "positive_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n val n = readInt()\r\n for (i <- 1 to n){\r\n val k = readInt()\r\n val l = readLine.split(\" \").map(_.toInt)\r\n val buf = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (j <- 0 until l.length-1) {\r\n buf += (l(j) - l(j+1))\r\n }\r\n val b = buf.toList\r\n var t: Long = 0\r\n var m: Long = 0\r\n val q = l(l.length-1)\r\n for (a <- b) {\r\n t+=abs(a)\r\n if (a < 0) {\r\n m +=a\r\n }\r\n\r\n }\r\n println(t+abs(q+m))\r\n }\r\n\r\n\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n val n = readInt()\r\n for (i <- 1 to n){\r\n val k = readInt()\r\n val l = readLine.split(\" \").map(_.toInt)\r\n val buf = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (j <- 0 until l.length-1) {\r\n buf += (l(j) - l(j+1))\r\n }\r\n val b = buf.toList\r\n var t = 0\r\n var m = 0\r\n val q = l(l.length-1)\r\n for (a <- b) {\r\n t+=abs(a)\r\n if (a < 0) {\r\n m +=a\r\n }\r\n\r\n }\r\n println(t+abs(q+m))\r\n }\r\n\r\n\r\n}\r\n\r\n"}], "src_uid": "f54c1448a279e59f96847a158f993101"} {"nl": {"description": "Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\\,010\\,111$$$ is a binary decimal, while $$$10\\,201$$$ and $$$787\\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$), denoting the number to be represented.", "output_spec": "For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.", "sample_inputs": ["3\n121\n5\n1000000000"], "sample_outputs": ["2\n5\n1"], "notes": "NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\\,000\\,000\\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains two integers n,\u2009k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of elements in a and the parameter k. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the elements of the array a.", "output_spec": "Print two integers l,\u2009r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) \u2014 the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.", "sample_inputs": ["5 5\n1 2 3 4 5", "9 3\n6 5 1 2 3 2 1 4 5", "3 1\n1 2 3"], "sample_outputs": ["1 5", "3 7", "1 1"], "notes": null}, "positive_code": [{"source_code": "import io.StdIn._\nimport scala.collection.mutable._\n\nobject Solution extends App {\n val nks = readLine().split(\" \")\n val nk = nks.map(_.toInt)\n\n val n = nk(0)\n val k = nk(1)\n \n val arr = readLine().split(\" \")\n val inp = arr.map(_.toInt)\n \n val a = new Array[Int](1000001)\n \n var l = 0\n var r = 0\n var maxans = 0\n var maxR = 0\n var maxL = 0 \n var curent = 0 \n \n for ( r <- 0 to (n-1) ) {\n a ( inp(r) ) = a ( inp ( r ) ) + 1 \n \n if ( a ( inp ( r ) ) == 1 ) {\n curent = curent + 1 \n }\n \n if ( curent <= k ) {\n if ( r - l + 1 > maxans ) {\n maxR = r\n maxL = l \n maxans = r - l + 1 \n }\n }\n \n \n while ( curent > k ) {\n a ( inp ( l ) ) = a ( inp ( l ) ) - 1 \n \n if ( a ( inp ( l ) ) == 0 ) {\n curent = curent - 1 \n }\n \n l = l + 1\n }\n \n \n }\n \n \n println ( (maxL+1) + \" \" + (maxR+1) ) \n \n \n}"}], "negative_code": [], "src_uid": "e0ea798c8ce0d8a4340e0fa3399bcc3b"} {"nl": {"description": "A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that: exactly two of them belong to the same side of a rectangle; the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \\le w, h \\le 10^6$$$)\u00a0\u2014 the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \\le k \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \\dots < x_k$$$ ($$$0 < x_i < w$$$)\u00a0\u2014 the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \\le k \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \\dots < y_k$$$ ($$$0 < y_i < h$$$)\u00a0\u2014 the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase print a single integer\u00a0\u2014 the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.", "sample_inputs": ["3\n5 8\n2 1 2\n3 2 3 4\n3 1 4 6\n2 4 5\n10 7\n2 3 9\n2 1 7\n3 1 3 4\n3 4 5 6\n11 5\n3 1 6 8\n3 3 6 8\n3 1 3 4\n2 2 4"], "sample_outputs": ["25\n42\n35"], "notes": "NoteThe points in the first testcase of the example: $$$(1, 0)$$$, $$$(2, 0)$$$; $$$(2, 8)$$$, $$$(3, 8)$$$, $$$(4, 8)$$$; $$$(0, 1)$$$, $$$(0, 4)$$$, $$$(0, 6)$$$; $$$(5, 4)$$$, $$$(5, 5)$$$. The largest triangle is formed by points $$$(0, 1)$$$, $$$(0, 6)$$$ and $$$(5, 4)$$$\u00a0\u2014 its area is $$$\\frac{25}{2}$$$. Thus, the doubled area is $$$25$$$. Two points that are on the same side are: $$$(0, 1)$$$ and $$$(0, 6)$$$."}, "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 w = readLong()\n val h = readLong()\n var x = 0L\n var y = 0L\n for (i <- 1 to 4){\n val k = readInt()\n val mn = readInt()\n var mx = 0\n for (j <- 2 to k) {\n mx = readInt()\n }\n if (i < 3)\n x = max(x, (mx - mn).toLong)\n else\n y = max(y, (mx - mn).toLong)\n }\n writer.println(max(x * h, y * w))\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": "2c67ee95eba7ffbbed99cb488abb5f3d"} {"nl": {"description": "Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009105). The second line contains m integers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u2009n). Note that Xenia can have multiple consecutive tasks in one house.", "output_spec": "Print a single integer \u2014 the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4 3\n3 2 3", "4 3\n2 3 3"], "sample_outputs": ["6", "2"], "notes": "NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1\u2009\u2192\u20092\u2009\u2192\u20093\u2009\u2192\u20094\u2009\u2192\u20091\u2009\u2192\u20092\u2009\u2192\u20093. This is optimal sequence. So, she needs 6 time units."}, "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": "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"}, {"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"} {"nl": {"description": "A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it\u00a0\u2014 the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \\dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \\dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$\u00a0\u2014 that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$\u00a0\u2014 that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$\u00a0\u2014 that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$\u00a0\u2014 that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 99$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the required length of permutations in the chain.", "output_spec": "For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \\dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \\dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.", "sample_inputs": ["2\n\n2\n\n3"], "sample_outputs": ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n @inline def operations(n: Int): List[List[Int]] = {\n val current = ArrayBuffer((1 to n) :_*)\n\n var result = List[List[Int]](current.toList)\n for (i <- 2 to n) {\n val j = n - i\n val a = current(j)\n val b = current(j + 1)\n\n current(j) = b\n current(j + 1) = a\n\n result = result :+ current.toList\n }\n\n result\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 val seq = operations(n)\n println(seq.size)\n seq.foreach(a => println(a.mkString(\" \")))\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject B extends App {\n\n import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}\n\n solve()\n\n @inline def operations(n: Int): List[List[Int]] = {\n val current = ArrayBuffer((1 to n) :_*)\n\n var result = List[List[Int]](current.toList)\n for (i <- 2 to n) {\n val j = n - i\n val a = current(j)\n val b = current(j + 1)\n\n current(j) = b\n current(j + 1) = a\n\n result = result :+ current.toList\n }\n\n result\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 val seq = operations(n)\n seq.foreach(a => println(a.mkString(\" \")))\n }\n }\n\n}\n"}], "src_uid": "02bdd12987af6e666d4283f075f73725"} {"nl": {"description": "We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1\\le t\\le 1000)$$$ \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\\le n\\le 2 \\cdot 10^5)$$$ \u00a0\u2014 the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$)\u00a0\u2014 elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"Yes\" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and \"No\" (without quotes) otherwise. You can output \"Yes\" and \"No\" in any case (for example, strings \"yEs\", \"yes\" and \"Yes\" will be recognized as a positive response).", "sample_inputs": ["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"], "sample_outputs": ["No\nYes\nNo\nNo\nYes\nYes\nYes"], "notes": "NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\\langle \\underline{0}, 0, 0, 0\\rangle \\to \\langle 1, \\underline{0}, 0, 0 \\rangle \\to \\langle \\underline{1}, -1, 0, 0\\rangle \\to \\langle 2, \\underline{-1}, 0, 0\\rangle \\to \\langle 2, 0, \\underline{0}, 0\\rangle \\to \\langle 2, \\underline{0}, -1, 0\\rangle \\to \\langle \\underline{2}, -1, -1, 0\\rangle$$$"}, "positive_code": [{"source_code": "object Main1 extends App {\r\n\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Long]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Long](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Long]): Boolean = {\r\n val sumArr = ar.scan(0L)(_ + _).tail\r\n val indexSumZero = sumArr.indexWhere(_ == 0)\r\n val lastNonZero = ar.lastIndexWhere(_ != 0)\r\n indexSumZero match {\r\n case -1 => false\r\n case _ if lastNonZero > indexSumZero => false\r\n case _ if sumArr.exists(_ < 0) => false\r\n case _ => true\r\n }\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(if (check(array(i))) \"Yes\" else \"No\")\r\n }\r\n}"}], "negative_code": [{"source_code": "object Main extends App {\r\n\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): Boolean = {\r\n val sumArr = ar.scan(0)(_ + _).tail\r\n val indexZero = sumArr.indexWhere(_ == 0)\r\n val lastNonZero = ar.lastIndexWhere(_ != 0)\r\n indexZero match {\r\n case -1 => false\r\n case _ if lastNonZero > indexZero => false\r\n case _ if sumArr.exists(_ < 0) => false\r\n case _ => true\r\n }\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(if (check(array(i))) \"Yes\" else \"No\")\r\n }\r\n\r\n}"}, {"source_code": "object Main extends App {\r\n\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): Boolean = {\r\n val sumArr = ar.scan(0)(_ + _).tail\r\n val indexZero = sumArr.indexWhere(_ == 0)\r\n val lastNonZero = sumArr.lastIndexWhere(_ != 0)\r\n indexZero match {\r\n case -1 => false\r\n case _ if lastNonZero > indexZero => false\r\n case _ if sumArr.exists(_ < 0) => false\r\n case _ => true\r\n }\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(if (check(array(i))) \"Yes\" else \"No\")\r\n }\r\n\r\n}"}, {"source_code": "object Main extends App {\r\n\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): Boolean = {\r\n val sumArr = ar.scan(0)(_ + _).tail\r\n val indexZero = sumArr.indexWhere(_ == 0)\r\n val lastNonZero = sumArr.lastIndexWhere(_ != 0)\r\n indexZero match {\r\n case -1 => false\r\n case _ if lastNonZero > indexZero => false\r\n case _ => true\r\n }\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(if (check(array(i))) \"Yes\" else \"No\")\r\n }\r\n\r\n}"}, {"source_code": "object Main extends App {\r\n\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): Boolean = {\r\n val sumArr = ar.scan(0)(_ + _)\r\n val indexZero = sumArr.indexWhere(_ == 0)\r\n val lastNonZero = sumArr.lastIndexWhere(_ != 0)\r\n indexZero match {\r\n case -1 => false\r\n case _ if lastNonZero > indexZero => false\r\n case _ => true\r\n }\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(if (check(array(i))) \"Yes\" else \"No\")\r\n }\r\n\r\n}"}, {"source_code": "object Main extends App {\r\n\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): Boolean = {\r\n val last = ar.lastIndexWhere(_ != 0)\r\n val ar2 = ar.take(last + 1)\r\n (1 to last).foldLeft(true) { (b, i) =>\r\n val left = ar2.take(i).sum\r\n val right = ar2.takeRight(ar2.length - i).sum\r\n b && left == -right && (left > right)\r\n }\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(if (check(array(i))) \"Yes\" else \"No\")\r\n }\r\n\r\n}"}, {"source_code": "object Main extends App {\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): String = {\r\n val result = (1 until ar.length).foldLeft(true) { (b, i) =>\r\n val left = ar.take(i).sum\r\n val right = ar.takeRight(ar.length - i).sum\r\n left == -right && ((left > right) || (left == 0 && right == 0)) && b\r\n }\r\n if (result) \"Yes\" else \"No\"\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(check(array(i)))\r\n }\r\n}"}, {"source_code": "object Main extends App {\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): String = {\r\n val result = (1 until ar.length).foldLeft(true) { (b, i) =>\r\n val left = ar.take(i).sum\r\n val right = ar.takeRight(ar.length - i).sum\r\n left == -right && left > right && b\r\n }\r\n if (result) \"Yes\" else \"No\"\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(check(array(i)))\r\n }\r\n}"}, {"source_code": "object Main extends App {\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): String = {\r\n val result = (1 until ar.length).foldLeft(true) { (b, i) =>\r\n val left = ar.take(i).sum\r\n val right = ar.takeRight(ar.length - i).sum\r\n left == -right && left >= right && b\r\n }\r\n if (result) \"Yes\" else \"No\"\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(check(array(i)))\r\n }\r\n}"}, {"source_code": " object Main extends App {\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): String = {\r\n val b = (1 until ar.length).foldLeft(true) { (b, i) =>\r\n val left = ar.take(i).sum\r\n val right = ar.takeRight(ar.length - 1).sum\r\n left == -right && left >= right && b\r\n }\r\n if (b) \"Yes\" else \"No\"\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(check(array(i)))\r\n }\r\n }"}, {"source_code": "object Main extends App {\r\n val scanner = new java.util.Scanner(System.in)\r\n val t = scanner.nextInt()\r\n val array = new Array[Array[Int]](t)\r\n (0 until t).foreach { i =>\r\n val n = scanner.nextInt()\r\n val ar = new Array[Int](n)\r\n (0 until n).foreach { j =>\r\n ar(j) = scanner.nextInt()\r\n }\r\n array(i) = ar\r\n }\r\n\r\n def check(ar: Array[Int]): String = {\r\n val b = ar.head == -1 * ar.tail.sum && ar.last == -1 * ar.init.sum\r\n if (b) \"Yes\" else \"No\"\r\n }\r\n\r\n (0 until t).foreach { i =>\r\n println(check(array(i)))\r\n }\r\n}"}], "src_uid": "9f0ffcbd0ce62a365a1ecbb4a2c1de3e"} {"nl": {"description": "There are $$$n$$$ heaps of stone. The $$$i$$$-th heap has $$$h_i$$$ stones. You want to change the number of stones in the heap by performing the following process once: You go through the heaps from the $$$3$$$-rd heap to the $$$n$$$-th heap, in this order. Let $$$i$$$ be the number of the current heap. You can choose a number $$$d$$$ ($$$0 \\le 3 \\cdot d \\le h_i$$$), move $$$d$$$ stones from the $$$i$$$-th heap to the $$$(i - 1)$$$-th heap, and $$$2 \\cdot d$$$ stones from the $$$i$$$-th heap to the $$$(i - 2)$$$-th heap. So after that $$$h_i$$$ is decreased by $$$3 \\cdot d$$$, $$$h_{i - 1}$$$ is increased by $$$d$$$, and $$$h_{i - 2}$$$ is increased by $$$2 \\cdot d$$$. You can choose different or same $$$d$$$ for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 2\\cdot 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$). The second lines of each test case contains $$$n$$$ integers $$$h_1, h_2, h_3, \\ldots, h_n$$$ ($$$1 \\le h_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the maximum number of stones that the smallest heap can contain.", "sample_inputs": ["4\n4\n1 2 10 100\n4\n100 100 100 1\n5\n5 1 1 1 8\n6\n1 2 3 4 5 6"], "sample_outputs": ["7\n1\n1\n3"], "notes": "NoteIn the first test case, the initial heap sizes are $$$[1, 2, 10, 100]$$$. We can move the stones as follows. move $$$3$$$ stones and $$$6$$$ from the $$$3$$$-rd heap to the $$$2$$$-nd and $$$1$$$ heap respectively. The heap sizes will be $$$[7, 5, 1, 100]$$$; move $$$6$$$ stones and $$$12$$$ stones from the last heap to the $$$3$$$-rd and $$$2$$$-nd heap respectively. The heap sizes will be $$$[7, 17, 7, 82]$$$. In the second test case, the last heap is $$$1$$$, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be $$$[3, 5, 3, 4, 3, 3]$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "895d5850e420a36ae3b5f0a50e359423"} {"nl": {"description": "Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves: Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$. Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer \u00a0\u2014 $$$n$$$ ($$$1 \\leq n \\leq 10^9$$$).", "output_spec": "For each test case, print \"Ashishgup\" if he wins, and \"FastestFinger\" otherwise (without quotes).", "sample_inputs": ["7\n1\n2\n3\n4\n5\n6\n12"], "sample_outputs": ["FastestFinger\nAshishgup\nAshishgup\nFastestFinger\nAshishgup\nFastestFinger\nAshishgup"], "notes": "NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$."}, "positive_code": [{"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val LIMIT = 100000\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 //println(i)\n i += 1\n }\n val primes = isPrime.indices.toArray.filter(isPrime(_))\n//println(primes.length)\n for (_ <- 1 to nextInt) {\n var n = nextInt\n var step = 0\n while (n > 1) {\n step += 1\n val b = 1 << Integer.numberOfTrailingZeros(n)\n if (n % 2 == 1) {\n n = 1\n } else if (n == 2) {\n n = 1\n } else if (n > b) {\n var i = 1\n while (i < primes.length && n % primes(i) != 0) {\n i += 1\n }\n if (i < primes.length && b == 2) {\n if (n == primes(i) * b) {\n n = b\n } else {\n n = primes(i) * b\n }\n } else {\n n = b\n }\n } else {\n n -= 1\n }\n //println(step, n, b)\n }\n val win = step % 2 == 1 //n > 1 && (n % 2 == 1 || ((Integer.bitCount(n) > 1 || n == 2) && (n / 2 % 2 == 0)))\n out.println(if (win) \"Ashishgup\" else \"FastestFinger\")\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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n var n = nextInt\n\n var step = 0\n while (n > 1) {\n step += 1\n val b = 1 << Integer.numberOfTrailingZeros(n)\n if (n % 2 == 1) {\n n = 1\n } else if (n == 2) {\n n = 1\n } else if (n > b) {\n n = b\n } else {\n n -= 1\n }\n //println(step, n, b)\n }\n val win = step % 2 == 1 //n > 1 && (n % 2 == 1 || ((Integer.bitCount(n) > 1 || n == 2) && (n / 2 % 2 == 0)))\n out.println(if (win) \"Ashishgup\" else \"FastestFinger\")\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val LIMIT = 100000\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 //println(i)\n i += 1\n }\n val primes = isPrime.indices.toArray.filter(isPrime(_))\n//println(primes.length)\n for (_ <- 1 to nextInt) {\n var n = nextInt\n var step = 0\n while (n > 1) {\n step += 1\n val b = 1 << Integer.numberOfTrailingZeros(n)\n if (n % 2 == 1) {\n n = 1\n } else if (n == 2) {\n n = 1\n } else if (n > b) {\n var i = 1\n while (n % primes(i) != 0 && i < primes.length) {\n i += 1\n }\n if (i < primes.length && (n / b) / primes(i) > 0) {\n if (n == primes(i) * b) {\n n = b\n } else {\n n = primes(i) * b\n }\n } else {\n n = b\n }\n } else {\n n -= 1\n }\n// println(step, n, b)\n }\n val win = step % 2 == 1 //n > 1 && (n % 2 == 1 || ((Integer.bitCount(n) > 1 || n == 2) && (n / 2 % 2 == 0)))\n out.println(if (win) \"Ashishgup\" else \"FastestFinger\")\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": "b533572dd6d5fe7350589c7f4d5e1c8c"} {"nl": {"description": "We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings \"ab\" in the string and replace it with the string \"bba\". If we have no \"ab\" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109\u2009+\u20097.The string \"ab\" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.", "input_spec": "The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.", "output_spec": "Print the minimum number of steps modulo 109\u2009+\u20097.", "sample_inputs": ["ab", "aab"], "sample_outputs": ["1", "3"], "notes": "NoteThe first example: \"ab\" \u2009\u2192\u2009 \"bba\".The second example: \"aab\" \u2009\u2192\u2009 \"abba\" \u2009\u2192\u2009 \"bbaba\" \u2009\u2192\u2009 \"bbbbaa\"."}, "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 def readLongs(n: Int) = { val tl = 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 val MOD = 1000000007L\n\n var aCnt = 0L\n var pow = 1L\n for (c <- s) {\n if (c == 'a') {\n aCnt = (aCnt + pow) % MOD\n pow = 2 * pow % MOD\n } else res = (res + aCnt) % MOD\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "8f52241c690ec4f9af71a52904fb19a0"} {"nl": {"description": "Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\\leq i \\leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \\,\\&\\, a_{r-i}$$$ at the same time, where $$$\\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\\,\\&\\, a_5, a_3\\,\\&\\, a_4, a_4\\,\\&\\, a_3, a_5\\,\\&\\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$).", "output_spec": "For each test case, print one integer \u2014 the minimal value of the maximum value in the sequence.", "sample_inputs": ["4\n2\n1 2\n3\n1 1 3\n4\n3 11 3 7\n5\n11 7 15 3 7"], "sample_outputs": ["0\n1\n3\n3"], "notes": "NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\\,\\&\\,2$$$, and the second element is $$$2\\,\\&\\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\\,\\&\\,3$$$, the second element is $$$1\\,\\&\\,1$$$, and the third element is $$$3\\,\\&\\,1$$$."}, "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": "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"}, {"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"} {"nl": {"description": "This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $$$a_1, a_2, \\dots, a_n$$$.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \\dots a_{p - 1} a_p, b_1 b_2 \\dots b_{q - 1} b_q)$$$, where $$$a_1 \\dots a_p$$$ and $$$b_1 \\dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally, if $$$p \\ge q$$$ then $$$f(a_1 \\dots a_p, b_1 \\dots b_q) = a_1 a_2 \\dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$$$; if $$$p < q$$$ then $$$f(a_1 \\dots a_p, b_1 \\dots b_q) = b_1 b_2 \\dots b_{q - p} a_1 b_{q - p + 1} a_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$, your task is to help students to calculate $$$\\sum_{i = 1}^{n}\\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\\,244\\,353$$$.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$) \u2014 the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the elements of the array.", "output_spec": "Print the answer modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["3\n12 3 45", "2\n123 456"], "sample_outputs": ["12330", "1115598"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 998244353\n\n /*\n * 10^18\u307e\u3067\u306epow\u3092\u914d\u5217\u3067\u7528\u610f\u3057\u3066\u304a\u304f\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\u306e\u6574\u6570\u5024\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}"}], "negative_code": [], "src_uid": "b4cd60296083ee2ae8a560209433dcaf"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \\le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 4 \\cdot 10^5$$$) \u2014 the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).", "sample_inputs": ["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"], "sample_outputs": ["cccbbabaccbc", "cccccc", ""], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "9f095a5f5b39d8c2f99c4162f2d7c5ff"} {"nl": {"description": "The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given an integer $$$n$$$. You have to find a sequence $$$s$$$ consisting of digits $$$\\{1, 3, 7\\}$$$ such that it has exactly $$$n$$$ subsequences equal to $$$1337$$$.For example, sequence $$$337133377$$$ has $$$6$$$ subsequences equal to $$$1337$$$: $$$337\\underline{1}3\\underline{3}\\underline{3}7\\underline{7}$$$ (you can remove the second and fifth characters); $$$337\\underline{1}\\underline{3}3\\underline{3}7\\underline{7}$$$ (you can remove the third and fifth characters); $$$337\\underline{1}\\underline{3}\\underline{3}37\\underline{7}$$$ (you can remove the fourth and fifth characters); $$$337\\underline{1}3\\underline{3}\\underline{3}\\underline{7}7$$$ (you can remove the second and sixth characters); $$$337\\underline{1}\\underline{3}3\\underline{3}\\underline{7}7$$$ (you can remove the third and sixth characters); $$$337\\underline{1}\\underline{3}\\underline{3}3\\underline{7}7$$$ (you can remove the fourth and sixth characters). Note that the length of the sequence $$$s$$$ must not exceed $$$10^5$$$.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10$$$) \u2014 the number of queries. Next $$$t$$$ lines contains a description of queries: the $$$i$$$-th line contains one integer $$$n_i$$$ ($$$1 \\le n_i \\le 10^9$$$).", "output_spec": "For the $$$i$$$-th query print one string $$$s_i$$$ ($$$1 \\le |s_i| \\le 10^5$$$) consisting of digits $$$\\{1, 3, 7\\}$$$. String $$$s_i$$$ must have exactly $$$n_i$$$ subsequences $$$1337$$$. If there are multiple such strings, print any of them.", "sample_inputs": ["2\n6\n1"], "sample_outputs": ["113337\n1337"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n var n = ni()\n val sevens = Array.ofDim[Int](10001)\n var i = 10000\n while(n > 0) {\n while(i * (i - 1) / 2 > n) i -=1\n n -= i * (i - 1) / 2\n sevens(i) += 1\n }\n out.print(\"1\")\n REP(10000, 1) { i =>\n out.print(\"3\")\n REP(sevens(i)) { _ =>\n out.print(\"7\")\n }\n }\n out.println()\n }\n }\n}"}], "negative_code": [], "src_uid": "9aabacc9817722dc11335eccac5d65ac"} {"nl": {"description": "Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.", "input_spec": "The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: ", "output_spec": "Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).", "sample_inputs": ["AHA", "Z", "XO"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "The police department of your city has just started its journey. Initially, they don\u2019t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.", "input_spec": "The first line of input will contain an integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.", "output_spec": "Print a single integer, the number of crimes which will go untreated.", "sample_inputs": ["3\n-1 -1 1", "8\n1 -1 1 -1 -1 1 1 1", "11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1"], "sample_outputs": ["2", "1", "8"], "notes": "NoteLets consider the second example: Firstly one person is hired. Then crime appears, the last hired person will investigate this crime. One more person is hired. One more crime appears, the last hired person will investigate this crime. Crime appears. There is no free policeman at the time, so this crime will go untreated. One more person is hired. One more person is hired. One more person is hired. The answer is one, as one crime (on step 5) will go untreated."}, "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": "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"}, {"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"} {"nl": {"description": "You are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder of ai divided by aj), where 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n and ai\u2009\u2265\u2009aj.", "input_spec": "The first line contains integer n\u00a0\u2014 the length of the sequence (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106).", "output_spec": "Print the answer to the problem.", "sample_inputs": ["3\n3 4 5"], "sample_outputs": ["2"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $$$80\\%$$$ of applicants are girls and majority of them are going to live in the university dormitory for the next $$$4$$$ (hopefully) years.The dormitory consists of $$$n$$$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $$$i$$$ costs $$$c_i$$$ burles. Rooms are numbered from $$$1$$$ to $$$n$$$.Mouse doesn't sit in place all the time, it constantly runs. If it is in room $$$i$$$ in second $$$t$$$ then it will run to room $$$a_i$$$ in second $$$t + 1$$$ without visiting any other rooms inbetween ($$$i = a_i$$$ means that mouse won't leave room $$$i$$$). It's second $$$0$$$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $$$1$$$ to $$$n$$$ at second $$$0$$$.What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?", "input_spec": "The first line contains as single integers $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of rooms in the dormitory. The second line contains $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$1 \\le c_i \\le 10^4$$$) \u2014 $$$c_i$$$ is the cost of setting the trap in room number $$$i$$$. The third line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$) \u2014 $$$a_i$$$ is the room the mouse will run to the next second after being in room $$$i$$$.", "output_spec": "Print a single integer \u2014 the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.", "sample_inputs": ["5\n1 2 3 2 10\n1 3 4 3 3", "4\n1 10 2 10\n2 4 2 2", "7\n1 1 1 1 1 1 1\n2 2 2 3 6 7 6"], "sample_outputs": ["3", "10", "2"], "notes": "NoteIn the first example it is enough to set mouse trap in rooms $$$1$$$ and $$$4$$$. If mouse starts in room $$$1$$$ then it gets caught immideately. If mouse starts in any other room then it eventually comes to room $$$4$$$.In the second example it is enough to set mouse trap in room $$$2$$$. If mouse starts in room $$$2$$$ then it gets caught immideately. If mouse starts in any other room then it runs to room $$$2$$$ in second $$$1$$$.Here are the paths of the mouse from different starts from the third example: $$$1 \\rightarrow 2 \\rightarrow 2 \\rightarrow \\dots$$$; $$$2 \\rightarrow 2 \\rightarrow \\dots$$$; $$$3 \\rightarrow 2 \\rightarrow 2 \\rightarrow \\dots$$$; $$$4 \\rightarrow 3 \\rightarrow 2 \\rightarrow 2 \\rightarrow \\dots$$$; $$$5 \\rightarrow 6 \\rightarrow 7 \\rightarrow 6 \\rightarrow \\dots$$$; $$$6 \\rightarrow 7 \\rightarrow 6 \\rightarrow \\dots$$$; $$$7 \\rightarrow 6 \\rightarrow 7 \\rightarrow \\dots$$$; So it's enough to set traps in rooms $$$2$$$ and $$$6$$$."}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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"}], "negative_code": [], "src_uid": "4278fece7812148863688c67218aca7b"} {"nl": {"description": "There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n\u2009>\u20091. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of banks. The second line contains n integers ai (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.", "output_spec": "Print the minimum number of operations required to change balance in each bank to zero.", "sample_inputs": ["3\n5 0 -5", "4\n-1 0 1 0", "4\n1 2 3 -6"], "sample_outputs": ["1", "2", "3"], "notes": "NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth. "}, "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.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"}, {"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"} {"nl": {"description": "There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \\ldots, y_{1,n}$$$ ($$$|y_{1,i}| \\le 10\\,000$$$) \u2014 the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \\ldots, y_{2,m}$$$ ($$$|y_{2,i}| \\le 10\\,000$$$) \u2014 the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.", "output_spec": "Print a single integer \u2013 the largest number of enemy spaceships that can be destroyed.", "sample_inputs": ["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"], "sample_outputs": ["9", "10"], "notes": "NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second \u2013 at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships."}, "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 ays = readInts(n)\n val bys = readInts(m)\n\n val hitBy = mutable.Map.empty[Double, mutable.Set[Int]]\n\n for {\n i <- ays.indices\n j <- bys.indices\n } {\n val mid = (ays(i) + bys(j)) / 2d\n if (hitBy.contains(mid)) {\n hitBy(mid) += -i - 1\n hitBy(mid) += j\n } else {\n hitBy(mid) = mutable.Set(-i - 1, j)\n }\n }\n\n var max = 0\n\n for {\n inC1 <- hitBy.valuesIterator\n inC2 <- hitBy.valuesIterator\n if inC1.size + inC2.size > max\n } {\n var total = inC1.size\n for (x <- inC2) if (!inC1(x)) total += 1\n if (total > max) max = total\n }\n\n println(max)\n}\n"}], "negative_code": [], "src_uid": "7dd891cef0aa40cc1522ca4b37963b92"} {"nl": {"description": "There is a polyline going through points (0,\u20090)\u2009\u2013\u2009(x,\u2009x)\u2009\u2013\u2009(2x,\u20090)\u2009\u2013\u2009(3x,\u2009x)\u2009\u2013\u2009(4x,\u20090)\u2009\u2013\u2009...\u2009-\u2009(2kx,\u20090)\u2009\u2013\u2009(2kx\u2009+\u2009x,\u2009x)\u2009\u2013\u2009.... We know that the polyline passes through the point (a,\u2009b). Find minimum positive value x such that it is true or determine that there is no such x.", "input_spec": "Only one line containing two positive integers a and b (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009109).", "output_spec": "Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009-\u20099. If there is no such x then output \u2009-\u20091 as the answer.", "sample_inputs": ["3 1", "1 3", "4 1"], "sample_outputs": ["1.000000000000", "-1", "1.250000000000"], "notes": "NoteYou can see following graphs for sample 1 and sample 3. "}, "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"}, {"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"}], "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"} {"nl": {"description": "Nauuo is a girl who loves drawing circles.One day she has drawn a circle and wanted to draw a tree on it.The tree is a connected undirected graph consisting of $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are numbered from $$$1$$$ to $$$n$$$.Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $$$n$$$ distinct points on the circle, and the edges should be straight without crossing each other.\"Without crossing each other\" means that every two edges have no common point or the only common point is an endpoint of both edges.Nauuo wants to draw the tree using a permutation of $$$n$$$ elements. A permutation of $$$n$$$ elements is a sequence of integers $$$p_1,p_2,\\ldots,p_n$$$ in which every integer from $$$1$$$ to $$$n$$$ appears exactly once.After a permutation is chosen Nauuo draws the $$$i$$$-th node in the $$$p_i$$$-th point on the circle, then draws the edges connecting the nodes.The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $$$998244353$$$, can you help her?It is obvious that whether a permutation is valid or not does not depend on which $$$n$$$ points on the circle are chosen.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2\\le n\\le 2\\cdot 10^5$$$) \u2014 the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\\le u,v\\le n$$$), denoting there is an edge between $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree.", "output_spec": "The output contains a single integer \u2014 the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $$$998244353$$$.", "sample_inputs": ["4\n1 2\n1 3\n2 4", "4\n1 2\n1 3\n1 4"], "sample_outputs": ["16", "24"], "notes": "NoteExample 1All valid permutations and their spanning trees are as follows.Here is an example of invalid permutation: the edges $$$(1,3)$$$ and $$$(2,4)$$$ are crossed.Example 2Every permutation leads to a valid tree, so the answer is $$$4! = 24$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 998244353\n\n val NN = 200000\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 val F = Array.ofDim[Long](NN + 1)\n F(0) = 1\n REP(NN) { i =>\n F(i + 1) = F(i) * (i + 1) % MOD\n }\n val I = Array.ofDim[Long](F.length)\n I(NN) = powMod(F(NN).toInt, MOD - 2, MOD)\n\n // x! = x(x-1)!\n // x!I(x!) \u2261 (x-1)!I((x-1)!)\n // I((x-1)!) \u2261 I(x!) * x MOD\u304c\u3067\u304b\u3044\u306e\u3067(x-1)!\u306fMOD\u3068\u7d20\n REP_r(NN) { 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) = {\n I(x) * F(x - 1) % MOD\n }\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (_, parent, queue) = traceBfs(g)\n\n val dp = Array.ofDim[Long](N)\n REP_r(N) { i =>\n val v = queue(i)\n var mul = 1L\n var cnt = 1 // v\u81ea\u8eab\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != parent(v)) {\n cnt += 1\n mul = mul * dp(u) % MOD\n }\n }\n if (v == 0) {\n // \u56de\u8ee2\u3057\u3066\u540c\u3058\u3082\u306e\u3092\u8003\u616e\u3059\u308b\n dp(v) = F(cnt - 1) * mul % MOD * N % MOD\n } else {\n dp(v) = F(cnt) * mul % MOD\n }\n }\n\n debug(dp)\n\n out.println(dp(0))\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": "03bfe285856fa74b89de7a1bebb14bca"} {"nl": {"description": "Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a \"+=\" operation that adds the right-hand side value to the left-hand side variable. For example, performing \"a += b\" when a = $$$2$$$, b = $$$3$$$ changes the value of a to $$$5$$$ (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations \"a += b\" or \"b += a\". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $$$n$$$. What is the smallest number of operations he has to perform?", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\leq T \\leq 100$$$)\u00a0\u2014 the number of test cases. Each of the following $$$T$$$ lines describes a single test case, and contains three integers $$$a, b, n$$$ ($$$1 \\leq a, b \\leq n \\leq 10^9$$$)\u00a0\u2014 initial values of a and b, and the value one of the variables has to exceed, respectively.", "output_spec": "For each test case print a single integer\u00a0\u2014 the smallest number of operations needed. Separate answers with line breaks.", "sample_inputs": ["2\n1 2 3\n5 4 100"], "sample_outputs": ["2\n7"], "notes": "NoteIn the first case we cannot make a variable exceed $$$3$$$ in one operation. One way of achieving this in two operations is to perform \"b += a\" twice."}, "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 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"}, {"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"} {"nl": {"description": "Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$\u00a0\u2014 at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \\le 1$$$ and $$$|y_1 - y_2| \\le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$\u00a0\u2014 at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \\le n \\le 100$$$)\u00a0\u2014 the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level\u00a0\u2014 the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.", "output_spec": "For each test case, output YES if it is possible to complete the level, and NO otherwise.", "sample_inputs": ["4\n3\n000\n000\n4\n0011\n1100\n4\n0111\n1110\n6\n010101\n101010"], "sample_outputs": ["YES\nYES\nNO\nYES"], "notes": "NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \\rightarrow (2, 2) \\rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 3) \\rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \\rightarrow (2, 2) \\rightarrow (1, 3) \\rightarrow (2, 4) \\rightarrow (1, 5) \\rightarrow (2, 6)$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "fefec879efd4f524de00684adee7cd19"} {"nl": {"description": "Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009k\u2009\u2264\u2009109)\u00a0\u2014 the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u2009104)\u00a0\u2014 number of pebbles of each type. ", "output_spec": "The only line of output contains one integer\u00a0\u2014 the minimum number of days Anastasia needs to collect all the pebbles.", "sample_inputs": ["3 2\n2 3 4", "5 4\n3 1 8 9 7"], "sample_outputs": ["3", "5"], "notes": "NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type\u00a0\u2014 on the second day, and of third type\u00a0\u2014 on the third day.Optimal sequence of actions in the second sample case: In the first day Anastasia collects 8 pebbles of the third type. In the second day she collects 8 pebbles of the fourth type. In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type. In the fourth day she collects 7 pebbles of the fifth type. In the fifth day she collects 1 pebble of the second type. "}, "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"}, {"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"}], "negative_code": [], "src_uid": "3992602be20a386f0ec57c51e14b39c5"} {"nl": {"description": "Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a \"type\" is in language X--: First, a type is a string \"int\". Second, a type is a string that starts with \"pair\", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either \"pair\" or \"int\" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words \"int\".", "output_spec": "If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print \"Error occurred\" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.", "sample_inputs": ["3\npair pair int int int", "1\npair int"], "sample_outputs": ["pair<pair<int,int>,int>", "Error occurred"], "notes": null}, "positive_code": [{"source_code": "object Solution {\n var tokens: List[String] = null;\n\n def nextToken(): String = {\n if (tokens.isEmpty) {\n throw new Exception(\"nope\")\n }\n val token = tokens.head\n tokens = tokens.tail\n token\n }\n\n def parse(buf: StringBuffer) {\n if (nextToken() == \"int\") {\n buf.append(\"int\")\n } else {\n buf.append(\"pair<\")\n parse(buf)\n buf.append(\",\")\n parse(buf)\n buf.append(\">\")\n }\n }\n\n def main(args: Array[String]) {\n val n = readInt()\n tokens = readLine().split(\" \").toList\n try {\n val buf = new StringBuffer()\n parse(buf)\n if (!tokens.isEmpty) {\n throw new Exception(\"nope\")\n }\n println(buf)\n } catch {\n case e => println(\"Error occurred\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "6587be85c64a0d5fb66eec0c5957cb62"} {"nl": {"description": "Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i$$$ ($$$1 \\le a_i \\le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\\lceil \\frac{n}{2} \\rceil$$$, where $$$\\lceil x \\rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\\lceil \\frac{n}{2} \\rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 1\\,000$$$) \u2014 the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ \u2014 the type of the favorite drink of the $$$i$$$-th student.", "output_spec": "Print exactly one integer \u2014 the maximum number of students that can get a favorite drink.", "sample_inputs": ["5 3\n1\n3\n1\n1\n2", "10 3\n2\n1\n3\n2\n3\n3\n1\n3\n1\n2"], "sample_outputs": ["4", "9"], "notes": "NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth)."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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}"}], "negative_code": [], "src_uid": "dceeb739a56bb799550138aa8c127996"} {"nl": {"description": "A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print \"NO\" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, \"ab\", \"c\", \"abc\" are substrings of string \"abc\", while \"ac\" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105.", "output_spec": "Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print \"NO\" (without quotes) if there are no good strings.", "sample_inputs": ["4\nmail\nai\nlru\ncf", "3\nkek\npreceq\ncheburek"], "sample_outputs": ["cfmailru", "NO"], "notes": "NoteOne can show that in the first sample only two good strings with minimum length exist: \"cfmailru\" and \"mailrucf\". The first string is lexicographically minimum."}, "positive_code": [{"source_code": "import 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 val Array(n) = readInts(1)\n\n val basis = ArrayBuffer.empty[String]\n\n //val basisByLetter = mutable.Map.empty[Char, Int]\n\n def overlap(a: String, b: String): Int = {\n var i = 0\n var res = 0\n while (i < a.length && i < b.length) {\n i += 1\n if (a.takeRight(i) == b.take(i)) res = i\n }\n res\n }\n\n var can = true\n var i = 0\n while (can && i < n) {\n i += 1\n\n val s = readLine\n val sDist = s.distinct\n if (s.length > sDist.length) can = false\n else {\n\n val empty = basis.indexOf(\"\")\n\n var updated = if (empty == -1) {\n basis += s\n basis.size - 1\n } else {\n basis(empty) = s\n empty\n }\n\n var canMerge = true\n var step = 0\n while (canMerge) {\n\n canMerge = false\n\n var basisIdx = 0\n\n while (basisIdx < basis.size && !canMerge) {\n //println(step, basis.mkString(\" \"), updated, basisIdx, can, canMerge)\n if (basis(basisIdx).nonEmpty && basisIdx != updated) {\n val basisS = basis(basisIdx)\n val otherS = basis(updated)\n\n //println(\"A\", basisS, otherS, overlap(basisS, otherS))\n //println(\"B\", otherS, basisS, overlap(otherS, basisS))\n\n if (basisS.indexOfSlice(otherS) >= 0) {\n basis(updated) = \"\"\n } else if (otherS.indexOfSlice(basisS) >= 0) {\n basis(basisIdx) = otherS\n basis(updated) = \"\"\n updated = basisIdx\n canMerge = true\n } else if (overlap(basisS, otherS) > 0) {\n val prefLen = overlap(basisS, otherS)\n val s2 = basisS + otherS.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n basis(basisIdx) = s2\n basis(updated) = \"\"\n updated = basisIdx\n canMerge = true\n }\n } else if (overlap(otherS, basisS) > 0) {\n val prefLen = overlap(otherS, basisS)\n val s2 = otherS + basisS.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n basis(basisIdx) = s2\n basis(updated) = \"\"\n updated = basisIdx\n canMerge = true\n }\n } else if (otherS.exists(c => basisS.contains(c))) can = false\n }\n\n basisIdx += 1\n }\n step += 1\n }\n\n }\n\n }\n\n if (can) {\n val res = basis.sorted.mkString\n if (res.length == res.distinct.length) println(res)\n else println(\"NO\")\n } else println(\"NO\")\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\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 val Array(n) = readInts(1)\n\n val basis = ArrayBuffer.empty[String]\n\n val basisByLetter = mutable.Map.empty[Char, Int]\n\n def overlap(a: String, b: String): Int = {\n var i = 0\n while (i < a.length && i < b.length && a.takeRight(i + 1) == b.take(i + 1)) i += 1\n i\n }\n\n var can = true\n var i = 0\n while (can && i < n) {\n i += 1\n\n val s = readLine\n val sDist = s.distinct\n if (s.length > sDist.length) can = false\n else {\n\n val cPos = s.indexWhere(basisByLetter.contains)\n\n if (cPos == -1) {\n s.foreach(c => basisByLetter(c) = basis.size)\n basis += s\n } else {\n val basisIdx = basisByLetter(s(cPos))\n val basisS = basis(basisIdx)\n if (basisS.indexOfSlice(s) >= 0) {\n // ok\n } else if (s.indexOfSlice(basisS) >= 0) {\n s.foreach(c => basisByLetter(c) = basisIdx)\n basis(basisIdx) = s\n } else if (overlap(basisS, s) > 0) {\n val prefLen = overlap(basisS, s)\n val s2 = basisS + s.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n s2.foreach(c => basisByLetter(c) = basisIdx)\n basis(basisIdx) = s2\n }\n } else if (overlap(s, basisS) > 0) {\n val prefLen = overlap(s, basisS)\n val s2 = s + basisS.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n s2.foreach(c => basisByLetter(c) = basisIdx)\n basis(basisIdx) = s2\n }\n } else can = false\n\n }\n\n }\n\n }\n\n if (can) println(basis.sorted.mkString)\n else println(\"NO\")\n}\n"}, {"source_code": "import 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 val Array(n) = readInts(1)\n\n val basis = ArrayBuffer.empty[String]\n\n //val basisByLetter = mutable.Map.empty[Char, Int]\n\n def overlap(a: String, b: String): Int = {\n var i = 0\n while (i < a.length && i < b.length && a.takeRight(i + 1) == b.take(i + 1)) i += 1\n i\n }\n\n var can = true\n var i = 0\n while (can && i < n) {\n i += 1\n\n val s = readLine\n val sDist = s.distinct\n if (s.length > sDist.length) can = false\n else {\n\n val empty = basis.indexOf(\"\")\n\n var updated = if (empty == -1) {\n basis += s\n basis.size - 1\n } else {\n basis(empty) = s\n empty\n }\n\n var canMerge = true\n var step = 0\n while (canMerge) {\n\n canMerge = false\n\n var basisIdx = 0\n\n while (basisIdx < basis.size && !canMerge) {\n //println(step, basis.mkString(\" \"), updated, basisIdx, can, canMerge)\n if (basis(basisIdx).nonEmpty && basisIdx != updated) {\n val basisS = basis(basisIdx)\n val otherS = basis(updated)\n\n if (basisS.indexOfSlice(otherS) >= 0) {\n basis(updated) = \"\"\n } else if (otherS.indexOfSlice(basisS) >= 0) {\n basis(basisIdx) = otherS\n basis(updated) = \"\"\n updated = basisIdx\n canMerge = true\n } else if (overlap(basisS, otherS) > 0) {\n val prefLen = overlap(basisS, otherS)\n val s2 = basisS + otherS.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n basis(basisIdx) = s2\n basis(updated) = \"\"\n updated = basisIdx\n canMerge = true\n }\n } else if (overlap(otherS, basisS) > 0) {\n val prefLen = overlap(otherS, basisS)\n val s2 = otherS + basisS.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n basis(basisIdx) = s2\n basis(updated) = \"\"\n updated = basisIdx\n canMerge = true\n }\n } else if (otherS.exists(c => basisS.contains(c))) can = false\n }\n\n basisIdx += 1\n }\n step += 1\n }\n\n }\n\n }\n\n if (can) {\n val res = basis.sorted.mkString\n if (res.length == res.distinct.length) println(res)\n else println(\"NO\")\n } else println(\"NO\")\n}\n"}, {"source_code": "import scala.collection.mutable\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 val Array(n) = readInts(1)\n\n val basis = ArrayBuffer.empty[String]\n\n val basisByLetter = mutable.Map.empty[Char, Int]\n\n def overlap(a: String, b: String): Int = {\n var i = 0\n while (i < a.length && i < b.length && a.takeRight(i + 1) == b.take(i + 1)) i += 1\n i\n }\n\n var can = true\n var i = 0\n while (can && i < n) {\n i += 1\n\n val s = readLine\n val sDist = s.distinct\n if (s.length > sDist.length) can = false\n else {\n\n val cPos = s.indexWhere(basisByLetter.contains)\n\n if (cPos == -1) {\n s.foreach(c => basisByLetter(c) = basis.size)\n basis += s\n } else {\n val basisIdx = basisByLetter(s(cPos))\n val basisS = basis(basisIdx)\n if (basisS.indexOfSlice(s) >= 0) {\n // ok\n } else if (s.indexOfSlice(basisS) >= 0) {\n s.foreach(c => basisByLetter(c) = basisIdx)\n basis(basisIdx) = s\n } else if (overlap(basisS, s) > 0) {\n val prefLen = overlap(basisS, s)\n val s2 = basisS + s.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n s2.foreach(c => basisByLetter(c) = basisIdx)\n basis(basisIdx) = s2\n }\n } else if (overlap(s, basisS) >= 0) {\n val prefLen = overlap(s, basisS)\n val s2 = s + basisS.drop(prefLen)\n val s2Dist = s2.distinct\n if (s2.length > s2Dist.length) can = false\n else {\n s2.foreach(c => basisByLetter(c) = basisIdx)\n basis(basisIdx) = s2\n }\n } else {\n s.foreach(c => basisByLetter(c) = basis.size)\n basis += s\n }\n\n }\n\n }\n\n }\n\n if (can) println(basis.sorted.mkString)\n else println(\"NO\")\n}\n"}], "src_uid": "02fe37c2e31ca4e278d493fc2e3e35e0"} {"nl": {"description": "A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You are given a permutation of $$$1,2,\\dots,n$$$, $$$[a_1,a_2,\\dots,a_n]$$$. For integers $$$i$$$, $$$j$$$ such that $$$1\\le i<j\\le n$$$, define $$$\\operatorname{mn}(i,j)$$$ as $$$\\min\\limits_{k=i}^j a_k$$$, and define $$$\\operatorname{mx}(i,j)$$$ as $$$\\max\\limits_{k=i}^j a_k$$$.Let us build an undirected graph of $$$n$$$ vertices, numbered $$$1$$$ to $$$n$$$. For every pair of integers $$$1\\le i<j\\le n$$$, if $$$\\operatorname{mn}(i,j)=a_i$$$ and $$$\\operatorname{mx}(i,j)=a_j$$$ both holds, or $$$\\operatorname{mn}(i,j)=a_j$$$ and $$$\\operatorname{mx}(i,j)=a_i$$$ both holds, add an undirected edge of length $$$1$$$ between vertices $$$i$$$ and $$$j$$$.In this graph, find the length of the shortest path from vertex $$$1$$$ to vertex $$$n$$$. We can prove that $$$1$$$ and $$$n$$$ will always be connected via some path, so a shortest path always exists.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 5\\cdot 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1\\le n\\le 2.5\\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$1\\le a_i\\le n$$$). It's guaranteed that $$$a$$$ is a permutation of $$$1$$$, $$$2$$$, $$$\\dots$$$, $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5\\cdot 10^5$$$.", "output_spec": "For each test case, print a single line containing one integer \u2014 the length of the shortest path from $$$1$$$ to $$$n$$$.", "sample_inputs": ["5\n\n1\n\n1\n\n2\n\n1 2\n\n5\n\n1 4 2 3 5\n\n5\n\n2 1 5 3 4\n\n10\n\n7 4 8 1 6 10 3 5 2 9"], "sample_outputs": ["0\n1\n1\n4\n6"], "notes": "NoteThe following are illustrations of constructed graphs in example test cases. the constructed graph in test case 1 the constructed graph in test case 2 the constructed graph in test case 3 the constructed graph in test case 4 the constructed graph in test case 5 "}, "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\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 tokenizer = new StringTokenizer(input.readLine())\r\n val A = ListBuffer.empty[Int]\r\n for (j <- 1 to n) {\r\n A += tokenizer.nextToken.toInt\r\n }\r\n var B = A.toArray\r\n var now = 0\r\n var pos = 0\r\n var st = 0\r\n var con = 0\r\n var cou = 0\r\n var noc = 0\r\n if (n == 1) {\r\n println(0)\r\n }\r\n else {\r\n if (B(0) < B(1)) {\r\n pos = 0\r\n }\r\n else pos = 1\r\n while ((B(now) != n) && B(now) != 0) {\r\n if (st < n - 1) {\r\n st += 1\r\n if (B(st) > B(con)) {\r\n con = st\r\n if (pos == 1) {\r\n now = noc\r\n pos = 0\r\n cou += 1\r\n }\r\n }\r\n if (B(st) < B(noc)) {\r\n noc = st\r\n if (pos == 0) {\r\n now = con\r\n pos = 1\r\n cou += 1\r\n }\r\n }\r\n }\r\n else {\r\n if (pos == 0) {\r\n now = con\r\n pos = 1\r\n cou += 1\r\n noc = now\r\n st = now\r\n }\r\n else if (pos == 1) {\r\n now = noc\r\n pos = 0\r\n cou += 1\r\n con = now\r\n st = now\r\n }\r\n }\r\n }\r\n B = B.reverse\r\n now = 0\r\n pos = 0\r\n st = 0\r\n con = 0\r\n noc = 0\r\n if (B(0) < B(1)) {\r\n pos = 0\r\n }\r\n else pos = 1\r\n while ((B(now) != n) && B(now) != 0) {\r\n if (st < n - 1) {\r\n st += 1\r\n if (B(st) > B(con)) {\r\n con = st\r\n if (pos == 1) {\r\n now = noc\r\n pos = 0\r\n cou += 1\r\n }\r\n }\r\n if (B(st) < B(noc)) {\r\n noc = st\r\n if (pos == 0) {\r\n now = con\r\n pos = 1\r\n cou += 1\r\n }\r\n }\r\n }\r\n else {\r\n if (pos == 0) {\r\n now = con\r\n pos = 1\r\n cou += 1\r\n noc = now\r\n st = now\r\n }\r\n else if (pos == 1) {\r\n now = noc\r\n pos = 0\r\n cou += 1\r\n con = now\r\n st = now\r\n }\r\n }\r\n }\r\n output.println(cou)\r\n }\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "2592836c1457efda9ad333524abfdf56"} {"nl": {"description": "You are given a table $$$a$$$ of size $$$n \\times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \\cdot m + j$$$, that is $$$a_{ij} = (i - 1) \\cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path. For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (1, 3) \\rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 2) \\rightarrow (2, 1)$$$ and $$$(1, 1) \\rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \\rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \\rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u2014 the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^4$$$) \u2014 the number of rows and columns of the table $$$a$$$ respectively.", "output_spec": "For each test case output a single integer \u2014 a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.", "sample_inputs": ["7\n\n1 1\n\n2 3\n\n3 2\n\n7 1\n\n1 10\n\n5 5\n\n10000 10000"], "sample_outputs": ["1\n12\n13\n28\n55\n85\n500099995000"], "notes": "NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table. "}, "positive_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n for (i <- 1 to n){\r\n val x = readLine().split(\" \").map(_.toLong)\r\n val y = x(1) * (x(1)+1) / 2 + x(0) * ( x(0) - 1) * x(1) / 2 + (x(0) -1) * x(1)\r\n println(y)\r\n }\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "7d774a003d2e3e8ae6fe1912b3998c96"} {"nl": {"description": "You are given a tree (a connected undirected graph without cycles) of $$$n$$$ vertices. Each of the $$$n - 1$$$ edges of the tree is colored in either black or red.You are also given an integer $$$k$$$. Consider sequences of $$$k$$$ vertices. Let's call a sequence $$$[a_1, a_2, \\ldots, a_k]$$$ good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $$$a_1$$$ and ending at $$$a_k$$$. Start at $$$a_1$$$, then go to $$$a_2$$$ using the shortest path between $$$a_1$$$ and $$$a_2$$$, then go to $$$a_3$$$ in a similar way, and so on, until you travel the shortest path between $$$a_{k-1}$$$ and $$$a_k$$$. If you walked over at least one black edge during this process, then the sequence is good. Consider the tree on the picture. If $$$k=3$$$ then the following sequences are good: $$$[1, 4, 7]$$$, $$$[5, 5, 3]$$$ and $$$[2, 3, 7]$$$. The following sequences are not good: $$$[1, 4, 6]$$$, $$$[5, 5, 5]$$$, $$$[3, 7, 3]$$$.There are $$$n^k$$$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$2 \\le k \\le 100$$$), the size of the tree and the length of the vertex sequence. Each of the next $$$n - 1$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$ and $$$x_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$x_i \\in \\{0, 1\\}$$$), where $$$u_i$$$ and $$$v_i$$$ denote the endpoints of the corresponding edge and $$$x_i$$$ is the color of this edge ($$$0$$$ denotes red edge and $$$1$$$ denotes black edge).", "output_spec": "Print the number of good sequences modulo $$$10^9 + 7$$$.", "sample_inputs": ["4 4\n1 2 1\n2 3 1\n3 4 1", "4 6\n1 2 0\n1 3 0\n1 4 0", "3 5\n1 2 1\n2 3 0"], "sample_outputs": ["252", "0", "210"], "notes": "NoteIn the first example, all sequences ($$$4^4$$$) of length $$$4$$$ except the following are good: $$$[1, 1, 1, 1]$$$ $$$[2, 2, 2, 2]$$$ $$$[3, 3, 3, 3]$$$ $$$[4, 4, 4, 4]$$$ In the second example, all edges are red, hence there aren't any good sequences."}, "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 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"}, {"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"}, {"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\u3092\u8d85\u3048\u306a\u3044\u3060\u308d\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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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"}], "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"} {"nl": {"description": "Suppose you have a special $$$x$$$-$$$y$$$-counter. This counter can store some value as a decimal number; at first, the counter has value $$$0$$$. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $$$x$$$ or $$$y$$$ to its value. So all sequences this counter generates are starting from $$$0$$$. For example, a $$$4$$$-$$$2$$$-counter can act as follows: it prints $$$0$$$, and adds $$$4$$$ to its value, so the current value is $$$4$$$, and the output is $$$0$$$; it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$8$$$, and the output is $$$04$$$; it prints $$$8$$$, and adds $$$4$$$ to its value, so the current value is $$$12$$$, and the output is $$$048$$$; it prints $$$2$$$, and adds $$$2$$$ to its value, so the current value is $$$14$$$, and the output is $$$0482$$$; it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$18$$$, and the output is $$$04824$$$. This is only one of the possible outputs; for example, the same counter could generate $$$0246802468024$$$ as the output, if we chose to add $$$2$$$ during each step.You wrote down a printed sequence from one of such $$$x$$$-$$$y$$$-counters. But the sequence was corrupted and several elements from the sequence could be erased.Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $$$s$$$ \u2014 the remaining data of the sequence. For all $$$0 \\le x, y < 10$$$, calculate the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$x$$$-$$$y$$$-counter. Note that you can't change the order of digits in string $$$s$$$ or erase any of them; only insertions are allowed.", "input_spec": "The first line contains a single string $$$s$$$ ($$$1 \\le |s| \\le 2 \\cdot 10^6$$$, $$$s_i \\in \\{\\text{0} - \\text{9}\\}$$$) \u2014 the remaining data you have. It's guaranteed that $$$s_1 = 0$$$.", "output_spec": "Print a $$$10 \\times 10$$$ matrix, where the $$$j$$$-th integer ($$$0$$$-indexed) on the $$$i$$$-th line ($$$0$$$-indexed too) is equal to the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$i$$$-$$$j$$$-counter, or $$$-1$$$ if there is no way to do so.", "sample_inputs": ["0840"], "sample_outputs": ["-1 17 7 7 7 -1 2 17 2 7 \n17 17 7 5 5 5 2 7 2 7 \n7 7 7 4 3 7 1 7 2 5 \n7 5 4 7 3 3 2 5 2 3 \n7 5 3 3 7 7 1 7 2 7 \n-1 5 7 3 7 -1 2 9 2 7 \n2 2 1 2 1 2 2 2 0 1 \n17 7 7 5 7 9 2 17 2 3 \n2 2 2 2 2 2 0 2 2 2 \n7 7 5 3 7 7 1 3 2 7"], "notes": "NoteLet's take, for example, $$$4$$$-$$$3$$$-counter. One of the possible outcomes the counter could print is $$$0(4)8(1)4(7)0$$$ (lost elements are in the brackets).One of the possible outcomes a $$$2$$$-$$$3$$$-counter could print is $$$0(35)8(1)4(7)0$$$.The $$$6$$$-$$$8$$$-counter could print exactly the string $$$0840$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val A = ns().map(_ - '0')\n val C = Array.ofDim[Int](A.length - 1)\n REP(A.length - 1) { i =>\n C(i) = (10 + A(i + 1) - A(i)) % 10\n }\n debug(C)\n\n val INF = 1e9.toInt\n // x, y\u3069\u3061\u3089\u304b\u304c\uff11\u56de\u4ee5\u4e0a\u3064\u304b\u308f\u308c\u3066\u3044\u308b\n def makeTrans(x: Int, y: Int): Array[Int] = {\n val dp = Array.fill[Int](10)(INF)\n REP(10) { i =>\n REP(10) { j =>\n val m = (i * x + j * y) % 10\n if (i + j > 0) dp(m) = min(dp(m), i + j)\n }\n }\n dp\n }\n\n val ans = Array.fill[Int](10, 10)(-1)\n REP(10) { x =>\n TO(x, 9) { y =>\n val t = makeTrans(x, y)\n debug(s\"x:$x y:$y\")\n debug(t)\n var cnt = 0\n var ok = true\n REP(C.length) { i =>\n val v = t(C(i))\n// debug(s\"x:$x y:$y i:$i v:$v\")\n ok &&= v != INF\n cnt += max(0, v - 1)\n }\n if (ok) {\n// debug(s\"x:$x y:$y cnt:$cnt\")\n ans(x)(y) = cnt\n ans(y)(x) = cnt\n }\n }\n }\n\n REP(10) { i =>\n out.println(ans(i).mkString(\" \"))\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val A = ns().map(_ - '0')\n val C = Array.ofDim[Int](A.length - 1)\n REP(A.length - 1) { i =>\n C(i) = (10 + A(i + 1) - A(i)) % 10\n }\n\n val INF = 1e9.toInt\n def makeTrans(x: Int, y: Int): Array[Int] = {\n val dp = Array.fill[Int](10)(INF)\n dp(0) = 0\n REP(10) { i =>\n REP(10) { j =>\n val m = (i * x + j * y) % 10\n dp(m) = min(dp(m), i + j)\n }\n }\n dp\n }\n\n val ans = Array.fill[Int](10, 10)(-1)\n REP(10) { x =>\n TO(x, 9) { j =>\n val t = makeTrans(x, j)\n debug(s\"x:$x y:$j\")\n debug(t)\n var cnt = 0\n var ok = true\n REP(C.length) { k =>\n val v = t(C(k))\n ok &&= v != INF\n cnt += max(0, v - 1)\n }\n if (ok) {\n ans(x)(j) = cnt\n ans(j)(x) = cnt\n }\n }\n }\n\n REP(10) { i =>\n out.println(ans(i).mkString(\" \"))\n }\n }\n}"}], "src_uid": "2ebfcb54231d115a4aa9e5fc52b4ebe7"} {"nl": {"description": "You are given an array $$$s$$$ consisting of $$$n$$$ integers.You have to find any array $$$t$$$ of length $$$k$$$ such that you can cut out maximum number of copies of array $$$t$$$ from array $$$s$$$.Cutting out the copy of $$$t$$$ means that for each element $$$t_i$$$ of array $$$t$$$ you have to find $$$t_i$$$ in $$$s$$$ and remove it from $$$s$$$. If for some $$$t_i$$$ you cannot find such element in $$$s$$$, then you cannot cut out one more copy of $$$t$$$. The both arrays can contain duplicate elements.For example, if $$$s = [1, 2, 3, 2, 4, 3, 1]$$$ and $$$k = 3$$$ then one of the possible answers is $$$t = [1, 2, 3]$$$. This array $$$t$$$ can be cut out $$$2$$$ times. To cut out the first copy of $$$t$$$ you can use the elements $$$[1, \\underline{\\textbf{2}}, 3, 2, 4, \\underline{\\textbf{3}}, \\underline{\\textbf{1}}]$$$ (use the highlighted elements). After cutting out the first copy of $$$t$$$ the array $$$s$$$ can look like $$$[1, 3, 2, 4]$$$. To cut out the second copy of $$$t$$$ you can use the elements $$$[\\underline{\\textbf{1}}, \\underline{\\textbf{3}}, \\underline{\\textbf{2}}, 4]$$$. After cutting out the second copy of $$$t$$$ the array $$$s$$$ will be $$$[4]$$$. Your task is to find such array $$$t$$$ that you can cut out the copy of $$$t$$$ from $$$s$$$ maximum number of times. If there are multiple answers, you may choose any of them.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$s$$$ and the desired number of elements in $$$t$$$, respectively. The second line of the input contains exactly $$$n$$$ integers $$$s_1, s_2, \\dots, s_n$$$ ($$$1 \\le s_i \\le 2 \\cdot 10^5$$$).", "output_spec": "Print $$$k$$$ integers \u2014 the elements of array $$$t$$$ such that you can cut out maximum possible number of copies of this array from $$$s$$$. If there are multiple answers, print any of them. The required array $$$t$$$ can contain duplicate elements. All the elements of $$$t$$$ ($$$t_1, t_2, \\dots, t_k$$$) should satisfy the following condition: $$$1 \\le t_i \\le 2 \\cdot 10^5$$$.", "sample_inputs": ["7 3\n1 2 3 2 4 3 1", "10 4\n1 3 1 3 10 3 7 7 12 3", "15 2\n1 2 1 1 1 2 1 1 2 1 2 1 1 1 1"], "sample_outputs": ["1 2 3", "7 3 1 3", "1 1"], "notes": "NoteThe first example is described in the problem statement.In the second example the only answer is $$$[7, 3, 1, 3]$$$ and any its permutations. It can be shown that you cannot choose any other array such that the maximum number of copies you can cut out would be equal to $$$2$$$.In the third example the array $$$t$$$ can be cut out $$$5$$$ times."}, "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 = 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\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\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}"}, {"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"}], "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"} {"nl": {"description": "Mr. F has $$$n$$$ positive integers, $$$a_1, a_2, \\ldots, a_n$$$.He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.", "input_spec": "The first line contains an integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$) \u2014 the number of integers Mr. F has. The second line contains $$$n$$$ integers, $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 1.5 \\cdot 10^7$$$).", "output_spec": "Print an integer\u00a0\u2014 the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. You should not remove all of the integers. If there is no solution, print \u00ab-1\u00bb (without quotes).", "sample_inputs": ["3\n1 2 4", "4\n6 9 15 30", "3\n1 1 1"], "sample_outputs": ["1", "2", "-1"], "notes": "NoteIn the first example, the greatest common divisor is $$$1$$$ in the beginning. You can remove $$$1$$$ so that the greatest common divisor is enlarged to $$$2$$$. The answer is $$$1$$$.In the second example, the greatest common divisor is $$$3$$$ in the beginning. You can remove $$$6$$$ and $$$9$$$ so that the greatest common divisor is enlarged to $$$15$$$. There is no solution which removes only one integer. So the answer is $$$2$$$.In the third example, there is no solution to enlarge the greatest common divisor. So the answer is $$$-1$$$."}, "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 g = gcd(A)\n rep(N) { i =>\n A(i) /= g\n }\n\n val NN = (1e7 + 5e6).toInt\n val prime = Array.ofDim[Int](1e6.toInt)\n val factor = Array.ofDim[Int](NN + 1)\n val C = Array.ofDim[Int](NN + 1)\n var pp = 0\n\n 2 to NN foreach { i =>\n if (factor(i) == 0) {\n factor(i) = i\n prime(pp) = i\n pp += 1\n }\n\n def fill(p: Int): Unit = {\n if (p < pp && prime(p) * i <= NN) {\n factor(prime(p) * i) = prime(p)\n if (prime(p) != i)\n fill(p + 1)\n }\n }\n\n fill(0)\n }\n\n var mx = 0\n def incrFactor(x: Int, pre: Int): Unit = {\n if (x > 1) {\n val f = factor(x)\n if (f != pre) {\n C(f) += 1\n mx = max(mx, C(f))\n }\n incrFactor(x / f, f)\n }\n }\n\n A foreach { a =>\n incrFactor(a, -1)\n }\n\n val ans = if (mx == 0) -1 else N - mx\n out.println(ans)\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 gcd(as: Array[Int]): Int = {\n var res = as(0)\n rep(as.length - 1, 1) { i =>\n res = gcd(res, as(i))\n }\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): 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"}], "negative_code": [], "src_uid": "9115965ff3421230eac37b22328c6153"} {"nl": {"description": "Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.", "input_spec": "The first line contains the integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain test cases\u00a0\u2014 one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$t$$$ answers\u00a0\u2014 one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).", "sample_inputs": ["5\n10\n0001111111\n4\n0101\n8\n11001101\n10\n1110000000\n1\n1"], "sample_outputs": ["0001111111\n001\n01\n0\n1"], "notes": "NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101\u00a0$$$\\rightarrow$$$ 1100101\u00a0$$$\\rightarrow$$$ 110101\u00a0$$$\\rightarrow$$$ 10101\u00a0$$$\\rightarrow$$$ 1101\u00a0$$$\\rightarrow$$$ 101\u00a0$$$\\rightarrow$$$ 01."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "bb071f1f4fc1c129a32064c1301f4942"} {"nl": {"description": "Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098)\u2009=\u20094\u2009+\u20090\u2009+\u20099\u2009+\u20098\u2009=\u200921. Then the digital root of number n equals to: dr(n)\u2009=\u2009S(n), if S(n)\u2009<\u200910; dr(n)\u2009=\u2009dr(\u2009S(n)\u2009), if S(n)\u2009\u2265\u200910. For example, dr(4098)\u2009\u2009=\u2009\u2009dr(21)\u2009\u2009=\u2009\u20093.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)\u2009\u2009=\u2009\u2009S(\u2009S(\u2009S(\u2009S(n)\u2009)\u2009)\u2009) (n\u2009\u2264\u2009101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.", "input_spec": "The first line contains two integers k and d (1\u2009\u2264\u2009k\u2009\u2264\u20091000;\u20020\u2009\u2264\u2009d\u2009\u2264\u20099).", "output_spec": "In a single line print either any number that meets the requirements (without the leading zeroes) or \"No solution\" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.", "sample_inputs": ["4 4", "5 1", "1 0"], "sample_outputs": ["5881", "36172", "0"], "notes": "NoteFor the first test sample dr(5881)\u2009\u2009=\u2009\u2009dr(22)\u2009\u2009=\u2009\u20094.For the second test sample dr(36172)\u2009\u2009=\u2009\u2009dr(19)\u2009\u2009=\u2009\u2009dr(10)\u2009\u2009=\u2009\u20091."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a $$$n\\times m$$$ grid (rows are numbered from $$$1$$$ to $$$n$$$, and columns are numbered from $$$1$$$ to $$$m$$$). You have a chess piece, and it stands at some cell $$$(S_x,S_y)$$$ which is not on the border (i.e. $$$2 \\le S_x \\le n-1$$$ and $$$2 \\le S_y \\le m-1$$$).From the cell $$$(x,y)$$$, you can move your chess piece to $$$(x,y')$$$ ($$$1\\le y'\\le m, y' \\neq y$$$) or $$$(x',y)$$$ ($$$1\\le x'\\le n, x'\\neq x$$$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.", "input_spec": "The only line of the input contains four integers $$$n$$$, $$$m$$$, $$$S_x$$$ and $$$S_y$$$ ($$$3\\le n,m\\le 100$$$, $$$2 \\le S_x \\le n-1$$$, $$$2 \\le S_y \\le m-1$$$) \u2014 the number of rows, the number of columns, and the initial position of your chess piece, respectively.", "output_spec": "You should print $$$n\\cdot m$$$ lines. The $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\leq x_i \\leq n$$$, $$$1 \\leq y_i \\leq m$$$), denoting the $$$i$$$-th cell that you visited. You should print exactly $$$nm$$$ pairs $$$(x_i, y_i)$$$, they should cover all possible pairs $$$(x_i, y_i)$$$, such that $$$1 \\leq x_i \\leq n$$$, $$$1 \\leq y_i \\leq m$$$. We can show that under these constraints there always exists a solution. If there are multiple answers, print any.", "sample_inputs": ["3 3 2 2", "3 4 2 2"], "sample_outputs": ["2 2\n1 2\n1 3\n2 3\n3 3\n3 2\n3 1\n2 1\n1 1", "2 2\n2 1\n2 3\n2 4\n1 4\n3 4\n3 3\n3 2\n3 1\n1 1\n1 2\n1 3"], "notes": "NotePossible routes for two examples: "}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \\le a, b, c \\le 10^9$$$) for which $$$(a\\oplus b)+(b\\oplus c)+(a\\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \\oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \\oplus 4 = 6$$$ and $$$3 \\oplus 1=2$$$.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$). ", "output_spec": "For each test case, print any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \\le a, b, c \\le 10^9$$$) for which $$$(a\\oplus b)+(b\\oplus c)+(a\\oplus c)=n$$$. If no such integers exist, print $$$-1$$$.", "sample_inputs": ["5\n\n4\n\n1\n\n12\n\n2046\n\n194723326"], "sample_outputs": ["3 3 1\n-1\n2 4 6\n69 420 666\n12345678 87654321 100000000"], "notes": "NoteIn the first test case, $$$a=3$$$, $$$b=3$$$, $$$c=1$$$, so $$$(3 \\oplus 3)+(3 \\oplus 1) + (3 \\oplus 1)=0+2+2=4$$$.In the second test case, there are no solutions.In the third test case, $$$(2 \\oplus 4)+(4 \\oplus 6) + (2 \\oplus 6)=6+2+4=12$$$."}, "positive_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 (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"}, {"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"} {"nl": {"description": "Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!", "input_spec": "The first line of the input contains single integer n n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1\u2009\u2264\u2009mi,\u2009\u2009ci\u2009\u2264\u20096)\u00a0\u2014 values on dice upper face after Mishka's and Chris' throws in i-th round respectively.", "output_spec": "If Mishka is the winner of the game, print \"Mishka\" (without quotes) in the only line. If Chris is the winner of the game, print \"Chris\" (without quotes) in the only line. If the result of the game is draw, print \"Friendship is magic!^^\" (without quotes) in the only line.", "sample_inputs": ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"], "sample_outputs": ["Mishka", "Friendship is magic!^^", "Chris"], "notes": "NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris."}, "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 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}"}, {"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"} {"nl": {"description": "You are given some Tetris field consisting of $$$n$$$ columns. The initial height of the $$$i$$$-th column of the field is $$$a_i$$$ blocks. On top of these columns you can place only figures of size $$$2 \\times 1$$$ (i.e. the height of this figure is $$$2$$$ blocks and the width of this figure is $$$1$$$ block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one $$$a_i$$$ is greater than $$$0$$$: You place one figure $$$2 \\times 1$$$ (choose some $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with $$$a_i + 2$$$); then, while all $$$a_i$$$ are greater than zero, replace each $$$a_i$$$ with $$$a_i - 1$$$. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of columns in the Tetris field. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the initial height of the $$$i$$$-th column of the Tetris field.", "output_spec": "For each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.", "sample_inputs": ["4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes $$$[2, 0, 2]$$$. Then place the figure in the second column and after the second step of the process, the field becomes $$$[0, 0, 0]$$$.And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes $$$[0, 2]$$$. Then place the figure in the first column and after the second step of the process, the field becomes $$$[0, 0]$$$.In the fourth test case of the example, place the figure in the first column, then the field becomes $$$[102]$$$ after the first step of the process, and then the field becomes $$$[0]$$$ after the second step of the process."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "53a3313f5d6ce19413d72473717054fc"} {"nl": {"description": "There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.", "input_spec": "The first line contains a single integer \u2014 n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105). Each of the next n lines contains an integer si \u2014 the size of the i-th kangaroo (1\u2009\u2264\u2009si\u2009\u2264\u2009105).", "output_spec": "Output a single integer \u2014 the optimal number of visible kangaroos.", "sample_inputs": ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"], "sample_outputs": ["5", "5"], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "361f65484d86051fa9ff013f5e8c9154"} {"nl": {"description": "The Berland language consists of words having exactly two letters. Moreover, the first letter of a word is different from the second letter. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.The Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $$$a$$$ comes earlier than word $$$b$$$ in the dictionary if one of the following conditions hold: the first letter of $$$a$$$ is less than the first letter of $$$b$$$; the first letters of $$$a$$$ and $$$b$$$ are the same, and the second letter of $$$a$$$ is less than the second letter of $$$b$$$. So, the dictionary looks like that: Word $$$1$$$: ab Word $$$2$$$: ac ... Word $$$25$$$: az Word $$$26$$$: ba Word $$$27$$$: bc ... Word $$$649$$$: zx Word $$$650$$$: zy You are given a word $$$s$$$ from the Berland language. Your task is to find its index in the dictionary.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 650$$$)\u00a0\u2014 the number of test cases. Each test case consists of one line containing $$$s$$$\u00a0\u2014 a string consisting of exactly two different lowercase Latin letters (i.\u2009e. a correct word of the Berland language).", "output_spec": "For each test case, print one integer\u00a0\u2014 the index of the word $$$s$$$ in the dictionary.", "sample_inputs": ["7\n\nab\n\nac\n\naz\n\nba\n\nbc\n\nzx\n\nzy"], "sample_outputs": ["1\n2\n25\n26\n27\n649\n650"], "notes": null}, "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(x: String) = {\r\n val f = x(0)\r\n val s = x(1)\r\n val a = 'a'\r\n if (f < s) (f - a) * 25 + s - a\r\n else (f - a) * 25 + s - a + 1\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 s = readLine()\r\n ) println(solve(s))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "2e3006d663a3c7ad3781aba1e37be3ca"} {"nl": {"description": "Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1,\u2009x2,\u2009...,\u2009xn. Vasya starts at the point with coordinate a. His goal is to visit at least n\u2009-\u20091 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.", "input_spec": "The first line of the input contains two integers n and a (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, \u2009-\u20091\u2009000\u2009000\u2009\u2264\u2009a\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the number of checkpoints and Vasya's starting position respectively. The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (\u2009-\u20091\u2009000\u2009000\u2009\u2264\u2009xi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 coordinates of the checkpoints.", "output_spec": "Print one integer\u00a0\u2014 the minimum distance Vasya has to travel in order to visit at least n\u2009-\u20091 checkpoint.", "sample_inputs": ["3 10\n1 7 12", "2 0\n11 -10", "5 0\n0 0 1000 0 0"], "sample_outputs": ["7", "10", "0"], "notes": "NoteIn the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12\u2009-\u200910\u2009=\u20092) and then proceed to the second one (distance is 12\u2009-\u20097\u2009=\u20095). The total distance is equal to 2\u2009+\u20095\u2009=\u20097.In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point \u2009-\u200910."}, "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, a) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt).sorted\n println(List(line.drop(1), line.dropRight(1)).filter(_.length > 0).map{ i =>\n i.last - i.head + Math.min(Math.abs(a - i.head), Math.abs(a - i.last))\n }.sorted.headOption.getOrElse(0))\n}\n"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, a) = in.next().split(' ').map(_.toInt)\n val line = in.next().split(' ').map(_.toInt).sorted\n println(List(line.drop(1), line.dropRight(1)).filter(_.length > 1).map{ i =>\n i.last - i.head + Math.min(Math.abs(a - i.head), Math.abs(a - i.last))\n }.sorted.headOption.getOrElse(0))\n}\n"}], "src_uid": "7807c484035e0327870b6cac23c8d60a"} {"nl": {"description": "You are given an array $$$a$$$ of $$$2n$$$ distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $$$2$$$ neighbours.More formally, find an array $$$b$$$, such that: $$$b$$$ is a permutation of $$$a$$$.For every $$$i$$$ from $$$1$$$ to $$$2n$$$, $$$b_i \\neq \\frac{b_{i-1}+b_{i+1}}{2}$$$, where $$$b_0 = b_{2n}$$$ and $$$b_{2n+1} = b_1$$$. It can be proved that under the constraints of this problem, such array $$$b$$$ always exists.", "input_spec": "The first line of input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$ \u2014 the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(1 \\leq n \\leq 25)$$$. The second line of each testcase contains $$$2n$$$ integers $$$a_1, a_2, \\ldots, a_{2n}$$$ $$$(1 \\leq a_i \\leq 10^9)$$$ \u2014 elements of the array. Note that there is no limit to the sum of $$$n$$$ over all testcases.", "output_spec": "For each testcase, you should output $$$2n$$$ integers, $$$b_1, b_2, \\ldots b_{2n}$$$, for which the conditions from the statement are satisfied.", "sample_inputs": ["3\n3\n1 2 3 4 5 6\n2\n123 456 789 10\n1\n6 9"], "sample_outputs": ["3 1 4 2 5 6\n123 10 456 789\n9 6"], "notes": "NoteIn the first testcase, array $$$[3, 1, 4, 2, 5, 6]$$$ works, as it's a permutation of $$$[1, 2, 3, 4, 5, 6]$$$, and $$$\\frac{3+4}{2}\\neq 1$$$, $$$\\frac{1+2}{2}\\neq 4$$$, $$$\\frac{4+5}{2}\\neq 2$$$, $$$\\frac{2+6}{2}\\neq 5$$$, $$$\\frac{5+3}{2}\\neq 6$$$, $$$\\frac{6+1}{2}\\neq 3$$$."}, "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 a2n = readLine().split(\" \").map(_.toInt).sorted\r\n val b2n = (0 until (2 * n)).map {\r\n case i if i % 2 == 0 => a2n(i / 2)\r\n case i => a2n(n + (i - 1) / 2)\r\n }\r\n\r\n println(b2n.mkString(\" \"))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "4296da660a39a6e98b41387929701c0a"} {"nl": {"description": "You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.", "input_spec": "The first line contains integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \\le r, g, b \\le 10^8$$$) \u2014 the number of red, green and blue candies, respectively.", "output_spec": "Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.", "sample_inputs": ["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"], "sample_outputs": ["1\n2\n2\n10\n5\n9"], "notes": "NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten."}, "positive_code": [{"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 xs = nextInts(3)\n val max = xs.max\n val min = xs.min\n val s = xs.sum\n val mid = s - max - min\n var h1, h2 = 0\n if (min >= max - mid) {\n h1 = max - mid + (min - (max - mid)) / 2\n h2 = min - h1\n } else {\n h1 = Math.min(min, Math.max((min + 1) / 2, max - mid))\n h2 = min - h1\n }\n val res = min + Math.min(max - h1, mid - h2)\n out.println(res)\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": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val xs = nextInts(3)\n val max = xs.max\n val min = xs.min\n val s = xs.sum\n val mid = s - max - min\n val h1 = Math.min(min, Math.max((min + 1) / 2, max - mid))\n val h2 = min - h1\n val res = min + Math.min(max - h1, mid - h2)\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"}], "src_uid": "1f29461c42665523d0a4d56b13f7e480"} {"nl": {"description": "Gerald found a table consisting of n rows and m columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value \u2014 it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.", "input_spec": "The first line contains two space-separated integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000). The following n lines describe the table. The i-th of these lines lists the space-separated integers ai,\u20091,\u2009ai,\u20092,\u2009...,\u2009ai,\u2009m (0\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u2009109) \u2014 the m numbers standing in the i-th row of the table.", "output_spec": "Print the answer to the problem.", "sample_inputs": ["2 2\n1 2\n3 4", "3 3\n1 0 0\n0 1 1\n1 0 0"], "sample_outputs": ["1", "0"], "notes": "NoteIn the first test case Gerald cannot crop the table \u2014 table contains only two rows and only two columns.In the second test case if we'll crop the table, the table will contain zero in some corner cell. Also initially it contains two zeros in the corner cells, so the answer is 0."}, "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 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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "This is the easy version of the problem. The only difference between the two versions is the constraint on $$$n$$$. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $$$1$$$ to $$$n$$$, and they would like to add edges to their forests such that: After adding edges, both of their graphs are still forests. They add the same edges. That is, if an edge $$$(u, v)$$$ is added to Mocha's forest, then an edge $$$(u, v)$$$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.", "input_spec": "The first line contains three integers $$$n$$$, $$$m_1$$$ and $$$m_2$$$ ($$$1 \\le n \\le 1000$$$, $$$0 \\le m_1, m_2 < n$$$) \u2014 the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next $$$m_1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) \u2014 the edges in Mocha's forest. Each of the next $$$m_2$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) \u2014 the edges in Diana's forest.", "output_spec": "The first line contains only one integer $$$h$$$, the maximum number of edges Mocha and Diana can add (in each forest). Each of the next $$$h$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) \u2014 the edge you add each time. If there are multiple correct answers, you can print any one of them.", "sample_inputs": ["3 2 2\n1 2\n2 3\n1 2\n1 3", "5 3 2\n5 4\n2 1\n4 3\n4 3\n1 4", "8 1 2\n1 7\n2 6\n1 5"], "sample_outputs": ["0", "1\n2 4", "5\n5 2\n2 3\n3 4\n4 7\n6 8"], "notes": "NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge $$$(2, 4)$$$."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "e3d2b67a62ac431718071ae20f3794aa"} {"nl": {"description": "You are given a binary string $$$s$$$ of length $$$n$$$.Let's define $$$d_i$$$ as the number whose decimal representation is $$$s_i s_{i+1}$$$ (possibly, with a leading zero). We define $$$f(s)$$$ to be the sum of all the valid $$$d_i$$$. In other words, $$$f(s) = \\sum\\limits_{i=1}^{n-1} d_i$$$.For example, for the string $$$s = 1011$$$: $$$d_1 = 10$$$ (ten); $$$d_2 = 01$$$ (one) $$$d_3 = 11$$$ (eleven); $$$f(s) = 10 + 01 + 11 = 22$$$. In one operation you can swap any two adjacent elements of the string. Find the minimum value of $$$f(s)$$$ that can be achieved if at most $$$k$$$ operations are allowed.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^5$$$). Description of the test cases follows. First line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$0 \\le k \\le 10^9$$$)\u00a0\u2014 the length of the string and the maximum number of operations allowed. The second line of each test case contains the binary string $$$s$$$ of length $$$n$$$, consisting of only zeros and ones. It is also given that sum of $$$n$$$ over all the test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print the minimum value of $$$f(s)$$$ you can obtain with at most $$$k$$$ operations.", "sample_inputs": ["3\n\n4 0\n\n1010\n\n7 1\n\n0010100\n\n5 2\n\n00110"], "sample_outputs": ["21\n22\n12"], "notes": "Note For the first example, you can't do any operation so the optimal string is $$$s$$$ itself. $$$f(s) = f(1010) = 10 + 01 + 10 = 21$$$. For the second example, one of the optimal strings you can obtain is \"0011000\". The string has an $$$f$$$ value of $$$22$$$. For the third example, one of the optimal strings you can obtain is \"00011\". The string has an $$$f$$$ value of $$$12$$$. "}, "positive_code": [{"source_code": "\r\n\r\nimport scala.collection.mutable\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 Array(count, moves) = StdIn.readLine().split(\" \").map(_.toInt)\r\n val numbers = StdIn.readLine().split(\"\").map(_.toInt)\r\n\r\n if(!numbers.contains(1)) {\r\n println(0)\r\n } else {\r\n val lastOne = numbers.lastIndexOf(1)\r\n val firstOne = numbers.indexOf(1)\r\n\r\n var score = 0\r\n for(i <- numbers.indices.drop(1)) {\r\n score += numbers(i - 1) * 10 + numbers(i)\r\n }\r\n\r\n val modifier = if(moves >= (count - (lastOne + 1)) + firstOne && firstOne != lastOne && firstOne != 0 && lastOne != count - 1) {\r\n -11\r\n } else if(moves >= (count - (lastOne + 1)) && lastOne != count - 1) {\r\n if(lastOne == 0) {\r\n -9\r\n } else {\r\n -10\r\n }\r\n } else if(moves >= firstOne && firstOne != 0 && firstOne != count - 1) {\r\n -1\r\n } else {\r\n 0\r\n }\r\n\r\n println(score + modifier)\r\n\r\n }\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import 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 Array(count, moves) = StdIn.readLine().split(\" \").map(_.toInt)\r\n val numbers = StdIn.readLine().split(\"\").map(_.toInt)\r\n\r\n if(!numbers.contains(1)) {\r\n println(0)\r\n } else {\r\n val lastOne = numbers.lastIndexOf(1)\r\n val firstOne = numbers.indexOf(1)\r\n\r\n var score = 0\r\n for(i <- numbers.indices.drop(1)) {\r\n score += numbers(i - 1) * 10 + numbers(i)\r\n }\r\n\r\n val modifier = if(moves >= (count - (lastOne + 1)) + firstOne && firstOne != lastOne && firstOne != 0 && lastOne != count - 1) {\r\n -11\r\n } else if(moves >= (count - (lastOne + 1)) && lastOne != count - 1) {\r\n -10\r\n } else if(moves >= firstOne && firstOne != 0 && firstOne != count - 1) {\r\n -1\r\n } else {\r\n 0\r\n }\r\n\r\n println(score + modifier)\r\n\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "\r\nimport scala.collection.mutable\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 Array(count, moves) = StdIn.readLine().split(\" \").map(_.toInt)\r\n val numbers = StdIn.readLine().split(\"\").map(_.toInt)\r\n\r\n if(!numbers.contains(1)) {\r\n println(0)\r\n } else {\r\n val lastOne = numbers.lastIndexOf(1)\r\n val firstOne = numbers.indexOf(1)\r\n\r\n var score = 0\r\n for(i <- numbers.indices.drop(1)) {\r\n score += numbers(i - 1) * 10 + numbers(i)\r\n }\r\n\r\n val modifier = if(moves >= (count - (lastOne + 1)) + firstOne && firstOne != lastOne && firstOne != 0 && lastOne != count - 1) {\r\n -11\r\n } else if(moves >= (count - (lastOne + 1)) && lastOne != count - 1) {\r\n -10\r\n } else if(moves >= firstOne && firstOne != 0) {\r\n -1\r\n } else {\r\n 0\r\n }\r\n\r\n println(score + modifier)\r\n\r\n }\r\n }\r\n }\r\n}\r\n"}], "src_uid": "ccecf97fcddbd0ab030d34b79a42cc6e"} {"nl": {"description": "Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order \u2014 their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$).", "input_spec": "The only line of the input contains four positive integers $$$x_1, x_2, x_3, x_4$$$ ($$$2 \\le x_i \\le 10^9$$$) \u2014 numbers written on a board in random order. It is guaranteed that the answer exists for the given number $$$x_1, x_2, x_3, x_4$$$.", "output_spec": "Print such positive integers $$$a$$$, $$$b$$$ and $$$c$$$ that four numbers written on a board are values $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$ written in some order. Print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.", "sample_inputs": ["3 6 5 4", "40 40 40 60", "201 101 101 200"], "sample_outputs": ["2 1 3", "20 20 20", "1 100 100"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "You are given array $$$a$$$ of length $$$n$$$. You can choose one segment $$$[l, r]$$$ ($$$1 \\le l \\le r \\le n$$$) and integer value $$$k$$$ (positive, negative or even zero) and change $$$a_l, a_{l + 1}, \\dots, a_r$$$ by $$$k$$$ each (i.e. $$$a_i := a_i + k$$$ for each $$$l \\le i \\le r$$$).What is the maximum possible number of elements with value $$$c$$$ that can be obtained after one such operation?", "input_spec": "The first line contains two integers $$$n$$$ and $$$c$$$ ($$$1 \\le n \\le 5 \\cdot 10^5$$$, $$$1 \\le c \\le 5 \\cdot 10^5$$$) \u2014 the length of array and the value $$$c$$$ to obtain. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 5 \\cdot 10^5$$$) \u2014 array $$$a$$$.", "output_spec": "Print one integer \u2014 the maximum possible number of elements with value $$$c$$$ which can be obtained after performing operation described above.", "sample_inputs": ["6 9\n9 9 9 9 9 9", "3 2\n6 2 6"], "sample_outputs": ["6", "2"], "notes": "NoteIn the first example we can choose any segment and $$$k = 0$$$. The array will stay same.In the second example we can choose segment $$$[1, 3]$$$ and $$$k = -4$$$. The array will become $$$[2, -2, 2]$$$."}, "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\n val M = 5e5.toInt + 1\n val cnt = Array.ofDim[Int](M)\n val P = Array.ofDim[Array[Int]](M) // \u6570\u5024\u6bce\u306e\u914d\u5217\n rep(N) { i =>\n val m = A(i)\n if (m != K) cnt(m) += 1\n }\n\n rep(M) { m =>\n P(m) = new Array(cnt(m))\n }\n\n rep_r(N) { i =>\n val m = A(i)\n if (m != K) {\n cnt(m) -= 1\n P(m)(cnt(m)) = i\n }\n }\n\n // K\u304c\u898b\u3064\u304b\u3063\u305f\u7d2f\u7a4d\u6570\n val cum = Array.ofDim[Int](N + 1)\n rep(N) { i =>\n cum(i + 1) = cum(i) + (if(A(i) == K) 1 else 0)\n }\n\n val S = cum(N)\n var ans = S\n rep(M) { m =>\n val p = P(m)\n val n = p.length\n if (n > 0) {\n var sum = 0\n var prev = 0\n var mx = 0\n var ms = 0\n rep(n) { i =>\n sum -= cum(p(i) + 1) - cum(prev)\n ms = min(ms, sum)\n sum += 1\n mx = max(mx, sum - ms) // \u3053\u308c\u307e\u3067\u306emin\u3068\u73fe\u5728\u5730\u306e\u5dee\u304c\u6700\u5927\u306b\u306a\u308b\u5834\u6240\u3092\u63a2\u3059\n prev = p(i)\n }\n // \u6700\u5f8c\u306b\u73fe\u308c\u308b\u4f4d\u7f6e\u3092\u8d85\u3048\u308b\u610f\u5473\u304c\u306a\u3044\n\n ans = max(ans, S + mx)\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}"}], "negative_code": [], "src_uid": "4cda03e0a8a77f8ffb6672b7a3827907"} {"nl": {"description": "In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i\u2009<\u2009n\u2009-\u20091), you can reach the tiles number i\u2009+\u20091 or the tile number i\u2009+\u20092 from it (if you stand on the tile number n\u2009-\u20091, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai\u2009+\u20091 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 the boulevard's length in tiles. The second line contains n space-separated integers ai \u2014 the number of days after which the i-th tile gets destroyed (1\u2009\u2264\u2009ai\u2009\u2264\u2009103). ", "output_spec": "Print a single number \u2014 the sought number of days.", "sample_inputs": ["4\n10 3 5 10", "5\n10 2 8 3 5"], "sample_outputs": ["5", "5"], "notes": "NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1\u2009\u2192\u20093\u2009\u2192\u20094. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1\u2009\u2192\u20093\u2009\u2192\u20095 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted."}, "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}"}, {"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"}], "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"} {"nl": {"description": "New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below. He lifts all the books above book x. He pushes book x out of the stack. He puts down the lifted books without changing their order. After reading book x, he puts book x on the top of the stack. He decided to read books for m days. In the j-th (1\u2009\u2264\u2009j\u2009\u2264\u2009m) day, he will read the book that is numbered with integer bj (1\u2009\u2264\u2009bj\u2009\u2264\u2009n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?", "input_spec": "The first line contains two space-separated integers n (2\u2009\u2264\u2009n\u2009\u2264\u2009500) and m (1\u2009\u2264\u2009m\u2009\u2264\u20091000) \u2014 the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u2009100) \u2014 the weight of each book. The third line contains m space separated integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009n) \u2014 the order of books that he would read. Note that he can read the same book more than once.", "output_spec": "Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.", "sample_inputs": ["3 5\n1 2 3\n1 3 2 3 1"], "sample_outputs": ["12"], "notes": "NoteHere's a picture depicting the example. Each vertical column presents the stacked books. "}, "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 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"}, {"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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\\max\\limits_{i = 1}^{n} a_i - \\min\\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^5$$$) \u2014 elements of the array $$$a$$$.", "output_spec": "Print one integer \u2014 the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.", "sample_inputs": ["4\n1 3 3 7", "2\n1 100000"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly."}, "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\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}"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "2eb7234904b28b4793b7c482a2370092"} {"nl": {"description": "You are given an array $$$a_{1}, a_{2}, \\ldots, a_{n}$$$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \\leq l \\leq r \\leq n$$$) and delete integers $$$a_l, a_{l+1}, \\ldots, a_r$$$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 2000$$$)\u00a0\u2014 the number of elements in the given array. The next line contains $$$n$$$ spaced integers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$ ($$$1 \\le a_{i} \\le 10^{9}$$$)\u00a0\u2014 the elements of the array. ", "output_spec": "Print a single integer\u00a0\u2014 the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $$$0$$$.", "sample_inputs": ["3\n1 2 3", "4\n1 1 2 2", "5\n1 4 1 4 9"], "sample_outputs": ["0", "2", "2"], "notes": "NoteIn the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index $$$2$$$ to $$$3$$$.In the third example you can remove the subsegments from index $$$1$$$ to $$$2$$$, or from index $$$2$$$ to $$$3$$$, or from index $$$3$$$ to $$$4$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.", "input_spec": "The first line contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of groups. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20092), where ai is the number of people in group i.", "output_spec": "Print the maximum number of teams of three people the coach can form.", "sample_inputs": ["4\n1 1 2 1", "2\n2 2", "7\n2 2 2 1 1 1 1", "3\n1 1 1"], "sample_outputs": ["1", "0", "3", "1"], "notes": "NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way: The first group (of two people) and the seventh group (of one person), The second group (of two people) and the sixth group (of one person), The third group (of two people) and the fourth group (of one person). "}, "positive_code": [{"source_code": "\nobject P899A_SplittingInTeams extends App {\n import scala.io.StdIn\n\n StdIn.readLine()\n val (singles, pairs) = StdIn.readLine().split(\" \").map(_.toInt).foldLeft((0, 0)) {\n case ((s, p), num) =>\n if (num == 1)\n (s + 1, p)\n else\n (s, p + 1)\n }\n if (pairs > singles) {\n println(singles)\n } else {\n println(pairs + (singles - pairs) / 3)\n }\n}"}], "negative_code": [], "src_uid": "6c9cbe714f8f594654ebc59b6059b30a"} {"nl": {"description": "In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i\u2009+\u20091) if the type of this bumper is '>', or one position to the left (to i\u2009-\u20091) if the type of the bumper at position i is '<'. If there is no such position, in other words if i\u2009-\u20091\u2009<\u20091 or i\u2009+\u20091\u2009>\u2009n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.", "output_spec": "Print one integer\u00a0\u2014 the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.", "sample_inputs": ["4\n<<><", "5\n>>>>>", "4\n>><<"], "sample_outputs": ["2", "5", "0"], "notes": "NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field."}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k \\le \\min(2 \\cdot 10^5, \\frac{n \\cdot (n - 1)}{2}))$$$ \u2014 total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \\dots, r_n$$$ $$$(1 \\le r_i \\le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \\le x, y \\le n$$$, $$$x \\ne y)$$$ \u2014 pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.", "output_spec": "Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.", "sample_inputs": ["4 2\n10 4 10 15\n1 2\n4 3", "10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5"], "sample_outputs": ["0 0 1 2", "5 4 0 5 3 3 9 0 2 5"], "notes": "NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel."}, "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 minus = Array.ofDim[Int](N)\n REP(M) { _ =>\n val u, v = ni() - 1\n if (A(u) < A(v)) minus(v) += 1\n if (A(v) < A(u)) minus(u) += 1\n }\n val sorted = A.clone()\n sort(sorted)\n\n val ans = ArrayBuffer[Int]()\n REP(N) { i =>\n ans += max(0, lowerBound(sorted, A(i)) - minus(i))\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] \u306e 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.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[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": "4687176445ed1087864b081a181e1840"} {"nl": {"description": "This is the harder version of the problem. In this version, $$$1 \\le n, m \\le 2\\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \\le k \\le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \\dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \\dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \\le t \\le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t<c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \\le k \\le n$$$, $$$1 \\le pos_j \\le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ \u2014 it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) \u2014 the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \\le m \\le 2\\cdot10^5$$$) \u2014 the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \\le k \\le n$$$, $$$1 \\le pos_j \\le k_j$$$) \u2014 the requests.", "output_spec": "Print $$$m$$$ integers $$$r_1, r_2, \\dots, r_m$$$ ($$$1 \\le r_j \\le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.", "sample_inputs": ["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"], "sample_outputs": ["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"], "notes": "NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$. "}, "positive_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.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"}, {"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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\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 \u304cLong\u3068\u304b\u3058\u3083\u306a\u3044\u5834\u5408\u306f\u3053\u308c\u3089\u3092\u5b9f\u88c5\u3057\u306a\u3044\u3068\u4e0b\u306e\u5974\u3089\u304c\u4f7f\u3048\u306a\u3044\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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) // \u964d\u9806\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"} {"nl": {"description": "Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h\u2009\u00d7\u2009w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.", "input_spec": "The first line of the input contains three integers: h,\u2009w,\u2009n \u2014 the sides of the board and the number of black cells (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009n\u2009\u2264\u20092000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri,\u2009ci (1\u2009\u2264\u2009ri\u2009\u2264\u2009h,\u20091\u2009\u2264\u2009ci\u2009\u2264\u2009w) \u2014 the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.", "output_spec": "Print a single line \u2014 the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109\u2009+\u20097.", "sample_inputs": ["3 4 2\n2 2\n2 3", "100 100 3\n15 16\n16 15\n99 88"], "sample_outputs": ["2", "545732279"], "notes": null}, "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\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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi,\u2009yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi\u2009-\u2009xj|\u2009+\u2009|yi\u2009-\u2009yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i,\u2009j) (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.", "input_spec": "The first line of the input contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|,\u2009|yi|\u2009\u2264\u2009109). Some positions may coincide.", "output_spec": "Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.", "sample_inputs": ["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"], "sample_outputs": ["2", "11"], "notes": "NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1\u2009-\u20097|\u2009+\u2009|1\u2009-\u20095|\u2009=\u200910 for Doctor Manhattan and for Daniel. For pairs (1,\u20091), (1,\u20095) and (7,\u20095), (1,\u20095) Doctor Manhattan and Daniel will calculate the same distances."}, "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 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"}, {"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"} {"nl": {"description": "The string $$$s$$$ is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.As long as the string length is greater than $$$1$$$, the following operation can be performed on it: select any two adjacent letters in the string $$$s$$$ and delete them from the string. For example, from the string \"lemma\" in one operation, you can get any of the four strings: \"mma\", \"lma\", \"lea\" or \"lem\" In particular, in one operation, the length of the string reduces by $$$2$$$.Formally, let the string $$$s$$$ have the form $$$s=s_1s_2 \\dots s_n$$$ ($$$n>1$$$). During one operation, you choose an arbitrary index $$$i$$$ ($$$1 \\le i < n$$$) and replace $$$s=s_1s_2 \\dots s_{i-1}s_{i+2} \\dots s_n$$$.For the given string $$$s$$$ and the letter $$$c$$$, determine whether it is possible to make such a sequence of operations that in the end the equality $$$s=c$$$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $$$1$$$, which consists of the letter $$$c$$$?", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of input test cases. The descriptions of the $$$t$$$ cases follow. Each test case is represented by two lines: string $$$s$$$, which has an odd length from $$$1$$$ to $$$49$$$ inclusive and consists of lowercase letters of the Latin alphabet; is a string containing one letter $$$c$$$, where $$$c$$$ is a lowercase letter of the Latin alphabet. ", "output_spec": "For each test case in a separate line output: YES, if the string $$$s$$$ can be converted so that $$$s=c$$$ is true; NO otherwise. You can output YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["5\n\nabcde\n\nc\n\nabcde\n\nb\n\nx\n\ny\n\naaaaaaaaaaaaaaa\n\na\n\ncontest\n\nt"], "sample_outputs": ["YES\nNO\nNO\nYES\nYES"], "notes": "NoteIn the first test case, $$$s$$$=\"abcde\". You need to get $$$s$$$=\"c\". For the first operation, delete the first two letters, we get $$$s$$$=\"cde\". In the second operation, we delete the last two letters, so we get the expected value of $$$s$$$=\"c\".In the third test case, $$$s$$$=\"x\", it is required to get $$$s$$$=\"y\". Obviously, this cannot be done."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n def main(args: Array[String]): Unit = {\n\n def f(s: String, c: Char) = {\n if (s.foldLeft(List.empty[Int], 0)(\n (acc, elem) => if (elem == c) ((acc._2 :: acc._1), acc._2 + 1) else (acc._1, acc._2 + 1)\n )._1.exists(_ % 2 == 0)) \"YES\" else \"NO\"\n\n }\n\n val cases = readLine().toInt\n for (\n i <- 0 until cases;\n s = readLine;\n c = readLine().head\n ) println(f(s, c))\n //readLine.split(\"\\\\s+\")\n\n }\n}\n\n"}], "negative_code": [], "src_uid": "c569b47cf80dfa98a7105e246c3c1e01"} {"nl": {"description": "One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: By the pieces lay a large square wooden board. The board is divided into $$$n^2$$$ cells arranged into $$$n$$$ rows and $$$n$$$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 50$$$) \u2014 the size of the board. The following $$$n$$$ lines describe the board. The $$$i$$$-th line ($$$1 \\leq i \\leq n$$$) contains a single string of length $$$n$$$. Its $$$j$$$-th character ($$$1 \\leq j \\leq n$$$) is equal to \".\" if the cell in the $$$i$$$-th row and the $$$j$$$-th column is free; it is equal to \"#\" if it's occupied. You can assume that the board contains at least one free cell.", "output_spec": "Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n#.#\n...\n#.#", "4\n##.#\n#...\n####\n##.#", "5\n#.###\n....#\n#....\n###.#\n#####", "5\n#.###\n....#\n#....\n....#\n#..##"], "sample_outputs": ["YES", "NO", "YES", "NO"], "notes": "NoteThe following sketches show the example boards and their tilings if such tilings exist: "}, "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Ukulele extends App {\n val FREE = '.'\n val WALL = '#'\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n var matrix = Array.ofDim[Char](n, n)\n for (i <- 0 until n) {\n line = new Scanner(StdIn.readLine())\n var matrixString = line.next()\n for (j <- 0 until n) {\n matrix(i)(j) = matrixString(j)\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (matrix(i)(j) == FREE && j != 0 && j != n-1 && i < n-2 &&\n matrix(i+1)(j) == FREE && matrix(i+2)(j) == FREE &&\n matrix(i+1)(j-1) == FREE && matrix(i+1)(j+1) == FREE) {\n matrix(i)(j) = WALL\n matrix(i+1)(j) = WALL\n matrix(i+2)(j) = WALL\n matrix(i+1)(j-1) = WALL\n matrix(i+1)(j+1) = WALL\n }\n if (matrix(i)(j) == FREE) {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n println(\"YES\")\n}\n"}], "negative_code": [], "src_uid": "cc1feee94617c0cba1c528a0cb3952a8"} {"nl": {"description": "Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX\u00a0\u2014 beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1\u2009\u2014\u20092\u2009\u2014\u2009...\u2009\u2014\u2009n\u2009\u2014\u20091. Formally, for every 1\u2009\u2264\u2009i\u2009<\u2009n there is a road between i-th and i\u2009+\u20091-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1\u2009\u2264\u2009i\u2009\u2264\u2009n,\u2009\u2009i\u2009\u2260\u2009x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci\u00b7cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a\u2009<\u2009b), such that there is a road between a and b you are to find sum of products ca\u00b7cb. Will you help her?", "input_spec": "The first line of the input contains two integers n and k (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u200910\u2009000)\u00a0\u2014 beauty values of the cities. The third line of the input contains k distinct integers id1,\u2009id2,\u2009...,\u2009idk (1\u2009\u2264\u2009idi\u2009\u2264\u2009n)\u00a0\u2014 indices of capital cities. Indices are given in ascending order.", "output_spec": "Print the only integer\u00a0\u2014 summary price of passing each of the roads in XXX.", "sample_inputs": ["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"], "sample_outputs": ["17", "71"], "notes": "NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71."}, "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": "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"}, {"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"} {"nl": {"description": "PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.AlgoRace is a special league of car racing where different teams compete in a country of n cities. Cities are numbered 1 through n. Every two distinct cities in the country are connected with one bidirectional road. Each competing team should introduce one driver and a set of cars.The competition is held in r rounds. In i-th round, drivers will start at city si and finish at city ti. Drivers are allowed to change their cars at most ki times. Changing cars can take place in any city in no time. One car can be used multiple times in one round, but total number of changes should not exceed ki. Drivers can freely choose their path to destination.PMP has prepared m type of purpose-built cars. Beside for PMP\u2019s driving skills, depending on properties of the car and the road, a car traverses each road in each direction in different times. PMP Warriors wants to devise best strategies of choosing car and roads in each round to maximize the chance of winning the cup. For each round they want to find the minimum time required to finish it.", "input_spec": "The first line contains three space-separated integers n,\u2009m,\u2009r (2\u2009\u2264\u2009n\u2009\u2264\u200960,\u20091\u2009\u2264\u2009m\u2009\u2264\u200960,\u20091\u2009\u2264\u2009r\u2009\u2264\u2009105) \u2014 the number of cities, the number of different types of cars and the number of rounds in the competition, correspondingly. Next m sets of n\u2009\u00d7\u2009n matrices of integers between 0 to 106 (inclusive) will follow \u2014 describing the time one car requires to traverse different roads. The k-th integer in j-th line of the i-th set is the time that i-th car requires to traverse the road from j-th city to k-th city. These matrices are not necessarily symmetric, but their diagonal is always zero. Next r lines contain description of the rounds. The i-th of these lines contains space-separated integers si,\u2009ti,\u2009ki (1\u2009\u2264\u2009si,\u2009ti\u2009\u2264\u2009n,\u2009si\u2009\u2260\u2009ti,\u20090\u2009\u2264\u2009ki\u2009\u2264\u20091000) \u2014 the number of starting city, finishing city and the number of possible car changes in i-th round, correspondingly.", "output_spec": "For each round you should print the minimum required time to complete the round in a single line.", "sample_inputs": ["4 2 3\n0 1 5 6\n2 0 3 6\n1 3 0 1\n6 6 7 0\n0 3 5 6\n2 0 1 6\n1 3 0 2\n6 6 7 0\n1 4 2\n1 4 1\n1 4 3", "4 2 3\n0 7 3 3\n8 0 10 5\n1 1 0 4\n8 9 2 0\n0 3 3 9\n7 0 4 9\n3 8 0 4\n4 8 9 0\n2 3 3\n2 1 3\n1 2 2"], "sample_outputs": ["3\n4\n3", "4\n5\n3"], "notes": "NoteIn the first sample, in all rounds PMP goes from city #1 to city #2, then city #3 and finally city #4. But the sequences of types of the cars he uses are (1, 2, 1) in the first round and (1, 2, 2) in the second round. In the third round, although he can change his car three times, he uses the same strategy as the first round which only needs two car changes."}, "positive_code": [{"source_code": "import scala.math\n\nobject CF119Div1B {\n val INF = 1 << 28\n\n def main(args: Array[String]): Unit = {\n val (n, m, r) = readThreeInts()\n val costMatrices = Array.ofDim[Int](m, n, n) // Type, Start, End\n for (t <- 0 until m) {\n for (i <- 0 until n) {\n val lineValues = readIntArray()\n for (j <- 0 until n) {\n costMatrices(t)(i)(j) = lineValues(j)\n }\n }\n\n // FW\n for (p <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n costMatrices(t)(i)(j) = math.min(\n costMatrices(t)(i)(p) + costMatrices(t)(p)(j),\n costMatrices(t)(i)(j))\n }\n }\n }\n }\n\n // Construct SM\n val superMatrices = Array.ofDim[Int](n, n, n) // # Change, Start, End\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n superMatrices(k)(i)(j) = INF\n }\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n for (t <- 0 until m) {\n superMatrices(0)(i)(j) = math.min(costMatrices(t)(i)(j), superMatrices(0)(i)(j))\n }\n }\n }\n for (k <- 1 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n for (m <- 0 until n) {\n superMatrices(k)(i)(j) = math.min(\n superMatrices(k - 1)(i)(m) + superMatrices(0)(m)(j),\n superMatrices(k)(i)(j))\n }\n }\n }\n }\n\n// for (k <- 0 until n) {\n// for (i <- 0 until n) {\n// println(superMatrices(k)(i).toList)\n// }\n// println()\n// }\n\n for (i <- 0 until r) {\n val (sPlusOne, tPlusOne, k) = readThreeInts()\n val s = sPlusOne - 1\n val t = tPlusOne - 1\n println(superMatrices(math.min(k, n - 1))(s)(t))\n }\n }\n\n def readThreeInts(): (Int, Int, Int) = {\n val line = readLine()\n val words = line.split(\" \")\n return (words(0).toInt, words(1).toInt, words(2).toInt)\n }\n\n def readIntArray(): Array[Int] = {\n val line = readLine()\n val words = line.split(\" \")\n val n = words.length\n val values = new Array[Int](n)\n for (i <- 0 until n) {\n values(i) = words(i).toInt\n }\n values\n }\n}\n"}], "negative_code": [{"source_code": "import scala.math\n\nobject CF119Div1B {\n val INF = 1 << 28\n\n def main(args: Array[String]): Unit = {\n val (n, m, r) = readThreeInts()\n val costMatrices = Array.ofDim[Int](m, n, n) // Type, Start, End\n for (t <- 0 until m) {\n for (i <- 0 until n) {\n val lineValues = readIntArray()\n for (j <- 0 until n) {\n costMatrices(t)(i)(j) = lineValues(j)\n }\n }\n\n // FW\n for (p <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n costMatrices(t)(i)(j) = math.min(\n costMatrices(t)(i)(p) + costMatrices(t)(p)(j),\n costMatrices(t)(i)(j))\n }\n }\n }\n }\n\n // Construct SM\n val superMatrices = Array.ofDim[Int](n, n, n) // # Change, Start, End\n for (k <- 0 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n superMatrices(k)(i)(j) = INF\n }\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n for (t <- 0 until m) {\n superMatrices(0)(i)(j) = math.min(costMatrices(t)(i)(j), superMatrices(0)(i)(j))\n }\n }\n }\n for (k <- 1 until n) {\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n for (m <- 0 until n) {\n superMatrices(k)(i)(j) = math.min(\n superMatrices(k - 1)(i)(m) + superMatrices(0)(m)(j),\n superMatrices(k)(i)(j))\n }\n }\n }\n }\n\n// for (k <- 0 until n) {\n// for (i <- 0 until n) {\n// println(superMatrices(k)(i).toList)\n// }\n// println()\n// }\n\n for (i <- 0 until r) {\n val (sPlusOne, tPlusOne, k) = readThreeInts()\n val s = sPlusOne - 1\n val t = tPlusOne - 1\n println(superMatrices(math.max(k, n - 1))(s)(t))\n }\n }\n\n def readThreeInts(): (Int, Int, Int) = {\n val line = readLine()\n val words = line.split(\" \")\n return (words(0).toInt, words(1).toInt, words(2).toInt)\n }\n\n def readIntArray(): Array[Int] = {\n val line = readLine()\n val words = line.split(\" \")\n val n = words.length\n val values = new Array[Int](n)\n for (i <- 0 until n) {\n values(i) = words(i).toInt\n }\n values\n }\n}\n"}], "src_uid": "6d47da375461c228bc70b117887cba33"} {"nl": {"description": "A new cottage village called \u00abFlatville\u00bb is being built in Flatland. By now they have already built in \u00abFlatville\u00bb n square houses with the centres on the \u041ex-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in \u00abFlatville\u00bb. The customer wants his future house to be on the \u041ex-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in \u00abFlatville\u00bb. Would you help him find the amount of possible positions of the new house?", "input_spec": "The first line of the input data contains numbers n and t (1\u2009\u2264\u2009n,\u2009t\u2009\u2264\u20091000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi \u2014 x-coordinate of the centre of the i-th house, and ai \u2014 length of its side (\u2009-\u20091000\u2009\u2264\u2009xi\u2009\u2264\u20091000, 1\u2009\u2264\u2009ai\u2009\u2264\u20091000).", "output_spec": "Output the amount of possible positions of the new house.", "sample_inputs": ["2 2\n0 4\n6 2", "2 2\n0 4\n5 2", "2 3\n0 4\n5 2"], "sample_outputs": ["4", "3", "2"], "notes": "NoteIt is possible for the x-coordinate of the new house to have non-integer value."}, "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Houses extends App {\n\n var result = 0\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val t = s.nextInt() * 2\n val arr = Array.ofDim[Int](40000)\n (0 until n).foreach { _ =>\n val x = (s.nextInt() * 2) + 5000\n val a = s.nextInt() * 2\n ((x - a / 2) until x + (a / 2)).foreach { m =>\n arr(m) = 1\n }\n }\n var i = 0;\n while (arr(i) == 0) {\n i += 1\n }\n while (i < arr.length) {\n val start = i\n while (i < arr.length && arr(i) == 0) {\n i += 1\n }\n val end = i\n val dist = end - start\n if (t < dist) {\n result += 2\n } else if (t == dist) {\n result += 1\n }\n i += 1\n }\n\n //result += 2\n println(result)\n\n}\n"}], "negative_code": [], "src_uid": "c31fed523230af1f904218b2fe0d663d"} {"nl": {"description": "Recently in Divanovo, a huge river locks system was built. There are now $$$n$$$ locks, the $$$i$$$-th of them has the volume of $$$v_i$$$ liters, so that it can contain any amount of water between $$$0$$$ and $$$v_i$$$ liters. Each lock has a pipe attached to it. When the pipe is open, $$$1$$$ liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $$$i$$$ to the lock $$$i + 1$$$. If the lock $$$i + 1$$$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $$$5$$$ locks with two open pipes at locks $$$1$$$ and $$$3$$$. Because locks $$$1$$$, $$$3$$$, and $$$4$$$ are already filled, effectively the water goes to locks $$$2$$$ and $$$5$$$. Note that the volume of the $$$i$$$-th lock may be greater than the volume of the $$$i + 1$$$-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $$$q$$$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $$$j$$$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $$$t_j$$$ seconds.Please help the mayor to solve this tricky problem and answer his queries. ", "input_spec": "The first lines contains one integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$)\u00a0\u2014 the number of locks. The second lines contains $$$n$$$ integers $$$v_1, v_2, \\dots, v_n$$$ ($$$1 \\le v_i \\le 10^9$$$))\u00a0\u2014 volumes of the locks. The third line contains one integer $$$q$$$ ($$$1 \\le q \\le 200\\,000$$$)\u00a0\u2014 the number of queries. Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \\le t_j \\le 10^9$$$)\u00a0\u2014 the number of seconds you have to fill all the locks in the query $$$j$$$. ", "output_spec": "Print $$$q$$$ integers. The $$$j$$$-th of them should be equal to the minimum number of pipes to turn on so that after $$$t_j$$$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $$$-1$$$. ", "sample_inputs": ["5\n4 1 5 4 1\n6\n1\n6\n2\n3\n4\n5", "5\n4 4 4 4 4\n6\n1\n3\n6\n5\n2\n4"], "sample_outputs": ["-1\n3\n-1\n-1\n4\n3", "-1\n-1\n4\n4\n-1\n5"], "notes": "NoteThere are $$$6$$$ queries in the first example test. In the queries $$$1, 3, 4$$$ the answer is $$$-1$$$. We need to wait $$$4$$$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$. After $$$4$$$ seconds the locks $$$1$$$ and $$$4$$$ are full. In the following $$$1$$$ second $$$1$$$ liter of water is transferred to the locks $$$2$$$ and $$$5$$$. The lock $$$3$$$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$.In the fifth query one can open pipes $$$1, 2, 3, 4$$$. "}, "positive_code": [{"source_code": "\r\nobject prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt).map(_.toLong).toList\r\n val m: Long = v.sum\r\n var j: Long = 0\r\n var p: Long = 0\r\n var co = 0\r\n val vv = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (i <- v) {\r\n co += 1\r\n j += i\r\n p = max(p, (j.toDouble / co).ceil.toLong)\r\n vv += max(p, (m.toDouble / co).ceil.toLong)\r\n }\r\n val wwww = vv.toList.toArray\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val l = readInt()\r\n if (wwww.last > l){\r\n println(-1)\r\n }\r\n else if (wwww.head <= l){\r\n println(1)\r\n }\r\n else {\r\n var a = 0\r\n var b = wwww.length - 1\r\n while ( (b - a) > 1) {\r\n val qqqq = (a + b) / 2\r\n if (wwww(qqqq) <= l) {\r\n b = qqqq\r\n }\r\n else {\r\n a = qqqq\r\n }\r\n }\r\n println(b+1)\r\n }\r\n }\r\n}\r\n\r\n\r\n"}], "negative_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt).toList\r\n val m: Long = v.sum\r\n var j: Long = 0\r\n var p: Long = 0\r\n val vv = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (i <- v.indices) {\r\n j+= v(i).toLong\r\n p = max(p, (j / (i+1)) + min(1,j % (i+1)))\r\n vv += max(p, (m / (i+1)) +min(1,m %(i+1)))\r\n }\r\n val wwww = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val l = readInt()\r\n if (wwww.last > l){\r\n println(-1)\r\n }\r\n else if (wwww.head <= l){\r\n println(1)\r\n }\r\n else {\r\n var a = 0\r\n var b = wwww.length - 1\r\n while ( (b - a) > 1) {\r\n if (wwww((a + b) / 2) <= l) {\r\n b = (a + b) / 2\r\n }\r\n else {\r\n a = (a + b) / 2\r\n }\r\n }\r\n println(b+1)\r\n }\r\n }\r\n}\r\n\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt).toList\r\n val m: Long = v.sum\r\n var j: Long = 0\r\n var p: Long = 0\r\n val vv = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (i <- v.indices) {\r\n j+= v(i)\r\n p = max(p, (j / (i+1)) + min(1,j % (i+1)))\r\n vv += max(p, (m / (i+1)) +min(1,m %(i+1))).toLong\r\n }\r\n val wwww = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val l = readInt()\r\n if (wwww.last > l){\r\n println(-1)\r\n }\r\n else if (wwww.head <= l){\r\n println(1)\r\n }\r\n else {\r\n var a = 0\r\n var b = wwww.length - 1\r\n while ( (b - a) > 1) {\r\n if (wwww((a + b) / 2) <= l) {\r\n b = (a + b) / 2\r\n }\r\n else {\r\n a = (a + b) / 2\r\n }\r\n }\r\n println(b+1)\r\n }\r\n }\r\n}\r\n\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt).toList\r\n val m = v.sum\r\n var j: Long = 0\r\n var d = 0\r\n var p: Long = 0\r\n val vv = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (i <- v.indices) {\r\n j+= v(i)\r\n p = max(p, (j / (i+1)) + min(1,j % (i+1)))\r\n vv += max(p, (m / (i+1)) +min(1,m %(i+1)))\r\n }\r\n val wwww = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val l = readInt()\r\n if (wwww.last > l){\r\n println(-1)\r\n }\r\n else if (wwww.head <= l){\r\n println(1)\r\n }\r\n else {\r\n var a = 0\r\n var b = wwww.length - 1\r\n while ( (b - a) > 1) {\r\n if (wwww((a + b) / 2) <= l) {\r\n b = (a + b) / 2\r\n }\r\n else {\r\n a = (a + b) / 2\r\n }\r\n }\r\n println(b+1)\r\n }\r\n }\r\n}\r\n\r\n\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val l = readInt()\r\n var a = true\r\n var b: Long = 0\r\n var j = 0\r\n for (s <- v) {\r\n j+=1\r\n b +=s\r\n if (((b / l) + min(1, b % l)) > j) {\r\n a = false\r\n }\r\n }\r\n if (a==true){\r\n println(b)\r\n }\r\n else{\r\n println(-1)\r\n }\r\n\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (t <- vvv) {\r\n ss += ((t / s) + min(1,t % s))\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.last)\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Byte]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j.toByte\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Byte]\r\n for (t <- vvv) {\r\n ss += ((t / s) + min(1,t % s)).toByte\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.max)\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Short]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j.toShort\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Short]\r\n for (t <- vvv) {\r\n ss += ((t / s) + min(1,t % s)).toShort\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.max)\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Long]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (t <- vvv) {\r\n ss += (t / s) + min(1,t % s)\r\n }\r\n val sss = ss.toList\r\n println(sss)\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.max)\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Long]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (t <- vvv) {\r\n ss += (t / s) + min(1,t % s)\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.max)\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Int]\r\n var ooo = 0\r\n for (t <- vvv) {\r\n val eee = max(ooo,(t / s) + min(1,t % s))\r\n ss += eee\r\n ooo = eee\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.max)\r\n }\r\n}\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (t <- vvv) {\r\n ss += (t / s) + min(1,t % s)\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.max)\r\n }\r\n}\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n\r\n val a = List(5,1,2,3,4)\r\n print(a.reduceLeft((c,b) => max(c,b) ), a.reduceLeft((c,b) => max(c,b) ), a.reduce((c,b) => max(c,b) ) )\r\n\r\n\r\n}\r\n\r\n\r\n\r\n"}, {"source_code": "object prob extends App {\r\n import scala.io.StdIn\r\n import scala.math.{max,min}\r\n import scala.List\r\n\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val vv = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (i <- v) {\r\n j +=i\r\n vv += j\r\n }\r\n val vvv = vv.toList\r\n val k = readInt()\r\n for (i <- 1 to k) {\r\n val s = readInt()\r\n val ss = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (t <- vvv) {\r\n ss += (t / s) + min(1,t % s)\r\n }\r\n val sss = ss.toList\r\n var it = true\r\n for (t <- 0 until sss.length) {\r\n if (sss(t) > t+1) {\r\n it = false\r\n }\r\n }\r\n if (!it) {\r\n println(-1)\r\n }\r\n else println(sss.reduce((a,b) => max(a,b)))\r\n }\r\n}\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n def find(t:Long,b:List[Long]): Long = {\r\n val bi = scala.collection.mutable.ListBuffer.empty[Long]\r\n for (i <- b) {\r\n val a = if ((i % t) == 0) i / t else {(i / t) + 1}\r\n bi += a\r\n }\r\n val bj = bi.toList\r\n val r = bj.reduceLeft((a,b) => if (a>b) a else b )\r\n var ti = true\r\n for (i <- 0 until bj.length) {\r\n if (bj(i) > i+1) {\r\n ti = false\r\n }\r\n }\r\n if (ti)\r\n r\r\n else\r\n -1\r\n }\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val b = scala.collection.mutable.ListBuffer.empty[Long]\r\n var j = 0\r\n for (l <- v) {\r\n j +=l\r\n b += j\r\n }\r\n val b1 = b.toList\r\n val k = readInt()\r\n for (i <- 1 to k){\r\n val qer = readInt()\r\n println(find(qer,b1))\r\n }\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n def find(t:Int,b:List[Int]): Int = {\r\n val bi = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (i <- b) {\r\n val a = if ((i % t) == 0) i / t else {(i / t) + 1}\r\n bi += a\r\n }\r\n val bj = bi.toList\r\n val r = bj.reduceLeft((a,b) => if (a>b) a else b )\r\n var ti = true\r\n for (i <- 0 until bj.length) {\r\n if (bj(i) > i+1) {\r\n ti = false\r\n }\r\n }\r\n if (ti)\r\n r\r\n else\r\n -1\r\n }\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val b = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (l <- v) {\r\n j +=l\r\n b += j\r\n }\r\n val b1 = b.toList\r\n val k = readInt()\r\n for (i <- 1 to k){\r\n val qer = readInt()\r\n println(find(qer,b1))\r\n }\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n def find(t:Int,b:List[Int]): Int = {\r\n val bi = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (i <- b) {\r\n val a = if ((i % t) == 0) i / t else {(i / t) + 1}\r\n bi += a\r\n }\r\n val bj = bi.toList\r\n val r = bj.reduceLeft((a,b) => if (a>b) a else b )\r\n var ti = true\r\n for (i <- 0 until min(r,bj.length)) {\r\n if (bj(i) > i+1) {\r\n ti = false\r\n }\r\n }\r\n if (ti)\r\n r\r\n else\r\n -1\r\n }\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val b = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (l <- v) {\r\n j +=l\r\n b += j\r\n }\r\n val b1 = b.toList\r\n val k = readInt()\r\n for (i <- 1 to k){\r\n val qer = readInt()\r\n println(find(qer,b1))\r\n }\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n def find(t:Int,b:List[Int]): Int = {\r\n val bi = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (i <- b) {\r\n val a = if ((i % t) == 0) i / t else {(i / t) + 1}\r\n bi += a\r\n }\r\n val bj = bi.toList\r\n val r = bj.reduceLeft((a,b) => if (a>b) a else b )\r\n var ti = true\r\n for (i <- 0 until min(r,bj.length)) {\r\n if (bj(i) > i+1) {\r\n ti = false\r\n }\r\n }\r\n if (ti)\r\n r\r\n else\r\n -1\r\n }\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val b = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (l <- v) {\r\n j +=l\r\n b += j\r\n }\r\n val b1 = b.toList\r\n val k = readInt()\r\n for (i <- 1 to k){\r\n val k = readInt()\r\n println(find(k,b1))\r\n }\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.{abs,max,min}\r\n import scala.List\r\n import scala.collection.mutable.ListBuffer\r\n def find(t:Int,b:List[Int]): Int = {\r\n val bi = scala.collection.mutable.ListBuffer.empty[Int]\r\n for (i <- b) {\r\n val a = if ((i % t) == 0) i / t else {(i / t) + 1}\r\n bi += a\r\n }\r\n val bj = bi.toList\r\n val r = bj.reduceLeft((a,b) => if (a>b) a else b )\r\n var ti = true\r\n for (i <- 0 until min(r,bj.length)) {\r\n if (bj(i) > i+1) {\r\n ti = false\r\n }\r\n }\r\n if (ti)\r\n r\r\n else\r\n -1\r\n }\r\n val n = readInt()\r\n val v = readLine.split(\" \").map(_.toInt)\r\n val b = scala.collection.mutable.ListBuffer.empty[Int]\r\n var j = 0\r\n for (l <- v) {\r\n j +=l\r\n b += j\r\n }\r\n val b1 = b.toList\r\n val k = readInt()\r\n for (i <- 1 to k){\r\n val k = readInt()\r\n println(find(k,b1))\r\n }\r\n\r\n\r\n}\r\n\r\n"}], "src_uid": "d7361a43bff124cea280ae8817b807ec"} {"nl": {"description": "This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.To bake a Napoleon cake, one has to bake $$$n$$$ dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps $$$n$$$ times: place a new cake layer on the top of the stack; after the $$$i$$$-th layer is placed, pour $$$a_i$$$ units of cream on top of the stack. When $$$x$$$ units of cream are poured on the top of the stack, top $$$x$$$ layers of the cake get drenched in the cream. If there are less than $$$x$$$ layers, all layers get drenched and the rest of the cream is wasted. If $$$x = 0$$$, no layer gets drenched. The picture represents the first test case of the example. Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 20\\,000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of layers in the cake. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le n$$$)\u00a0\u2014 the amount of cream poured on the cake after adding each layer. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single line with $$$n$$$ integers. The $$$i$$$-th of the integers should be equal to $$$1$$$ if the $$$i$$$-th layer from the bottom gets drenched, and $$$0$$$ otherwise.", "sample_inputs": ["3\n6\n0 3 0 0 1 3\n10\n0 0 0 1 0 5 0 0 0 2\n3\n0 0 0"], "sample_outputs": ["1 1 0 1 1 1 \n0 1 1 1 1 1 0 0 1 1 \n0 0 0"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "807c5ec37b0ea83ef40550698f1ff498"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$. The string $$$s$$$ consists of lowercase Latin letters and at most one wildcard character '*', the string $$$t$$$ consists only of lowercase Latin letters. The length of the string $$$s$$$ equals $$$n$$$, the length of the string $$$t$$$ equals $$$m$$$.The wildcard character '*' in the string $$$s$$$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $$$s$$$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $$$s$$$ to obtain a string $$$t$$$, then the string $$$t$$$ matches the pattern $$$s$$$.For example, if $$$s=$$$\"aba*aba\" then the following strings match it \"abaaba\", \"abacaba\" and \"abazzzaba\", but the following strings do not match: \"ababa\", \"abcaaba\", \"codeforces\", \"aba1aba\", \"aba?aba\".If the given string $$$t$$$ matches the given string $$$s$$$, print \"YES\", otherwise print \"NO\".", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$) \u2014 the length of the string $$$s$$$ and the length of the string $$$t$$$, respectively. The second line contains string $$$s$$$ of length $$$n$$$, which consists of lowercase Latin letters and at most one wildcard character '*'. The third line contains string $$$t$$$ of length $$$m$$$, which consists only of lowercase Latin letters.", "output_spec": "Print \"YES\" (without quotes), if you can obtain the string $$$t$$$ from the string $$$s$$$. Otherwise print \"NO\" (without quotes).", "sample_inputs": ["6 10\ncode*s\ncodeforces", "6 5\nvk*cup\nvkcup", "1 1\nv\nk", "9 6\ngfgf*gfgf\ngfgfgf"], "sample_outputs": ["YES", "YES", "NO", "NO"], "notes": "NoteIn the first example a wildcard character '*' can be replaced with a string \"force\". So the string $$$s$$$ after this replacement is \"codeforces\" and the answer is \"YES\".In the second example a wildcard character '*' can be replaced with an empty string. So the string $$$s$$$ after this replacement is \"vkcup\" and the answer is \"YES\".There is no wildcard character '*' in the third example and the strings \"v\" and \"k\" are different so the answer is \"NO\".In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string $$$t$$$ so the answer is \"NO\"."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) and replaces the i-th element of array ai either with ai\u2009+\u2009x or with ai\u2009-\u2009x. Please note that the operation may be applied more than once to the same position.Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. ) can reach, if Maxim would apply no more than k operations to it. Please help him in that.", "input_spec": "The first line of the input contains three integers n,\u2009k and x (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009200\u2009000,\u20091\u2009\u2264\u2009x\u2009\u2264\u2009109)\u00a0\u2014 the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an ()\u00a0\u2014 the elements of the array found by Maxim.", "output_spec": "Print n integers b1,\u2009b2,\u2009...,\u2009bn in the only line\u00a0\u2014 the array elements after applying no more than k operations to the array. In particular, should stay true for every 1\u2009\u2264\u2009i\u2009\u2264\u2009n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them.", "sample_inputs": ["5 3 1\n5 4 3 5 2", "5 3 1\n5 4 3 5 5", "5 3 1\n5 4 4 5 5", "3 2 7\n5 4 2"], "sample_outputs": ["5 4 3 5 -1", "5 4 0 5 5", "5 1 4 5 5", "5 11 -5"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k\n if (parity == 0) {\n left -= Math.min(k, 1 + Math.abs(a(min)) / x).toInt\n if (a(min) >= 0)\n a(min) -= Math.min(k, 1 + Math.abs(a(min)) / x) * x\n else\n a(min) += Math.min(k, 1 + Math.abs(a(min)) / x) * x\n }\n\n if (left > 0) {\n val q = mutable.PriorityQueue(a.map(i => -Math.abs(i)).zipWithIndex: _*)\n (0 until left).foreach { _ =>\n val (value, index) = q.dequeue()\n q.enqueue((value - x, index))\n }\n q.foreach {\n case (value, index) if a(index) >= 0 => a(index) = Math.abs(value)\n case (value, index) => a(index) = -Math.abs(value)\n }\n\n }\n\n println(a.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt)\n val min = a.indices.minBy(a)\n val nValue = a(min) - Math.min(k, 1 + a(min) / x) * x\n var left = k - Math.min(k, 1 + a(min) / x)\n a(min) = -nValue\n\n if (left > 0) {\n val sorted = a.indices.sortBy(i => Math.abs(a(i)))\n val increments = Array.ofDim[Int](n + 1)\n var i = 1\n while (left > 0) {\n val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)\n increments(0) += 1\n if (left >= j) {\n increments(j - 1) -= 1\n i = j\n left -= j\n } else {\n increments(k - 1) -= 1\n left = 0\n }\n }\n var sum = 0\n (0 until n).foreach { i =>\n sum += x * increments(i)\n a(sorted(i)) += sum\n }\n\n// println(increments.mkString(\" \"))\n }\n a(min) *= -1\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k\n if (parity == 0) {\n left -= Math.min(k, 1 + a(min) / x).toInt\n if (a(min) >= 0)\n a(min) -= Math.min(k, 1 + a(min) / x) * x\n else\n a(min) += Math.min(k, 1 + a(min) / x) * x\n }\n\n if (left > 0) {\n val q = mutable.PriorityQueue(a.map(i => -Math.abs(i)).zipWithIndex: _*)\n (0 until left).foreach { _ =>\n val (value, index) = q.dequeue()\n q.enqueue((value - x, index))\n }\n q.foreach {\n case (value, index) if a(index) >= 0 => a(index) = Math.abs(value)\n case (value, index) => a(index) = -Math.abs(value)\n }\n\n }\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k.toLong\n if (parity == 0) {\n left -= Math.min(k, 1 + a(min) / x)\n if (a(min) >= 0)\n a(min) -= Math.min(k, 1 + a(min) / x) * x\n else\n a(min) += Math.min(k, 1 + a(min) / x) * x\n }\n\n if (left > 0) {\n val sorted = a.indices.sortBy(i => Math.abs(a(i)))\n val increments = Array.ofDim[Int](n + 1)\n var i = 1\n while (left > 0) {\n val j = (i until n).find(z => Math.abs(a(sorted(z))) >= Math.abs(a(sorted(0)) + (increments(0) + 1) * x)).getOrElse(n)\n increments(0) += 1\n if (left >= j) {\n increments(j) -= 1\n i = j\n left -= j\n } else {\n increments(left.toInt) -= 1\n left = 0\n }\n }\n var sum = 0l\n (0 until n).foreach { i =>\n sum += x * increments(i)\n if (a(sorted(i)) >= 0)\n a(sorted(i)) += sum\n else\n a(sorted(i)) -= sum\n }\n\n // println(increments.mkString(\" \"))\n }\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k.toLong\n if (parity == 0) {\n val nValue = a(min) - Math.min(k, 1 + a(min) / x) * x\n left -= Math.min(k, 1 + a(min) / x)\n a(min) = -nValue\n }\n\n if (left > 0) {\n val sorted = a.indices.sortBy(i => Math.abs(a(i)))\n val increments = Array.ofDim[Int](n + 1)\n var i = 1\n while (left > 0) {\n val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)\n increments(0) += 1\n if (left >= j) {\n increments(j - 1) -= 1\n i = j\n left -= j\n } else {\n increments(left.toInt) -= 1\n left = 0\n }\n }\n var sum = 0l\n (0 until n).foreach { i =>\n sum += x * increments(i)\n if (a(sorted(i)) >= 0)\n a(sorted(i)) += sum\n else\n a(sorted(i)) -= sum\n }\n\n // println(increments.mkString(\" \"))\n }\n if (parity == 0)\n a(min) *= -1\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k.toLong\n if (parity == 0) {\n left -= Math.min(k, 1 + a(min) / x)\n if (a(min) >= 0)\n a(min) -= Math.min(k, 1 + a(min) / x) * x\n else\n a(min) += Math.min(k, 1 + a(min) / x) * x\n }\n\n if (left > 0) {\n val sorted = a.indices.sortBy(i => Math.abs(a(i)))\n val increments = Array.ofDim[Int](n + 1)\n var i = 1\n while (left > 0) {\n val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)\n increments(0) += 1\n if (left >= j) {\n increments(j - 1) -= 1\n i = j\n left -= j\n } else {\n increments(left.toInt) -= 1\n left = 0\n }\n }\n var sum = 0l\n (0 until n).foreach { i =>\n sum += x * increments(i)\n if (a(sorted(i)) >= 0)\n a(sorted(i)) += sum\n else\n a(sorted(i)) -= sum\n }\n\n // println(increments.mkString(\" \"))\n }\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k.toLong\n if (parity == 0) {\n val nValue = a(min) - Math.min(k, 1 + a(min) / x) * x\n left -= Math.min(k, 1 + a(min) / x)\n a(min) = -nValue\n }\n\n if (left > 0) {\n val sorted = a.indices.sortBy(i => Math.abs(a(i)))\n val increments = Array.ofDim[Int](n + 1)\n var i = 1\n while (left > 0) {\n val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)\n increments(0) += 1\n if (left >= j) {\n increments(j - 1) -= 1\n i = j\n left -= j\n } else {\n increments(left.toInt - 1) -= 1\n left = 0\n }\n }\n var sum = 0l\n (0 until n).foreach { i =>\n sum += x * increments(i)\n if (a(sorted(i)) >= 0)\n a(sorted(i)) += sum\n else\n a(sorted(i)) -= sum\n }\n\n// println(increments.mkString(\" \"))\n }\n if (parity == 0)\n a(min) *= -1\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k\n if (parity == 1) {\n left -= Math.min(k, 1 + Math.abs(a(min)) / x).toInt\n if (a(min) >= 0)\n a(min) -= Math.min(k, 1 + Math.abs(a(min)) / x) * x\n else\n a(min) += Math.min(k, 1 + Math.abs(a(min)) / x) * x\n }\n\n if (left > 0) {\n val q = mutable.PriorityQueue(a.map(i => -Math.abs(i)).zipWithIndex: _*)\n (0 until left).foreach { _ =>\n val (value, index) = q.dequeue()\n q.enqueue((value - x, index))\n }\n q.foreach {\n case (value, index) if a(index) >= 0 => a(index) = Math.abs(value)\n case (value, index) => a(index) = -Math.abs(value)\n }\n\n }\n\n println(a.mkString(\" \"))\n}"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, k, x) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toLong)\n val parity = a.count(_ < 0) % 2\n val zeros = a.count(_ == 0)\n\n\n val min = a.indices.minBy(i => Math.abs(a(i)))\n var left = k.toLong\n if (parity == 0) {\n left -= Math.min(k, 1 + a(min) / x)\n if (a(min) >= 0)\n a(min) -= Math.min(k, 1 + a(min) / x) * x\n else\n a(min) += Math.min(k, 1 + a(min) / x) * x\n }\n\n if (left > 0) {\n val sorted = a.indices.sortBy(i => Math.abs(a(i)))\n val increments = Array.ofDim[Int](n + 1)\n var i = 1\n while (left > 0) {\n val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)\n increments(0) += 1\n if (left >= j) {\n increments(j) -= 1\n i = j\n left -= j\n } else {\n increments(left.toInt) -= 1\n left = 0\n }\n }\n var sum = 0l\n (0 until n).foreach { i =>\n sum += x * increments(i)\n if (a(sorted(i)) >= 0)\n a(sorted(i)) += sum\n else\n a(sorted(i)) -= sum\n }\n\n // println(increments.mkString(\" \"))\n }\n\n println(a.mkString(\" \"))\n}"}], "src_uid": "6db54c7de672a1fd0afd052894ce4ce8"} {"nl": {"description": "Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0,\u2009a1,\u2009...,\u2009ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.", "input_spec": "The first line contains a single integer h (2\u2009\u2264\u2009h\u2009\u2264\u2009105)\u00a0\u2014 the height of the tree. The second line contains h\u2009+\u20091 integers\u00a0\u2014 the sequence a0,\u2009a1,\u2009...,\u2009ah (1\u2009\u2264\u2009ai\u2009\u2264\u20092\u00b7105). The sum of all ai does not exceed 2\u00b7105. It is guaranteed that there is at least one tree matching this sequence.", "output_spec": "If there is only one tree matching this sequence, print \"perfect\". Otherwise print \"ambiguous\" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence.", "sample_inputs": ["2\n1 1 1", "2\n1 2 2"], "sample_outputs": ["perfect", "ambiguous\n0 1 1 3 3\n0 1 1 3 2"], "notes": "NoteThe only tree in the first example and the two printed trees from the second example are shown on the picture:"}, "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(h) = readIntLine()\n val heightCounts = readIntLine()\n val n = heightCounts.sum\n val ambiguous = heightCounts.sliding(2).exists(a => a(0) > 1 && a(1) > 1)\n if (!ambiguous) {\n println(\"perfect\")\n return\n }\n\n println(\"ambiguous\")\n println(construct(h, heightCounts, true).mkString(\" \"))\n println(construct(h, heightCounts, false).mkString(\" \"))\n }\n\n def construct(h : Int, heightCounts : Array[Int], mode : Boolean): Array[Int] = {\n val heightSums : Array[Int] = Array.ofDim(h + 1)\n heightSums.indices.tail.foreach{\n i =>\n heightSums(i) = heightSums(i - 1) + heightCounts(i - 1)\n }\n val parents = Array.ofDim[Int](heightSums.last + heightCounts.last)\n parents(0) = 0\n for ((count, height) <- heightCounts.zipWithIndex.tail) {\n val nodeIdx = heightSums(height)\n for (i <- 0 until count) {\n if (mode) {\n parents(i + nodeIdx) = (nodeIdx - 1) + 1\n } else {\n parents(i + nodeIdx) = Math.min(nodeIdx - 1, heightSums(height - 1) + i) + 1\n }\n }\n }\n parents\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": "a186acbdc88a7ed131a7e5f999877fd6"} {"nl": {"description": "$$$n$$$ heroes fight against each other in the Arena. Initially, the $$$i$$$-th hero has level $$$a_i$$$.Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $$$1$$$.The winner of the tournament is the first hero that wins in at least $$$100^{500}$$$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.Calculate the number of possible winners among $$$n$$$ heroes.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 the number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the initial level of the $$$i$$$-th hero.", "output_spec": "For each test case, print one integer \u2014 the number of possible winners among the given $$$n$$$ heroes.", "sample_inputs": ["3\n3\n3 2 2\n2\n5 5\n4\n1 3 3 7"], "sample_outputs": ["1\n0\n3"], "notes": "NoteIn the first test case of the example, the only possible winner is the first hero.In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner."}, "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": "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"}, {"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"} {"nl": {"description": "A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i,\u2009j) such that i\u2009>\u2009j and ai\u2009<\u2009aj. For example, a permutation [4,\u20091,\u20093,\u20092] contains 4 inversions: (2,\u20091), (3,\u20091), (4,\u20091), (4,\u20093).You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l,\u2009r] of the permutation. For example, if a\u2009=\u2009[1,\u20092,\u20093,\u20094] and a query l\u2009=\u20092, r\u2009=\u20094 is applied, then the resulting permutation is [1,\u20094,\u20093,\u20092].After each query you have to determine whether the number of inversions is odd or even.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091500) \u2014 the size of the permutation. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the elements of the permutation. These integers are pairwise distinct. The third line contains one integer m (1\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of queries to process. Then m lines follow, i-th line containing two integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) denoting that i-th query is to reverse a segment [li,\u2009ri] of the permutation. All queries are performed one after another.", "output_spec": "Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.", "sample_inputs": ["3\n1 2 3\n2\n1 2\n2 3", "4\n1 2 4 3\n4\n1 1\n1 4\n1 4\n2 3"], "sample_outputs": ["odd\neven", "odd\nodd\nodd\neven"], "notes": "NoteThe first example: after the first query a\u2009=\u2009[2,\u20091,\u20093], inversion: (2,\u20091); after the second query a\u2009=\u2009[2,\u20093,\u20091], inversions: (3,\u20091), (3,\u20092). The second example: a\u2009=\u2009[1,\u20092,\u20094,\u20093], inversion: (4,\u20093); a\u2009=\u2009[3,\u20094,\u20092,\u20091], inversions: (3,\u20091), (4,\u20091), (3,\u20092), (4,\u20092), (4,\u20093); a\u2009=\u2009[1,\u20092,\u20094,\u20093], inversion: (4,\u20093); a\u2009=\u2009[1,\u20094,\u20092,\u20093], inversions: (3,\u20092), (4,\u20092). "}, "positive_code": [{"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 inversionCount[T](a : Array[T])(implicit ev: T => Ordered[T]) : Int = {\n inversionCountHelp(a, a.clone(), 0, a.length)\n }\n\n def inversionCountHelp[T](a : Array[T], b : Array[T], from : Int, to : Int)(implicit ev: T => Ordered[T]) : Int = {\n if (to - from <= 1) {\n return 0\n }\n var mid = (from + to) / 2\n var sum = inversionCountHelp(b, a, from, mid) + inversionCountHelp(b, a, mid, to)\n var i = from\n var j = mid\n var c = from\n while (i < mid && j < to) {\n if (b(i) < b(j)) {\n a(c) = b(i)\n i += 1\n } else {\n sum += mid - i\n a(c) = b(j)\n j += 1\n }\n c += 1\n }\n var x = i\n while (x < mid) {\n a(c) = b(x)\n c += 1\n x += 1\n }\n x = j\n while (x < to) {\n a(c) = b(x)\n c += 1\n x += 1\n }\n sum\n }\n\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val perm = readIntLine().map(_ - 1)\n val Array(m) = readIntLine()\n\n var count = inversionCount(perm.clone()) % 2\n var record : List[String] = List()\n var i = 0\n while (i < m) {\n var Array(l, r) = readIntLine()\n val changes = (r - l + 1) * (r - l) / 2\n count = (count + changes) % 2\n\n if (count % 2 == 1) {\n record ::= \"odd\"\n } else {\n record ::= \"even\"\n }\n i += 1\n }\n print(record.toArray.reverse.mkString(\"\\n\"))\n print(\"\\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 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": "d20cc952cdf3a99e7d980a0270c49f78"} {"nl": {"description": "Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?", "input_spec": "The first line of the input contains two integers n and h (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009h\u2009\u2264\u20091000)\u00a0\u2014 the number of friends and the height of the fence, respectively. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20092h), the i-th of them is equal to the height of the i-th person.", "output_spec": "Print a single integer\u00a0\u2014 the minimum possible valid width of the road.", "sample_inputs": ["3 7\n4 5 14", "6 1\n1 1 1 1 1 1", "6 5\n7 6 8 9 10 5"], "sample_outputs": ["4", "6", "11"], "notes": "NoteIn the first sample, only person number 3 must bend down, so the required width is equal to 1\u2009+\u20091\u2009+\u20092\u2009=\u20094.In the second sample, all friends are short enough and no one has to bend, so the width 1\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u20096 is enough.In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2\u2009+\u20092\u2009+\u20092\u2009+\u20092\u2009+\u20092\u2009+\u20091\u2009=\u200911."}, "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": "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"}, {"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"} {"nl": {"description": "You are given two arrays of integers $$$a_1,\\ldots,a_n$$$ and $$$b_1,\\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\\ldots,c_k$$$ that is a subsequence of $$$a_1,\\ldots,a_n$$$, and also a subsequence of $$$b_1,\\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 1000$$$) \u00a0\u2014 the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\\le n,m\\le 1000$$$) \u00a0\u2014 the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\\ldots,a_n$$$ ($$$1\\le a_i\\le 1000$$$) \u00a0\u2014 the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\\ldots,b_m$$$ ($$$1\\le b_i\\le 1000$$$) \u00a0\u2014 the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\\sum\\limits_{i=1}^t n_i, \\sum\\limits_{i=1}^t m_i\\le 1000$$$).", "output_spec": "For each test case, output \"YES\" if a solution exists, or \"NO\" otherwise. If the answer is \"YES\", on the next line output an integer $$$k$$$ ($$$1\\le k\\le 1000$$$) \u00a0\u2014 the length of the array, followed by $$$k$$$ integers $$$c_1,\\ldots,c_k$$$ ($$$1\\le c_i\\le 1000$$$) \u00a0\u2014 the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.", "sample_inputs": ["5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5"], "sample_outputs": ["YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 2"], "notes": "NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is \"NO\"."}, "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 val d = in.nextInt()\n\n val number1 = in.line().split(\" \").map(_.toInt)\n val number2 = in.line().split(\" \").map(_.toInt)\n\n val t = number1.find(number2.contains)\n\n if (t.isDefined) {\n println(\"YES\")\n println(s\"1 ${t.get}\")\n } else {\n println(\"NO\")\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}"}], "negative_code": [], "src_uid": "776a06c14c6fa3ef8664eec0b4d50824"} {"nl": {"description": "Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence $$$a_1, a_2, \\ldots, a_n$$$ of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.Let's denote the fingers of hand by numbers from $$$1$$$ to $$$5$$$. We call a fingering any sequence $$$b_1, \\ldots, b_n$$$ of fingers numbers. A fingering is convenient if for all $$$1\\leq i \\leq n - 1$$$ the following holds: if $$$a_i < a_{i+1}$$$ then $$$b_i < b_{i+1}$$$, because otherwise Paul needs to take his hand off the keyboard to play the $$$(i+1)$$$-st note; if $$$a_i > a_{i+1}$$$ then $$$b_i > b_{i+1}$$$, because of the same; if $$$a_i = a_{i+1}$$$ then $$$b_i\\neq b_{i+1}$$$, because using the same finger twice in a row is dumb. Please note that there is $$$\\neq$$$, not $$$=$$$ between $$$b_i$$$ and $$$b_{i+1}$$$. Please provide any convenient fingering or find out that there is none.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) denoting the number of notes. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2\\cdot10^5$$$) denoting the positions of notes on the keyboard.", "output_spec": "If there is no convenient fingering, print $$$-1$$$. Otherwise, print $$$n$$$ numbers $$$b_1, b_2, \\ldots, b_n$$$, each from $$$1$$$ to $$$5$$$, denoting a convenient fingering, separated by spaces.", "sample_inputs": ["5\n1 1 4 2 2", "7\n1 5 7 8 10 3 1", "19\n3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8"], "sample_outputs": ["1 4 5 4 5", "1 2 3 4 5 4 3", "1 3 4 5 4 5 4 5 4 5 4 5 4 3 5 4 3 5 4"], "notes": "NoteThe third sample test is kinda \"Non stop\" song by Reflex."}, "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[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}"}, {"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"} {"nl": {"description": "You are given two sequences $$$a_1, a_2, \\dots, a_n$$$ and $$$b_1, b_2, \\dots, b_n$$$. Each element of both sequences is either $$$0$$$, $$$1$$$ or $$$2$$$. The number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$a$$$ is $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ respectively, and the number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$b$$$ is $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ respectively.You can rearrange the elements in both sequences $$$a$$$ and $$$b$$$ however you like. After that, let's define a sequence $$$c$$$ as follows:$$$c_i = \\begin{cases} a_i b_i & \\mbox{if }a_i > b_i \\\\ 0 & \\mbox{if }a_i = b_i \\\\ -a_i b_i & \\mbox{if }a_i < b_i \\end{cases}$$$You'd like to make $$$\\sum_{i=1}^n c_i$$$ (the sum of all elements of the sequence $$$c$$$) as large as possible. What is the maximum possible sum?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \\le x_1, y_1, z_1 \\le 10^8$$$)\u00a0\u2014 the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$a$$$. The second line of each test case also contains three integers $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \\le x_2, y_2, z_2 \\le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$)\u00a0\u2014 the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.", "output_spec": "For each test case, print the maximum possible sum of the sequence $$$c$$$.", "sample_inputs": ["3\n2 3 2\n3 3 1\n4 0 1\n2 3 0\n0 0 1\n0 0 1"], "sample_outputs": ["4\n2\n0"], "notes": "NoteIn the first sample, one of the optimal solutions is:$$$a = \\{2, 0, 1, 1, 0, 2, 1\\}$$$$$$b = \\{1, 0, 1, 0, 2, 1, 0\\}$$$$$$c = \\{2, 0, 0, 0, 0, 2, 0\\}$$$In the second sample, one of the optimal solutions is:$$$a = \\{0, 2, 0, 0, 0\\}$$$$$$b = \\{1, 1, 0, 1, 0\\}$$$$$$c = \\{0, 2, 0, 0, 0\\}$$$In the third sample, the only possible solution is:$$$a = \\{2\\}$$$$$$b = \\{2\\}$$$$$$c = \\{0\\}$$$"}, "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": "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"}, {"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"} {"nl": {"description": "In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.", "input_spec": "The input contains three strings in three separate lines: s1, s2 and virus (1\u2009\u2264\u2009|s1|,\u2009|s2|,\u2009|virus|\u2009\u2264\u2009100). Each string consists only of uppercase English letters.", "output_spec": "Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted. If there is no valid common subsequence, output 0.", "sample_inputs": ["AJKEQSLOBSROFGZ\nOVGURWZLWVLUXTH\nOZ", "AA\nA\nA"], "sample_outputs": ["ORZ", "0"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.immutable.StringOps\nimport scala.util.control.Breaks._\n\n\nobject Main {\n\n def kmpMatch(s: StringOps): Array[Int] = {\n val n = s.length\n val ret = (1 to n).map(_ => -1).toArray\n for (i <- 0 to n - 1) {\n var j = i - 1\n breakable {\n while (j != -1) {\n if (s(ret(j) + 1) == s(i)) {\n break\n }\n j = ret(j)\n }\n }\n if (j != -1) {\n ret.update(i, ret(j) + 1)\n }\n }\n return ret\n }\n\n def solve(s: StringOps, t: StringOps, virus: StringOps): String = {\n def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {\n if (x == 0 || y == 0) {\n return \"\"\n }\n if (rec(x)(y)(z) == 0) {\n return build(x - 1, y, z, rec)\n } else if (rec(x)(y)(z) == 1) {\n return build(x, y - 1, z, rec)\n } else {\n return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))\n }\n }\n val ns = s.length\n val nt = t.length\n val nv = virus.length\n val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val kmp = kmpMatch(virus)\n for (i <- 0 to ns) {\n dp(i)(0)(0) = 0\n }\n for (j <- 0 to nt) {\n dp(0)(j)(0) = 0\n }\n for (i <- 0 to ns - 1) {\n for (j <- 0 to nt - 1) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) != -1) {\n if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {\n rec(i + 1)(j)(k) = 0\n dp(i + 1)(j)(k) = dp(i)(j)(k)\n }\n if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {\n rec(i)(j + 1)(k) = 1\n dp(i)(j + 1)(k) = dp(i)(j)(k)\n }\n if (s(i) == t(j)) {\n var idx = k - 1\n breakable {\n while (idx != -1) {\n if (virus(idx + 1) == s(i)) {\n break\n }\n idx = kmp(idx)\n }\n }\n if (virus(idx + 1) == s(i)) {\n idx = idx + 1\n }\n if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {\n rec(i + 1)(j + 1)(idx + 1) = -(k + 1)\n dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1\n }\n }\n }\n }\n }\n }\n var r = -1\n var x = -1\n var y = -1\n var z = -1\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) > r) {\n r = dp(i)(j)(k)\n x = i\n y = j\n z = k\n }\n }\n }\n }\n return if (r > 0) build(x, y, z, rec) else \"0\"\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n val t = readLine()\n val virus = readLine()\n println(solve(s, t, virus))\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.collection.immutable.StringOps\nimport scala.util.control.Breaks._\n\n\nobject Main {\n\n def kmpMatch(s: StringOps): Array[Int] = {\n val n = s.length\n val ret = (1 to n).map(_ => -1).toArray\n for (i <- 0 to n - 1) {\n var j = i - 1\n breakable {\n while (j != -1) {\n if (s(ret(j) + 1) == s(i)) {\n break\n }\n j = ret(j)\n }\n }\n if (j != -1) {\n ret.update(i, ret(j) + 1)\n }\n }\n return ret\n }\n\n def solve(s: StringOps, t: StringOps, virus: StringOps): String = {\n def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {\n if (x == 0 || y == 0) {\n return \"\"\n }\n if (rec(x)(y)(z) == 0) {\n return build(x - 1, y, z, rec)\n } else if (rec(x)(y)(z) == 1) {\n return build(x, y - 1, z, rec)\n } else {\n return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))\n }\n }\n val ns = s.length\n val nt = t.length\n val nv = virus.length\n val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val kmp = kmpMatch(virus)\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n dp(i)(j)(0) = 0\n }\n }\n for (i <- 0 to ns - 1) {\n for (j <- 0 to nt - 1) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) != -1) {\n if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {\n rec(i + 1)(j)(k) = 0\n dp(i + 1)(j)(k) = dp(i)(j)(k)\n }\n if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {\n rec(i)(j + 1)(k) = 1\n dp(i)(j + 1)(k) = dp(i)(j)(k)\n }\n if (s(i) == t(j)) {\n var idx = k\n breakable {\n while (idx != -1) {\n if (virus(idx) == s(i)) {\n break\n }\n idx = kmp(idx)\n }\n }\n if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {\n rec(i + 1)(j + 1)(idx + 1) = -(k + 1)\n dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1\n }\n }\n }\n }\n }\n }\n var r = -1\n var x = -1\n var y = -1\n var z = -1\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) > r) {\n r = dp(i)(j)(k)\n x = i\n y = j\n z = k\n }\n }\n }\n }\n return if (r > 0) build(x, y, z, rec) else \"0\"\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n val t = readLine()\n val virus = readLine()\n println(solve(s, t, virus))\n }\n\n}\n"}, {"source_code": "import scala.collection.immutable.StringOps\nimport scala.util.control.Breaks._\n\n\nobject Main {\n\n def kmpMatch(s: StringOps): Array[Int] = {\n val n = s.length\n val ret = (1 to n).map(_ => -1).toArray\n for (i <- 0 to n - 1) {\n var j = i - 1\n breakable {\n while (j != -1) {\n if (s(ret(j) + 1) == s(i)) {\n break\n }\n j = ret(j)\n }\n }\n if (j != -1) {\n ret.update(i, ret(j) + 1)\n }\n }\n return ret\n }\n\n def solve(s: StringOps, t: StringOps, virus: StringOps): String = {\n def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {\n if (x == 0 || y == 0) {\n return \"\"\n }\n if (rec(x)(y)(z) == 0) {\n return build(x - 1, y, z, rec)\n } else if (rec(x)(y)(z) == 1) {\n return build(x, y - 1, z, rec)\n } else {\n return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))\n }\n }\n val ns = s.length\n val nt = t.length\n val nv = virus.length\n val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val kmp = kmpMatch(virus)\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n dp(i)(j)(0) = 0\n }\n }\n for (i <- 0 to ns - 1) {\n for (j <- 0 to nt - 1) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) != -1) {\n if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {\n rec(i + 1)(j)(k) = 0\n dp(i + 1)(j)(k) = dp(i)(j)(k)\n }\n if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {\n rec(i)(j + 1)(k) = 1\n dp(i)(j + 1)(k) = dp(i)(j)(k)\n }\n if (s(i) == t(j)) {\n var idx = k\n breakable {\n while (idx != -1) {\n if (virus(idx) == s(i)) {\n break\n }\n idx = kmp(idx)\n }\n }\n if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {\n rec(i + 1)(j + 1)(idx + 1) = -(k + 1)\n dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1\n }\n }\n }\n }\n }\n }\n var r = -1\n var x = -1\n var y = -1\n var z = -1\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) > r) {\n r = dp(i)(j)(k)\n x = i\n y = j\n z = k\n }\n }\n }\n }\n return build(x, y, z, rec)\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n val t = readLine()\n val virus = readLine()\n println(solve(s, t, virus))\n }\n\n}\n"}, {"source_code": "import scala.collection.immutable.StringOps\nimport scala.util.control.Breaks._\n\n\nobject Main {\n\n def kmpMatch(s: StringOps): Array[Int] = {\n val n = s.length\n val ret = (1 to n).map(_ => -1).toArray\n for (i <- 0 to n - 1) {\n var j = i - 1\n breakable {\n while (j != -1) {\n if (s(ret(j) + 1) == s(i)) {\n break\n }\n j = ret(j)\n }\n }\n if (j != -1) {\n ret.update(i, ret(j) + 1)\n }\n }\n return ret\n }\n\n def solve(s: StringOps, t: StringOps, virus: StringOps): String = {\n def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {\n if (x == 0 || y == 0) {\n return \"\"\n }\n if (rec(x)(y)(z) == 0) {\n return build(x - 1, y, z, rec)\n } else if (rec(x)(y)(z) == 1) {\n return build(x, y - 1, z, rec)\n } else {\n return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))\n }\n }\n val ns = s.length\n val nt = t.length\n val nv = virus.length\n val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val kmp = kmpMatch(virus)\n for (i <- 0 to ns) {\n dp(i)(0)(0) = 0\n }\n for (j <- 0 to nt) {\n dp(0)(j)(0) = 0\n }\n for (i <- 0 to ns - 1) {\n for (j <- 0 to nt - 1) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) != -1) {\n if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {\n rec(i + 1)(j)(k) = 0\n dp(i + 1)(j)(k) = dp(i)(j)(k)\n }\n if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {\n rec(i)(j + 1)(k) = 1\n dp(i)(j + 1)(k) = dp(i)(j)(k)\n }\n if (s(i) == t(j)) {\n var idx = k\n breakable {\n while (idx != -1) {\n if (virus(idx) == s(i)) {\n break\n }\n idx = kmp(idx)\n }\n }\n if (idx < nv - 1 && virus(idx + 1) == s(i)) {\n idx = idx + 1\n }\n if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {\n rec(i + 1)(j + 1)(idx + 1) = -(k + 1)\n dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1\n }\n }\n }\n }\n }\n }\n var r = -1\n var x = -1\n var y = -1\n var z = -1\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) > r) {\n r = dp(i)(j)(k)\n x = i\n y = j\n z = k\n }\n }\n }\n }\n return if (r > 0) build(x, y, z, rec) else \"0\"\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n val t = readLine()\n val virus = readLine()\n println(solve(s, t, virus))\n }\n\n}\n"}, {"source_code": "import scala.collection.immutable.StringOps\nimport scala.util.control.Breaks._\n\n\nobject Main {\n\n def kmpMatch(s: StringOps): Array[Int] = {\n val n = s.length\n val ret = (1 to n).map(_ => -1).toArray\n for (i <- 0 to n - 1) {\n var j = i - 1\n breakable {\n while (j != -1) {\n if (s(ret(j) + 1) == s(i)) {\n break\n }\n j = ret(j)\n }\n }\n if (j != -1) {\n ret.update(i, ret(j) + 1)\n }\n }\n return ret\n }\n\n def solve(s: StringOps, t: StringOps, virus: StringOps): String = {\n def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {\n if (x == 0 || y == 0) {\n return \"\"\n }\n if (rec(x)(y)(z) == 0) {\n return build(x - 1, y, z, rec)\n } else if (rec(x)(y)(z) == 1) {\n return build(x, y - 1, z, rec)\n } else {\n return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))\n }\n }\n val ns = s.length\n val nt = t.length\n val nv = virus.length\n val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)\n val kmp = kmpMatch(virus)\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n dp(i)(0)(0) = 0\n dp(0)(j)(0) = 0\n }\n }\n for (i <- 0 to ns - 1) {\n for (j <- 0 to nt - 1) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) != -1) {\n if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {\n rec(i + 1)(j)(k) = 0\n dp(i + 1)(j)(k) = dp(i)(j)(k)\n }\n if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {\n rec(i)(j + 1)(k) = 1\n dp(i)(j + 1)(k) = dp(i)(j)(k)\n }\n if (s(i) == t(j)) {\n var idx = k\n breakable {\n while (idx != -1) {\n if (virus(idx) == s(i)) {\n break\n }\n idx = kmp(idx)\n }\n }\n if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {\n rec(i + 1)(j + 1)(idx + 1) = -(k + 1)\n dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1\n }\n }\n }\n }\n }\n }\n var r = -1\n var x = -1\n var y = -1\n var z = -1\n for (i <- 0 to ns) {\n for (j <- 0 to nt) {\n for (k <- 0 to nv - 1) {\n if (dp(i)(j)(k) > r) {\n r = dp(i)(j)(k)\n x = i\n y = j\n z = k\n }\n }\n }\n }\n return if (r > 0) build(x, y, z, rec) else \"0\"\n }\n\n def main(args: Array[String]) {\n val s = readLine()\n val t = readLine()\n val virus = readLine()\n println(solve(s, t, virus))\n }\n\n}\n"}], "src_uid": "391c2abbe862139733fcb997ba1629b8"} {"nl": {"description": "Given $$$n$$$, find any array $$$a_1, a_2, \\ldots, a_n$$$ of integers such that all of the following conditions hold: $$$1 \\le a_i \\le 10^9$$$ for every $$$i$$$ from $$$1$$$ to $$$n$$$.$$$a_1 < a_2 < \\ldots <a_n$$$For every $$$i$$$ from $$$2$$$ to $$$n$$$, $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$It can be shown that such an array always exists under the constraints of the problem.", "input_spec": "The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case print $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ \u2014 the array you found. If there are multiple arrays satisfying all the conditions, print any of them.", "sample_inputs": ["3\n1\n2\n7"], "sample_outputs": ["1\n2 3\n111 1111 11111 111111 1111111 11111111 111111111"], "notes": "NoteIn the first test case, array $$$[1]$$$ satisfies all the conditions.In the second test case, array $$$[2, 3]$$$ satisfies all the conditions, as $$$2<3$$$ and $$$3$$$ is not divisible by $$$2$$$.In the third test case, array $$$[111, 1111, 11111, 111111, 1111111, 11111111, 111111111]$$$ satisfies all the conditions, as it's increasing and $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$ for any $$$i$$$ from $$$2$$$ to $$$7$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n\u2009\u00d7\u2009m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i,\u2009j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i,\u2009j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round. ", "input_spec": "The first line of input contains three integers n, m and q (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500 and 1\u2009\u2264\u2009q\u2009\u2264\u20095000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1\u2009\u2264\u2009i\u2009\u2264\u2009n and 1\u2009\u2264\u2009j\u2009\u2264\u2009m), the row number and the column number of the bear changing his state.", "output_spec": "After each round, print the current score of the bears.", "sample_inputs": ["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"], "sample_outputs": ["3\n4\n3\n3\n4"], "notes": null}, "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 = _\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}"}, {"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"} {"nl": {"description": "There are $$$n$$$ students standing in a circle in some order. The index of the $$$i$$$-th student is $$$p_i$$$. It is guaranteed that all indices of students are distinct integers from $$$1$$$ to $$$n$$$ (i.\u2009e. they form a permutation).Students want to start a round dance. A clockwise round dance can be started if the student $$$2$$$ comes right after the student $$$1$$$ in clockwise order (there are no students between them), the student $$$3$$$ comes right after the student $$$2$$$ in clockwise order, and so on, and the student $$$n$$$ comes right after the student $$$n - 1$$$ in clockwise order. A counterclockwise round dance is almost the same thing \u2014 the only difference is that the student $$$i$$$ should be right after the student $$$i - 1$$$ in counterclockwise order (this condition should be met for every $$$i$$$ from $$$2$$$ to $$$n$$$). For example, if the indices of students listed in clockwise order are $$$[2, 3, 4, 5, 1]$$$, then they can start a clockwise round dance. If the students have indices $$$[3, 2, 1, 4]$$$ in clockwise order, then they can start a counterclockwise round dance.Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 200$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 200$$$) \u2014 the number of students. The second line of the query contains a permutation of indices $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$), where $$$p_i$$$ is the index of the $$$i$$$-th student (in clockwise order). It is guaranteed that all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.\u2009e. they form a permutation).", "output_spec": "For each query, print the answer on it. If a round dance can be started with the given order of students, print \"YES\". Otherwise print \"NO\".", "sample_inputs": ["5\n4\n1 2 3 4\n3\n1 3 2\n5\n1 2 3 5 4\n1\n1\n5\n3 2 1 5 4"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "b27436086ead93397be748d8ebdbf19a"} {"nl": {"description": "A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.", "input_spec": "First line of the input contains the string s\u00a0\u2014 the coating that is present in the shop. Second line contains the string t\u00a0\u2014 the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.", "output_spec": "The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating. If the answer is not -1, then the following n lines should contain two integers xi and yi\u00a0\u2014 numbers of ending blocks in the corresponding piece. If xi\u2009\u2264\u2009yi then this piece is used in the regular order, and if xi\u2009>\u2009yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.", "sample_inputs": ["abc\ncbaabc", "aaabrytaaa\nayrat", "ami\nno"], "sample_outputs": ["2\n3 1\n1 3", "3\n1 1\n6 5\n8 7", "-1"], "notes": "NoteIn the first sample string \"cbaabc\" = \"cba\" + \"abc\".In the second sample: \"ayrat\" = \"a\" + \"yr\" + \"at\"."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Nauuo is a girl who loves playing cards.One day she was playing cards but found that the cards were mixed with some empty ones.There are $$$n$$$ cards numbered from $$$1$$$ to $$$n$$$, and they were mixed with another $$$n$$$ empty cards. She piled up the $$$2n$$$ cards and drew $$$n$$$ of them. The $$$n$$$ cards in Nauuo's hands are given. The remaining $$$n$$$ cards in the pile are also given in the order from top to bottom.In one operation she can choose a card in her hands and play it \u2014 put it at the bottom of the pile, then draw the top card from the pile.Nauuo wants to make the $$$n$$$ numbered cards piled up in increasing order (the $$$i$$$-th card in the pile from top to bottom is the card $$$i$$$) as quickly as possible. Can you tell her the minimum number of operations?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1\\le n\\le 2\\cdot 10^5$$$) \u2014 the number of numbered cards. The second line contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$0\\le a_i\\le n$$$) \u2014 the initial cards in Nauuo's hands. $$$0$$$ represents an empty card. The third line contains $$$n$$$ integers $$$b_1,b_2,\\ldots,b_n$$$ ($$$0\\le b_i\\le n$$$) \u2014 the initial cards in the pile, given in order from top to bottom. $$$0$$$ represents an empty card. It is guaranteed that each number from $$$1$$$ to $$$n$$$ appears exactly once, either in $$$a_{1..n}$$$ or $$$b_{1..n}$$$.", "output_spec": "The output contains a single integer \u2014 the minimum number of operations to make the $$$n$$$ numbered cards piled up in increasing order.", "sample_inputs": ["3\n0 2 0\n3 0 1", "3\n0 2 0\n1 0 3", "11\n0 0 0 5 0 0 0 4 0 0 11\n9 2 6 0 8 1 7 0 3 0 10"], "sample_outputs": ["2", "4", "18"], "notes": "NoteExample 1We can play the card $$$2$$$ and draw the card $$$3$$$ in the first operation. After that, we have $$$[0,3,0]$$$ in hands and the cards in the pile are $$$[0,1,2]$$$ from top to bottom.Then, we play the card $$$3$$$ in the second operation. The cards in the pile are $$$[1,2,3]$$$, in which the cards are piled up in increasing order.Example 2Play an empty card and draw the card $$$1$$$, then play $$$1$$$, $$$2$$$, $$$3$$$ in order."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A, B = na(N)\n\n def endsWithAsc: Boolean = {\n REP_r(N) { i =>\n if (i + 1 < N && B(i) + 1 != B(i + 1)) return false\n if (B(i) == 1) return true\n }\n true\n }\n\n val hands = Array.ofDim[Boolean](N + 1)\n\n def test1: Boolean = {\n val toFill = B.indexWhere(_ == 1)\n test2(toFill)\n }\n\n def test2(x: Int): Boolean = {\n import java.util\n util.Arrays.fill(hands, false)\n REP(N) { i =>\n if (A(i) != 0) hands(A(i)) = true\n }\n REP(x) { i =>\n if (i >= x - N) {\n val cur = i - (x - N) + 1\n if (!hands(cur)) return false\n hands(cur) = false\n }\n if (i < N && B(i) != 0) hands(B(i)) = true\n }\n true\n }\n\n val ans = if (B.forall(_ == 0)) N\n else if (endsWithAsc && test1) {\n B.indexWhere(_ == 1)\n } else {\n findMin(test2, N, 2 * N)\n }\n\n out.println(ans)\n }\n\n def findMin(f: Int => Boolean, min: Int, max: Int): Int = {\n var l = min - 1\n var h = max\n while(h - l > 1) {\n val x = (h + l) / 2\n if (f(x)) h = x\n else l = x\n }\n h\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val _, B = na(N)\n val V = Array.ofDim[Int](N + 1)\n\n if (B.forall(_ == 0)) out.println(N)\n else {\n var cont = -1\n REP(N) { i =>\n if (B(i) == 1) {\n cont = i\n } else if (cont >= 0 && B(i - 1) + 1 != B(i)) {\n cont = -1\n }\n }\n\n if (cont > 0 && B(cont - 1) == B.last + 1) cont = -1\n\n debug(s\"cont:$cont\")\n\n if (cont >= 0) {\n out.println(cont)\n } else {\n REP(N) { i =>\n if (B(i) > 0) {\n V(B(i)) = i + 2 + (N - B(i))\n }\n }\n debug(V)\n out.println(V.max)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val _, B = na(N)\n val V = Array.ofDim[Int](N + 1)\n\n if (B.forall(_ == 0)) out.println(N)\n else {\n var cont = false\n REP(N) { i =>\n if (B(i) == 1) {\n cont = true\n } else if (cont && B(i - 1) + 1 != B(i)) {\n cont = false\n }\n\n if (B(i) > 0 && !cont) {\n V(B(i)) = i + 2 + (N - B(i))\n }\n }\n debug(V)\n out.println(V.max)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val _, B = na(N)\n val V = Array.ofDim[Int](N + 1)\n\n if (B.forall(_ == 0)) out.println(N)\n else {\n var cont = -1\n REP(N) { i =>\n if (B(i) == 1) {\n cont = i\n } else if (cont >= 0 && B(i - 1) + 1 != B(i)) {\n cont = -1\n }\n }\n\n debug(s\"cont:$cont\")\n\n val cnt = if (cont >= 0) cont else N\n\n REP(cnt) { i =>\n if (B(i) > 0) {\n V(B(i)) = i + 2 + (N - B(i))\n }\n }\n debug(V)\n out.println(max(V.max, cont))\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A, B = na(N)\n\n def endsWithAsc: Boolean = {\n REP_r(N) { i =>\n if (i + 1 < N && B(i) + 1 != B(i + 1)) return false\n if (B(i) == 1) return true\n }\n true\n }\n\n val hands = Array.ofDim[Boolean](N + 1)\n\n def test1: Boolean = {\n val toFill = B.indexWhere(_ == 1)\n test2(toFill)\n }\n\n def test2(x: Int): Boolean = {\n import java.util\n util.Arrays.fill(hands, false)\n REP(N) { i =>\n if (A(i) != 0) hands(A(i)) = true\n }\n REP(x) { i =>\n if (i >= x - N) {\n val cur = i - (x - N) + 1\n if (!hands(cur)) return false\n hands(cur) = false\n }\n if (i < N && B(i) != 0) hands(B(i)) = true\n }\n true\n }\n\n val ans = if (B.forall(_ == 0)) N\n else if (endsWithAsc && test1) {\n B.indexWhere(_ == 1)\n } else {\n findMin(test2, N + 1, 2 * N)\n }\n\n out.println(ans)\n }\n\n def findMin(f: Int => Boolean, min: Int, max: Int): Int = {\n var l = min - 1\n var h = max\n while(h - l > 1) {\n val x = (h + l) / 2\n if (f(x)) h = x\n else l = x\n }\n h\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val _, B = na(N)\n val V = Array.ofDim[Int](N + 1)\n\n if (B.forall(_ == 0)) out.println(N)\n else {\n var cont = -1\n REP(N) { i =>\n if (B(i) == 1) {\n cont = i\n } else if (cont >= 0 && B(i - 1) + 1 != B(i)) {\n cont = -1\n }\n }\n\n debug(s\"cont:$cont\")\n\n if (cont >= 0) {\n out.println(cont)\n } else {\n REP(N) { i =>\n if (B(i) > 0) {\n V(B(i)) = i + 2 + (N - B(i))\n }\n }\n debug(V)\n out.println(V.max)\n }\n }\n }\n}"}], "src_uid": "ec092209aa9f45409e5aa01d7fc784e1"} {"nl": {"description": "Polycarpus has a hobby \u2014 he develops an unusual social network. His work is almost completed, and there is only one more module to implement \u2014 the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0\u2009<\u2009t2\u2009-\u2009t1\u2009\u2264\u2009d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.", "input_spec": "The first line of the input contains two integers n and d (1\u2009\u2264\u2009n,\u2009d\u2009\u2264\u20091000). The next n lines contain the messages log. The i-th line contains one line of the log formatted as \"Ai Bi ti\" (without the quotes), which means that user Ai sent a message to user Bi at time ti (1\u2009\u2264\u2009i\u2009\u2264\u2009n). Ai and Bi are non-empty strings at most 20 characters long, consisting of lowercase letters ('a' ... 'z'), and ti is an integer (0\u2009\u2264\u2009ti\u2009\u2264\u200910000). It is guaranteed that the lines are given in non-decreasing order of ti's and that no user sent a message to himself. The elements in the lines are separated by single spaces.", "output_spec": "In the first line print integer k \u2014 the number of pairs of friends. In the next k lines print pairs of friends as \"Ai Bi\" (without the quotes). You can print users in pairs and the pairs themselves in any order. Each pair must be printed exactly once.", "sample_inputs": ["4 1\nvasya petya 1\npetya vasya 2\nanya ivan 2\nivan anya 4", "1 1000\na b 0"], "sample_outputs": ["1\npetya vasya", "0"], "notes": "NoteIn the first sample test case Vasya and Petya are friends because their messages' sending times are one second apart. Anya and Ivan are not, because their messages' sending times differ by more than one second."}, "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) // \u0423\u0434\u0430\u043b\u044f\u0435\u043c \u0443\u0441\u0442\u0430\u0440\u0435\u0432\u0448\u0438\u0435 \u043f\u0430\u0440\u044b\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}"}, {"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"}], "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) // \u0423\u0434\u0430\u043b\u044f\u0435\u043c \u0443\u0441\u0442\u0430\u0440\u0435\u0432\u0448\u0438\u0435 \u043f\u0430\u0440\u044b\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"} {"nl": {"description": "Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1,\u2009a2,\u2009...,\u2009an are good.Now she is interested in good sequences. A sequence x1,\u2009x2,\u2009...,\u2009xk is called good if it satisfies the following three conditions: The sequence is strictly increasing, i.e. xi\u2009<\u2009xi\u2009+\u20091 for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009k\u2009-\u20091). No two adjacent elements are coprime, i.e. gcd(xi,\u2009xi\u2009+\u20091)\u2009>\u20091 for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009k\u2009-\u20091) (where gcd(p,\u2009q) denotes the greatest common divisor of the integers p and q). All elements of the sequence are good integers. Find the length of the longest good sequence.", "input_spec": "The input consists of two lines. The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of good integers. The second line contains a single-space separated list of good integers a1,\u2009a2,\u2009...,\u2009an in strictly increasing order (1\u2009\u2264\u2009ai\u2009\u2264\u2009105;\u00a0ai\u2009<\u2009ai\u2009+\u20091).", "output_spec": "Print a single integer \u2014 the length of the longest good sequence.", "sample_inputs": ["5\n2 3 4 6 9", "9\n1 2 3 5 6 7 8 9 10"], "sample_outputs": ["4", "4"], "notes": "NoteIn the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4."}, "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 \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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \\le 2$$$ and $$$a_5=1 \\le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \\le 5$$$, $$$a_3=4 \\le 5$$$ and $$$a_4=5 \\le 5$$$); the $$$6$$$-th granny cannot be called into the yard \u00a0\u2014 therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies). ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2\\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer $$$k$$$ ($$$1 \\le k \\le n + 1$$$) \u2014 the maximum possible number of grannies in the courtyard.", "sample_inputs": ["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"], "sample_outputs": ["6\n1\n6\n4"], "notes": "NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total."}, "positive_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 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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "718cea81f609055cece58cae5310f703"} {"nl": {"description": "You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \\times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \\times x$$$ subgrid or a vertical $$$x \\times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \\times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 2\\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \\le r, c \\le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: \"A\" means that the dominant religion is Beingawesomeism; \"P\" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain \"A\" or \"P\" characters. It is guaranteed that the sum of the $$$r \\cdot c$$$ in a single file is at most $$$3 \\cdot 10^6$$$.", "output_spec": "For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string \"MORTAL\" (without quotes) if it is impossible to do so. ", "sample_inputs": ["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"], "sample_outputs": ["2\n1\nMORTAL\n4"], "notes": "NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is \"MORTAL\"."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve2(): Unit = {\n val R, C = ni()\n val g = nm_c(R, C)\n def allA = map(R) { i =>\n g(i).forall(_ == 'A')\n }.reduce(_ && _)\n\n if (allA) {\n out.println(0)\n return\n }\n\n def allP = map(R) { i =>\n g(i).forall(_ == 'P')\n }.reduce(_ && _)\n\n if (allA) {\n out.println(0)\n }\n else if (allP) {\n out.println(\"MORTAL\")\n } else {\n out.println(solve3(R, C, g))\n }\n }\n\n def cnt(N: Int, M: Int)(g: Int => Int => Char) = {\n var res = 1e9.toInt\n\n def allA(i: Int): Boolean = {\n var allA = true\n REP(M) { j =>\n allA &&= g(i)(j) == 'A'\n }\n allA\n }\n\n def containsA(i: Int): Boolean = {\n var ok = false\n REP(M) { j =>\n ok ||= g(i)(j) == 'A'\n }\n ok\n }\n\n REP(N) { i =>\n val cnt = if (allA(i)) {\n 2\n } else if (g(i)(0) == 'A' || g(i)(M - 1) == 'A') {\n 3\n } else {\n if (containsA(i))\n 4\n else\n 1e9.toInt\n }\n\n if (i == 0 || i == N - 1)\n res = min(res, cnt - 1)\n else\n res = min(res, cnt)\n }\n res\n }\n\n def solve3(R: Int, C: Int, g: Array[Array[Char]]): Int = {\n var ans = 1e9.toInt\n ans = min(ans, cnt(R, C) { r => c =>\n g(r)(c)\n })\n ans = min(ans, cnt(C, R) { c => r =>\n g(r)(c)\n })\n ans\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n}"}], "negative_code": [], "src_uid": "da18ca9f125d1524e7c0a2637b1fa3df"} {"nl": {"description": "Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire. Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i\u2009-\u20091, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i\u2009+\u20091, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.", "input_spec": "The first line of the input contains an integer n, (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The next line contains a list of space-separated integers a1,\u2009a2,\u2009...,\u2009an, (0\u2009\u2264\u2009ai\u2009\u2264\u2009100). The third line contains an integer m, (0\u2009\u2264\u2009m\u2009\u2264\u2009100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1\u2009\u2264\u2009xi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment.", "output_spec": "On the i-th line of the output print the number of birds on the i-th wire.", "sample_inputs": ["5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6", "3\n2 4 1\n1\n2 2"], "sample_outputs": ["0\n12\n5\n0\n16", "3\n0\n3"], "notes": null}, "positive_code": [{"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}"}, {"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": "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"}, {"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 }"}], "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"} {"nl": {"description": "You are given a description of a depot. It is a rectangular checkered field of n\u2009\u00d7\u2009m size. Each cell in a field can be empty (\".\") or it can be occupied by a wall (\"*\"). You have one bomb. If you lay the bomb at the cell (x,\u2009y), then after triggering it will wipe out all walls in the row x and all walls in the column y.You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall.", "input_spec": "The first line contains two positive integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the number of rows and columns in the depot field. The next n lines contain m symbols \".\" and \"*\" each\u00a0\u2014 the description of the field. j-th symbol in i-th of them stands for cell (i,\u2009j). If the symbol is equal to \".\", then the corresponding cell is empty, otherwise it equals \"*\" and the corresponding cell is occupied by a wall.", "output_spec": "If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print \"NO\" in the first line (without quotes). Otherwise print \"YES\" (without quotes) in the first line and two integers in the second line\u00a0\u2014 the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them.", "sample_inputs": ["3 4\n.*..\n....\n.*..", "3 3\n..*\n.*.\n*..", "6 5\n..*..\n..*..\n*****\n..*..\n..*..\n..*.."], "sample_outputs": ["YES\n1 2", "NO", "YES\n3 3"], "notes": null}, "positive_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 + 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}"}, {"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": "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": "\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 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": "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": "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"}, {"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"}], "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"} {"nl": {"description": "Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!", "input_spec": "The first line of the input contains two space-separated integers, n and d (1\u2009\u2264\u2009n\u2009\u2264\u2009105, ) \u2014 the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively. Next n lines contain the descriptions of Kefa's friends, the (i\u2009+\u20091)-th line contains the description of the i-th friend of type mi, si (0\u2009\u2264\u2009mi,\u2009si\u2009\u2264\u2009109) \u2014 the amount of money and the friendship factor, respectively. ", "output_spec": "Print the maximum total friendship factir that can be reached.", "sample_inputs": ["4 5\n75 5\n0 100\n150 20\n75 1", "5 100\n0 7\n11 32\n99 10\n46 8\n87 54"], "sample_outputs": ["100", "111"], "notes": "NoteIn the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends."}, "positive_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 - 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}"}, {"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(_.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 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"}, {"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 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}"}], "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"} {"nl": {"description": "Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $$$0$$$. Also, let's say that the train will visit $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$ along its way, and that Alexey destination is the station $$$n$$$.Alexey learned from the train schedule $$$n$$$ integer pairs $$$(a_i, b_i)$$$ where $$$a_i$$$ is the expected time of train's arrival at the $$$i$$$-th station and $$$b_i$$$ is the expected time of departure.Also, using all information he has, Alexey was able to calculate $$$n$$$ integers $$$tm_1, tm_2, \\dots, tm_n$$$ where $$$tm_i$$$ is the extra time the train need to travel from the station $$$i - 1$$$ to the station $$$i$$$. Formally, the train needs exactly $$$a_i - b_{i-1} + tm_i$$$ time to travel from station $$$i - 1$$$ to station $$$i$$$ (if $$$i = 1$$$ then $$$b_0$$$ is the moment the train leave the terminal, and it's equal to $$$0$$$).The train leaves the station $$$i$$$, if both conditions are met: it's on the station for at least $$$\\left\\lceil \\frac{b_i - a_i}{2} \\right\\rceil$$$ units of time (division with ceiling); current time $$$\\ge b_i$$$. Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station $$$n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of stations. Next $$$n$$$ lines contain two integers each: $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i < b_i \\le 10^6$$$). It's guaranteed that $$$b_i < a_{i+1}$$$. Next line contains $$$n$$$ integers $$$tm_1, tm_2, \\dots, tm_n$$$ ($$$0 \\le tm_i \\le 10^6$$$).", "output_spec": "For each test case, print one integer\u00a0\u2014 the time of Alexey's arrival at the last station.", "sample_inputs": ["2\n2\n2 4\n10 12\n0 2\n5\n1 4\n7 8\n9 10\n13 15\n19 20\n1 2 3 4 5"], "sample_outputs": ["12\n32"], "notes": "NoteIn the first test case, Alexey arrives at station $$$1$$$ without any delay at the moment $$$a_1 = 2$$$ (since $$$tm_1 = 0$$$). After that, he departs at moment $$$b_1 = 4$$$. Finally, he arrives at station $$$2$$$ with $$$tm_2 = 2$$$ extra time, or at the moment $$$12$$$.In the second test case, Alexey arrives at the first station with $$$tm_1 = 1$$$ extra time, or at moment $$$2$$$. The train, from one side, should stay at the station at least $$$\\left\\lceil \\frac{b_1 - a_1}{2} \\right\\rceil = 2$$$ units of time and from the other side should depart not earlier than at moment $$$b_1 = 4$$$. As a result, the trains departs right at the moment $$$4$$$.Using the same logic, we can figure out that the train arrives at the second station at the moment $$$9$$$ and departs at the moment $$$10$$$; at the third station: arrives at $$$14$$$ and departs at $$$15$$$; at the fourth: arrives at $$$22$$$ and departs at $$$23$$$. And, finally, arrives at the fifth station at $$$32$$$."}, "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, bs = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n val a, b = nextInt\n as(i) = a\n bs(i) = b\n }\n val tms = nextInts(n)\n\n var t = 0\n var res = 0\n var prevB = 0\n for (i <- 0 until n) {\n t = t + (as(i) - prevB + tms(i))\n res = t\n t = Math.max(bs(i), t + (bs(i) - as(i) + 1) / 2)\n prevB = bs(i)\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": [], "src_uid": "42840fc873369e0d0d6a4ad24a43f5a6"} {"nl": {"description": "Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password k times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100)\u00a0\u2014 the number of Vanya's passwords and the number of failed tries, after which the access to the site is blocked for 5 seconds. The next n lines contains passwords, one per line\u00a0\u2014 pairwise distinct non-empty strings consisting of latin letters and digits. Each password length does not exceed 100 characters. The last line of the input contains the Vanya's Codehorses password. It is guaranteed that the Vanya's Codehorses password is equal to some of his n passwords.", "output_spec": "Print two integers\u00a0\u2014 time (in seconds), Vanya needs to be authorized to Codehorses in the best case for him and in the worst case respectively.", "sample_inputs": ["5 2\ncba\nabc\nbb1\nabC\nABC\nabc", "4 100\n11\n22\n1\n2\n22"], "sample_outputs": ["1 15", "3 4"], "notes": "NoteConsider the first sample case. As soon as all passwords have the same length, Vanya can enter the right password at the first try as well as at the last try. If he enters it at the first try, he spends exactly 1 second. Thus in the best case the answer is 1. If, at the other hand, he enters it at the last try, he enters another 4 passwords before. He spends 2 seconds to enter first 2 passwords, then he waits 5 seconds as soon as he made 2 wrong tries. Then he spends 2 more seconds to enter 2 wrong passwords, again waits 5 seconds and, finally, enters the correct password spending 1 more second. In summary in the worst case he is able to be authorized in 15 seconds.Consider the second sample case. There is no way of entering passwords and get the access to the site blocked. As soon as the required password has length of 2, Vanya enters all passwords of length 1 anyway, spending 2 seconds for that. Then, in the best case, he immediately enters the correct password and the answer for the best case is 3, but in the worst case he enters wrong password of length 2 and only then the right one, spending 4 seconds at all."}, "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 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"}, {"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"} {"nl": {"description": "Polycarp lives on a coordinate line at the point $$$x = 0$$$. He goes to his friend that lives at the point $$$x = a$$$. Polycarp can move only from left to right, he can pass one unit of length each second.Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $$$n$$$ non-intersecting segments, the $$$i$$$-th segment which is in the rain is represented as $$$[l_i, r_i]$$$ ($$$0 \\le l_i < r_i \\le a$$$).There are $$$m$$$ umbrellas lying on the line, the $$$i$$$-th umbrella is located at point $$$x_i$$$ ($$$0 \\le x_i \\le a$$$) and has weight $$$p_i$$$. When Polycarp begins his journey, he doesn't have any umbrellas.During his journey from $$$x = 0$$$ to $$$x = a$$$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $$$x$$$ to $$$x + 1$$$ if a segment $$$[x, x + 1]$$$ is in the rain (i.e. if there exists some $$$i$$$ such that $$$l_i \\le x$$$ and $$$x + 1 \\le r_i$$$).The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.Can Polycarp make his way from point $$$x = 0$$$ to point $$$x = a$$$? If yes, find the minimum total fatigue after reaching $$$x = a$$$, if Polycarp picks up and throws away umbrellas optimally.", "input_spec": "The first line contains three integers $$$a$$$, $$$n$$$ and $$$m$$$ ($$$1 \\le a, m \\le 2000, 1 \\le n \\le \\lceil\\frac{a}{2}\\rceil$$$) \u2014 the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \\le l_i < r_i \\le a$$$) \u2014 the borders of the $$$i$$$-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments $$$i$$$ and $$$j$$$ either $$$r_i < l_j$$$ or $$$r_j < l_i$$$. Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$p_i$$$ ($$$0 \\le x_i \\le a$$$, $$$1 \\le p_i \\le 10^5$$$) \u2014 the location and the weight of the $$$i$$$-th umbrella.", "output_spec": "Print \"-1\" (without quotes) if Polycarp can't make his way from point $$$x = 0$$$ to point $$$x = a$$$. Otherwise print one integer \u2014 the minimum total fatigue after reaching $$$x = a$$$, if Polycarp picks up and throws away umbrellas optimally.", "sample_inputs": ["10 2 4\n3 7\n8 10\n0 10\n3 4\n8 1\n1 2", "10 1 1\n0 9\n0 5", "10 1 1\n0 9\n1 5"], "sample_outputs": ["14", "45", "-1"], "notes": "NoteIn the first example the only possible strategy is to take the fourth umbrella at the point $$$x = 1$$$, keep it till the point $$$x = 7$$$ (the total fatigue at $$$x = 7$$$ will be equal to $$$12$$$), throw it away, move on from $$$x = 7$$$ to $$$x = 8$$$ without an umbrella, take the third umbrella at $$$x = 8$$$ and keep it till the end (the total fatigue at $$$x = 10$$$ will be equal to $$$14$$$). In the second example the only possible strategy is to take the first umbrella, move with it till the point $$$x = 9$$$, throw it away and proceed without an umbrella till the end."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of laptops. Next n lines contain two integers each, ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. ", "output_spec": "If Alex is correct, print \"Happy Alex\", otherwise print \"Poor Alex\" (without the quotes).", "sample_inputs": ["2\n1 2\n2 1"], "sample_outputs": ["Happy Alex"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \\times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \\times l$$$ or $$$l \\times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake \"over the top\" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u2014 the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \\le n,m \\le 2000$$$)\u00a0\u2014 length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\\cdot10^6$$$.", "output_spec": "Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \\le k \\le 26$$$)\u00a0\u2014 number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$\u00a0\u2014 coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \\le r_{1,i}, r_{2,i} \\le n$$$, $$$1 \\le c_{1,i}, c_{2,i} \\le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.", "sample_inputs": ["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"], "sample_outputs": ["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"], "notes": null}, "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[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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n class Axis {\n def set(v: Int, i: Int): Unit = {\n if (empty) {\n ok = true\n this.v = v\n } else if (this.v != v) {\n ok = false\n }\n ms = min(ms, i)\n mx = max(mx, i)\n }\n\n def empty: Boolean = v == -1\n\n def reset(): Unit = {\n ok = false\n v = -1\n ms = 1e4.toInt\n mx = 0\n }\n\n var ok: Boolean = false\n var v: Int = 0\n var ms: Int = 0\n var mx: Int = 0\n\n override def toString: String = s\"ok:$ok v:$v ms:$ms mx:$mx\"\n\n def answer = Answer(v + 1, ms + 1, v + 1, mx + 1)\n }\n\n case class Answer(r1: Int, c1: Int, r2: Int, c2: Int) {\n def rotate: Answer = Answer(c1, r1, c2, r2)\n }\n\n val H, V = Array.fill[Axis](26)(new Axis)\n\n def solve2(): Boolean = {\n REP(26) { i =>\n H(i).reset()\n V(i).reset()\n }\n val N, M = ni()\n val g = nm_c(N, M)\n REP(N) { i =>\n REP(M) { j =>\n if (g(i)(j) != '.') {\n val c = g(i)(j) - 'a'\n H(c).set(i, j)\n V(c).set(j, i)\n }\n }\n }\n\n DEBUG {\n debug(\"H\")\n H.foreach(a => debug(a.toString))\n debug(\"V\")\n V.foreach(a => debug(a.toString))\n }\n\n def test(c: Int, ax: Axis)(f: Int => Char): Boolean = {\n TO(ax.ms, ax.mx) { i =>\n val c2 = f(i)\n if (c2 == '.' || c2 - 'a' < c) return false\n }\n true\n }\n\n var ok = true\n REP(26) { i =>\n // \u51fa\u3066\u3053\u306a\u3044 OR \u3069\u3063\u3061\u304b\u306e\u8ef8\u304c\u6b63\u89e3\n ok &&= H(i).empty ||\n (H(i).ok && test(i, H(i))(g(H(i).v)(_))) ||\n (V(i).ok && test(i, V(i))(g(_)(V(i).v)))\n }\n if (!ok) return false\n\n out.println(\"YES\")\n var last = -1\n REP(26) { i =>\n // \u30c1\u30a7\u30c3\u30af\u6e08\u307f\u306a\u306e\u3067\u3001\u3053\u306e\u6642\u70b9\u3067\u306fok\u304b\u3069\u3046\u304b\u3060\u3051\u3067\u3044\u3044\n if (H(i).ok || V(i).ok) last = i\n }\n out.println(last + 1)\n REP(last + 1) { i =>\n val ix = if (H(i).ok || V(i).ok) i else last // \u4e0a\u66f8\u304d\u3055\u308c\u308b\u86c7\u306f\u6700\u5f8c\u306e\u6587\u5b57\u3068\u540c\u3058\u7dda\u306b\u3057\u3066\u304a\u304f\n val ans = if (H(ix).ok) H(ix).answer else V(ix).answer.rotate\n out.println(s\"${ans.r1} ${ans.c1} ${ans.r2} ${ans.c2}\")\n }\n\n true\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n // \u5931\u6557\u306e\u3068\u304d\u3060\u3051\u3053\u3063\u3061\u3067\u51fa\u529b\u3059\u308b\n if (!solve2()) {\n out.println(\"NO\")\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "f34d21b9568c758cacc1d00af1316c86"} {"nl": {"description": "A string is called palindrome if it reads the same from left to right and from right to left. For example \"kazak\", \"oo\", \"r\" and \"mikhailrubinchikkihcniburliahkim\" are palindroms, but strings \"abb\" and \"ij\" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.", "input_spec": "The only line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20092\u00b7105) consisting of only lowercase Latin letters.", "output_spec": "Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.", "sample_inputs": ["aabc", "aabcd"], "sample_outputs": ["abba", "abcba"], "notes": null}, "positive_code": [{"source_code": "/**\n * Created by katerinaglushchenko on 9/18/16.\n */\nobject Task3 {\n def main(args: Array[String]) {\n val str = readLine()\n val sorted = str.sorted\n val notHasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 1) Some(s._2.head) else None).toList.sorted\n val hasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 0) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else if (s._2.length >= 3) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else None).flatten.toList\n val rest = notHasPair.take(notHasPair.size / 2)\n val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else \"\"\n val half = (hasPair ++ rest).sorted\n println((half ++ center ++ half.reverse).mkString(\"\"))\n }\n}\n"}], "negative_code": [{"source_code": "object Task3 {\n def main(args: Array[String]) {\n val str = readLine()\n val p = str.sorted.zipWithIndex.partition(_._2 % 2 == 0)\n val p1 = p._1.map(_._1)\n val p2 = p._2.map(_._1)\n\n val sorted = str.sorted\n val hasPair = sorted.zipWithIndex.flatMap(s => if (s._2 + 1 < sorted.length && sorted.charAt(s._2 + 1) == s._1) Some(s._1) else None)\n val notHasPair = sorted.toCharArray.toSet -- hasPair.toSet\n\n val p11 = hasPair\n val p22 = hasPair\n\n val center = if(notHasPair.size%2==1) notHasPair.toList(notHasPair.size/2).toString else \"\"\n val rest = if(notHasPair.size%2==1) notHasPair - center.head else notHasPair\n val gr = rest.grouped(2).toList.map(s=>s.head)\n\n println((p11++gr++center.toCharArray++gr++p22.reverse).mkString(\"\"))\n }\n}\n"}, {"source_code": "/**\n * Created by katerinaglushchenko on 9/18/16.\n */\nobject Task3 {\n def main(args: Array[String]) {\n val str = readLine()\n if(isPalindrom(str))\n println(str)\n else {\n val p = str.sorted.zipWithIndex.partition(_._2 % 2 == 0)\n \n val sorted = str.sorted\n val hasPair = sorted.zipWithIndex.flatMap(s => if (s._2 + 1 < sorted.length && sorted.charAt(s._2 + 1) == s._1) Some(s._1) else None)\n val notHasPair = sorted.toCharArray.toSet -- hasPair.toSet\n\n val p11 = hasPair\n val p22 = hasPair\n\n val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else \"\"\n val rest = if (notHasPair.size % 2 == 1) notHasPair - center.head else notHasPair\n println(\"center \" + center)\n val gr = rest.grouped(2).toList.map(s => s.head)\n gr.foreach(r => println(r))\n\n println((p11 ++ gr ++ center.toCharArray ++ gr ++ p22.reverse).mkString(\"\"))\n }\n }\n\n def isPalindrom(str: String) = {\n val center1 = str.length / 2\n val center2 = if ((str.length % 2) == 1) (str.length / 2) + 1 else str.length / 2\n val parts = List(str.substring(0, center1), str.substring(center2, str.length))\n parts(0) == parts(1).reverse\n }\n}\n"}, {"source_code": "object Task3 {\n def main(args: Array[String]) {\n val str = readLine()\n val sorted = str.sorted\n val notHasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 1) Some(s._2.head) else None).toList\n val hasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 0) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else if (s._2.length >= 3) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else None).flatten.toList\n val rest = notHasPair.take(notHasPair.size / 2)\n val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else \"\"\n val half = (hasPair ++ rest).sorted\n println((half ++ center ++ half.reverse).mkString(\"\"))\n }\n}\n"}, {"source_code": "object Task3 {\n def main(args: Array[String]) {\n val str = readLine()\n if(isPalindrom(str))\n println(str)\n else {\n val p = str.sorted.zipWithIndex.partition(_._2 % 2 == 0)\n\n val sorted = str.sorted\n val hasPair = sorted.zipWithIndex.flatMap(s => if (s._2 + 1 < sorted.length && sorted.charAt(s._2 + 1) == s._1) Some(s._1) else None)\n val notHasPair = sorted.toCharArray.toSet -- hasPair.toSet\n\n val p11 = hasPair\n val p22 = hasPair\n\n val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else \"\"\n val rest = if (notHasPair.size % 2 == 1) notHasPair - center.head else notHasPair\n val gr = rest.grouped(2).toList.map(s => s.head)\n \n println((p11 ++ gr ++ center.toCharArray ++ gr ++ p22.reverse).mkString(\"\"))\n }\n }\n\n def isPalindrom(str: String) = {\n val center1 = str.length / 2\n val center2 = if ((str.length % 2) == 1) (str.length / 2) + 1 else str.length / 2\n val parts = List(str.substring(0, center1), str.substring(center2, str.length))\n parts(0) == parts(1).reverse\n }\n}\n"}], "src_uid": "f996224809df700265d940b12622016f"} {"nl": {"description": "A Martian boy is named s \u2014 he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=\u00ababa\u00bb, then strings \u00abbaobab\u00bb, \u00abaabbaa\u00bb, \u00abhelloabahello\u00bb make him very happy and strings \u00abaab\u00bb, \u00abbaaa\u00bb and \u00abhelloabhello\u00bb do not.However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.", "input_spec": "The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters. The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 106 letters.", "output_spec": "Print the sought number of ways to cut string t in two so that each part made s happy. ", "sample_inputs": ["aba\nbaobababbah", "mars\nsunvenusearthmarsjupitersaturnuranusneptune"], "sample_outputs": ["2", "0"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Bob is playing a game named \"Walk on Matrix\".In this game, player is given an $$$n \\times m$$$ matrix $$$A=(a_{i,j})$$$, i.e. the element in the $$$i$$$-th row in the $$$j$$$-th column is $$$a_{i,j}$$$. Initially, player is located at position $$$(1,1)$$$ with score $$$a_{1,1}$$$. To reach the goal, position $$$(n,m)$$$, player can move right or down, i.e. move from $$$(x,y)$$$ to $$$(x,y+1)$$$ or $$$(x+1,y)$$$, as long as player is still on the matrix.However, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.Bob can't wait to find out the maximum score he can get using the tool he recently learnt \u00a0\u2014 dynamic programming. Here is his algorithm for this problem. However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix $$$A$$$. Thus, for any given non-negative integer $$$k$$$, he wants to find out an $$$n \\times m$$$ matrix $$$A=(a_{i,j})$$$ such that $$$1 \\le n,m \\le 500$$$ (as Bob hates large matrix); $$$0 \\le a_{i,j} \\le 3 \\cdot 10^5$$$ for all $$$1 \\le i\\le n,1 \\le j\\le m$$$ (as Bob hates large numbers); the difference between the maximum score he can get and the output of his algorithm is exactly $$$k$$$. It can be shown that for any given integer $$$k$$$ such that $$$0 \\le k \\le 10^5$$$, there exists a matrix satisfying the above constraints.Please help him with it!", "input_spec": "The only line of the input contains one single integer $$$k$$$ ($$$0 \\le k \\le 10^5$$$).", "output_spec": "Output two integers $$$n$$$, $$$m$$$ ($$$1 \\le n,m \\le 500$$$) in the first line, representing the size of the matrix. Then output $$$n$$$ lines with $$$m$$$ integers in each line, $$$a_{i,j}$$$ in the $$$(i+1)$$$-th row, $$$j$$$-th column.", "sample_inputs": ["0", "1"], "sample_outputs": ["1 1\n300000", "3 4\n7 3 3 1\n4 8 3 6\n7 7 7 3"], "notes": "NoteIn the first example, the maximum score Bob can achieve is $$$300000$$$, while the output of his algorithm is $$$300000$$$.In the second example, the maximum score Bob can achieve is $$$7\\&3\\&3\\&3\\&7\\&3=3$$$, while the output of his algorithm is $$$2$$$."}, "positive_code": [{"source_code": "object D extends App {\n val k = scala.io.StdIn.readInt()\n val a = 1 << 17\n\n println(\"2 3\")\n println(s\"${a ^ k} $a 0\")\n println(s\"$k ${a ^ k} $k\")\n}\n"}], "negative_code": [], "src_uid": "fc0442e5cda2498a1818702e5e3eeec4"} {"nl": {"description": "You are given an undirected weighted connected graph with $$$n$$$ vertices and $$$m$$$ edges without loops and multiple edges.The $$$i$$$-th edge is $$$e_i = (u_i, v_i, w_i)$$$; the distance between vertices $$$u_i$$$ and $$$v_i$$$ along the edge $$$e_i$$$ is $$$w_i$$$ ($$$1 \\le w_i$$$). The graph is connected, i.\u2009e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $$$1$$$. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is $$$k$$$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $$$k$$$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5, n - 1 \\le m \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices and the number of edges in the initial graph. The next $$$m$$$ lines contain three integers each. The $$$i$$$-th line contains the description of the $$$i$$$-th edge $$$e_i$$$. It is denoted by three integers $$$u_i, v_i$$$ and $$$w_i$$$ ($$$1 \\le u_i, v_i \\le n, u_i \\ne v_i, 1 \\le w \\le 10^9$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices connected by the $$$i$$$-th edge and $$$w_i$$$ is the weight of this edge. It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $$$i$$$ from $$$1$$$ to $$$m$$$ $$$u_i \\ne v_i$$$ and for each unordered pair of vertices $$$(u, v)$$$ there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected.", "output_spec": "Print one integer \u2014 the minimum number of operations to unify MST of the initial graph without changing the cost of MST.", "sample_inputs": ["8 10\n1 2 1\n2 3 2\n2 4 5\n1 4 2\n6 3 3\n6 1 3\n3 5 2\n3 7 1\n4 8 1\n6 2 4", "4 3\n2 1 3\n4 3 4\n2 4 1", "3 3\n1 2 1\n2 3 2\n1 3 3", "3 3\n1 2 1\n2 3 3\n1 3 3", "1 0", "5 6\n1 2 2\n2 3 1\n4 5 3\n2 4 2\n1 4 2\n1 5 3"], "sample_outputs": ["1", "0", "0", "1", "0", "2"], "notes": "NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge $$$(1, 6)$$$ or $$$(6, 3)$$$ by $$$1$$$ to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges $$$(1, 5)$$$ and $$$(2, 4)$$$ by $$$1$$$ to unify MST."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $$$n$$$ stairs, then it is made of $$$n$$$ columns, the first column is $$$1$$$ cell high, the second column is $$$2$$$ cells high, $$$\\ldots$$$, the $$$n$$$-th column if $$$n$$$ cells high. The lowest cells of all stairs must be in the same row.A staircase with $$$n$$$ stairs is called nice, if it may be covered by $$$n$$$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $$$7$$$ stairs looks like: Find out the maximal number of different nice staircases, that can be built, using no more than $$$x$$$ cells, in total. No cell can be used more than once.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 1000)$$$ \u00a0\u2014 the number of test cases. The description of each test case contains a single integer $$$x$$$ $$$(1 \\le x \\le 10^{18})$$$ \u00a0\u2014 the number of cells for building staircases.", "output_spec": "For each test case output a single integer \u00a0\u2014 the number of different nice staircases, that can be built, using not more than $$$x$$$ cells, in total.", "sample_inputs": ["4\n1\n8\n6\n1000000000000000000"], "sample_outputs": ["1\n2\n1\n30"], "notes": "NoteIn the first test case, it is possible to build only one staircase, that consists of $$$1$$$ stair. It's nice. That's why the answer is $$$1$$$.In the second test case, it is possible to build two different nice staircases: one consists of $$$1$$$ stair, and another consists of $$$3$$$ stairs. This will cost $$$7$$$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $$$2$$$.In the third test case, it is possible to build only one of two nice staircases: with $$$1$$$ stair or with $$$3$$$ stairs. In the first case, there will be $$$5$$$ cells left, that may be used only to build a staircase with $$$2$$$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $$$1$$$. If Jett builds a staircase with $$$3$$$ stairs, then there are no more cells left, so the answer is $$$1$$$ again."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.More formally, you've got two arrays of integers a1,\u2009a2,\u2009...,\u2009an and b1,\u2009b2,\u2009...,\u2009bn of length n. Also, you've got m queries of two types: Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by\u2009+\u2009q\u2009=\u2009ax\u2009+\u2009q for all integer q (0\u2009\u2264\u2009q\u2009<\u2009k). The given operation is correct \u2014 both subsegments do not touch unexistent elements. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result \u2014 the value of the corresponding element of array b.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009109). The third line contains an array of integers b1,\u2009b2,\u2009...,\u2009bn (|bi|\u2009\u2264\u2009109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti \u2014 the type of the i-th query (1\u2009\u2264\u2009ti\u2009\u2264\u20092). If ti\u2009=\u20091, then the i-th query means the copying operation. If ti\u2009=\u20092, then the i-th query means taking the value in array b. If ti\u2009=\u20091, then the query type is followed by three integers xi,\u2009yi,\u2009ki (1\u2009\u2264\u2009xi,\u2009yi,\u2009ki\u2009\u2264\u2009n) \u2014 the parameters of the copying query. If ti\u2009=\u20092, then the query type is followed by integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n) \u2014 the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.", "output_spec": "For each second type query print the result on a single line.", "sample_inputs": ["5 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"], "sample_outputs": ["0\n3\n-1\n3\n2\n3\n-1"], "notes": null}, "positive_code": [{"source_code": "/*\nE. \u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u041e\u0447\u0435\u043d\u044c \u0447\u0430\u0441\u0442\u043e \u043f\u0440\u0438\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u043e\u0431\u044a\u0435\u043c\u044b \u0434\u0430\u043d\u043d\u044b\u0445. \u0422\u0430\u043a\u0430\u044f \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044f \u043c\u043e\u0436\u0435\u0442 \u043f\u043e\u0442\u0440\u0435\u0431\u043e\u0432\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0438\u0445 \u0437\u0430\u0442\u0440\u0430\u0442 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u044b\u0445 \u0440\u0435\u0441\u0443\u0440\u0441\u043e\u0432. \u0412 \u0441\u0432\u044f\u0437\u0438 \u0441 \u044d\u0442\u0438\u043c, \u0432 \u044d\u0442\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u0432\u0430\u043c \u043f\u0440\u0435\u0434\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u043f\u0440\u0438\u0434\u0443\u043c\u0430\u0442\u044c \u0441\u043f\u043e\u0441\u043e\u0431 \u0431\u044b\u0441\u0442\u0440\u043e\u0433\u043e \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0447\u0430\u0441\u0442\u0438 \u043e\u0434\u043d\u043e\u0433\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0447\u0438\u0441\u0435\u043b \u0432 \u0434\u0440\u0443\u0433\u043e\u0439.\n\n\u0411\u043e\u043b\u0435\u0435 \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, \u0432\u0430\u043c \u0437\u0430\u0434\u0430\u043d\u043e \u0434\u0432\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an \u0438 b1,\u2009b2,\u2009...,\u2009bn \u0434\u043b\u0438\u043d\u044b n. \u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c m \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0434\u0432\u0443\u0445 \u0442\u0438\u043f\u043e\u0432:\n\n \u0421\u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u043f\u043e\u0434\u043e\u0442\u0440\u0435\u0437\u043e\u043a \u043c\u0430\u0441\u0441\u0438\u0432\u0430 a \u0434\u043b\u0438\u043d\u044b k, \u043d\u0430\u0447\u0438\u043d\u0430\u044f \u0441 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 x, \u0432 \u043c\u0430\u0441\u0441\u0438\u0432 b, \u043d\u0430\u0447\u0438\u043d\u0430\u044f \u0441 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 y, \u0442\u043e \u0435\u0441\u0442\u044c \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c by\u2009+\u2009q\u2009=\u2009ax\u2009+\u2009q \u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0446\u0435\u043b\u044b\u0445 q (0\u2009\u2264\u2009q\u2009<\u2009k). \u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f \u0437\u0430\u0434\u0430\u043d\u0430 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e \u2014 \u043e\u0431\u0430 \u043f\u043e\u0434\u043e\u0442\u0440\u0435\u0437\u043a\u0430 \u0446\u0435\u043b\u0438\u043a\u043e\u043c \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u0441\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 a \u0438 b \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e.\n \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0432 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 x \u043c\u0430\u0441\u0441\u0438\u0432\u0430 b, \u0442\u043e \u0435\u0441\u0442\u044c \u043d\u0430\u0439\u0442\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 bx. \n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0442\u0438\u043f\u0430 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u2014 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 b.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e. \u0412\u043e \u0432\u0442\u043e\u0440\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009109). \u0412 \u0442\u0440\u0435\u0442\u044c\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b b1,\u2009b2,\u2009...,\u2009bn (|bi|\u2009\u2264\u2009109).\n\n\u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 m \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u0434\u0430\u043d\u044b \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432. \u0412 i-\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0437\u0430\u0434\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e ti \u2014 \u0442\u0438\u043f i-\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 (1\u2009\u2264\u2009ti\u2009\u2264\u20092). \u0415\u0441\u043b\u0438 ti\u2009=\u20091, \u0442\u043e i-\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0435\u0441\u043b\u0438 ti\u2009=\u20092, \u0442\u043e i-\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u0432\u0437\u044f\u0442\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 b. \u0415\u0441\u043b\u0438 ti\u2009=\u20091, \u0442\u043e \u043f\u043e\u0441\u043b\u0435 \u0442\u0438\u043f\u0430 \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0442\u0440\u0438 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 xi,\u2009yi,\u2009ki (1\u2009\u2264\u2009xi,\u2009yi,\u2009ki\u2009\u2264\u2009n) \u2014 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f. \u0415\u0441\u043b\u0438 ti\u2009=\u20092, \u0442\u043e \u0441\u043b\u0435\u0434\u043e\u043c, \u043f\u043e\u0441\u043b\u0435 \u0442\u0438\u043f\u0430 \u0437\u0430\u043f\u0440\u043e\u0441\u0430, \u0432 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n) \u2014 \u043f\u043e\u0437\u0438\u0446\u0438\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 b.\n\n\u0412\u0441\u0435 \u0447\u0438\u0441\u043b\u0430 \u0432 \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u044b \u043e\u0434\u0438\u043d\u043e\u0447\u043d\u044b\u043c\u0438 \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c\u0438. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 \u0437\u0430\u043f\u0440\u043e\u0441\u044b \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b, \u0442\u043e \u0435\u0441\u0442\u044c \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0435 \u0432\u044b\u0445\u043e\u0434\u044f\u0442 \u0437\u0430 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u0432 a \u0438 b.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0442\u0438\u043f\u0430 \u0432 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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}"}, {"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}"}], "negative_code": [{"source_code": "/*\nE. \u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u041e\u0447\u0435\u043d\u044c \u0447\u0430\u0441\u0442\u043e \u043f\u0440\u0438\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u043e\u0431\u044a\u0435\u043c\u044b \u0434\u0430\u043d\u043d\u044b\u0445. \u0422\u0430\u043a\u0430\u044f \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044f \u043c\u043e\u0436\u0435\u0442 \u043f\u043e\u0442\u0440\u0435\u0431\u043e\u0432\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0438\u0445 \u0437\u0430\u0442\u0440\u0430\u0442 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u044b\u0445 \u0440\u0435\u0441\u0443\u0440\u0441\u043e\u0432. \u0412 \u0441\u0432\u044f\u0437\u0438 \u0441 \u044d\u0442\u0438\u043c, \u0432 \u044d\u0442\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u0432\u0430\u043c \u043f\u0440\u0435\u0434\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u043f\u0440\u0438\u0434\u0443\u043c\u0430\u0442\u044c \u0441\u043f\u043e\u0441\u043e\u0431 \u0431\u044b\u0441\u0442\u0440\u043e\u0433\u043e \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0447\u0430\u0441\u0442\u0438 \u043e\u0434\u043d\u043e\u0433\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0447\u0438\u0441\u0435\u043b \u0432 \u0434\u0440\u0443\u0433\u043e\u0439.\n\n\u0411\u043e\u043b\u0435\u0435 \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, \u0432\u0430\u043c \u0437\u0430\u0434\u0430\u043d\u043e \u0434\u0432\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an \u0438 b1,\u2009b2,\u2009...,\u2009bn \u0434\u043b\u0438\u043d\u044b n. \u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c m \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0434\u0432\u0443\u0445 \u0442\u0438\u043f\u043e\u0432:\n\n \u0421\u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u043f\u043e\u0434\u043e\u0442\u0440\u0435\u0437\u043e\u043a \u043c\u0430\u0441\u0441\u0438\u0432\u0430 a \u0434\u043b\u0438\u043d\u044b k, \u043d\u0430\u0447\u0438\u043d\u0430\u044f \u0441 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 x, \u0432 \u043c\u0430\u0441\u0441\u0438\u0432 b, \u043d\u0430\u0447\u0438\u043d\u0430\u044f \u0441 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 y, \u0442\u043e \u0435\u0441\u0442\u044c \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c by\u2009+\u2009q\u2009=\u2009ax\u2009+\u2009q \u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0446\u0435\u043b\u044b\u0445 q (0\u2009\u2264\u2009q\u2009<\u2009k). \u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f \u0437\u0430\u0434\u0430\u043d\u0430 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e \u2014 \u043e\u0431\u0430 \u043f\u043e\u0434\u043e\u0442\u0440\u0435\u0437\u043a\u0430 \u0446\u0435\u043b\u0438\u043a\u043e\u043c \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u0441\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 a \u0438 b \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e.\n \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0432 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 x \u043c\u0430\u0441\u0441\u0438\u0432\u0430 b, \u0442\u043e \u0435\u0441\u0442\u044c \u043d\u0430\u0439\u0442\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 bx. \n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0442\u0438\u043f\u0430 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u2014 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 b.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e. \u0412\u043e \u0432\u0442\u043e\u0440\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009109). \u0412 \u0442\u0440\u0435\u0442\u044c\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b b1,\u2009b2,\u2009...,\u2009bn (|bi|\u2009\u2264\u2009109).\n\n\u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 m \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u0434\u0430\u043d\u044b \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432. \u0412 i-\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0437\u0430\u0434\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e ti \u2014 \u0442\u0438\u043f i-\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 (1\u2009\u2264\u2009ti\u2009\u2264\u20092). \u0415\u0441\u043b\u0438 ti\u2009=\u20091, \u0442\u043e i-\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0435\u0441\u043b\u0438 ti\u2009=\u20092, \u0442\u043e i-\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u0432\u0437\u044f\u0442\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 b. \u0415\u0441\u043b\u0438 ti\u2009=\u20091, \u0442\u043e \u043f\u043e\u0441\u043b\u0435 \u0442\u0438\u043f\u0430 \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0442\u0440\u0438 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 xi,\u2009yi,\u2009ki (1\u2009\u2264\u2009xi,\u2009yi,\u2009ki\u2009\u2264\u2009n) \u2014 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f. \u0415\u0441\u043b\u0438 ti\u2009=\u20092, \u0442\u043e \u0441\u043b\u0435\u0434\u043e\u043c, \u043f\u043e\u0441\u043b\u0435 \u0442\u0438\u043f\u0430 \u0437\u0430\u043f\u0440\u043e\u0441\u0430, \u0432 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n) \u2014 \u043f\u043e\u0437\u0438\u0446\u0438\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 b.\n\n\u0412\u0441\u0435 \u0447\u0438\u0441\u043b\u0430 \u0432 \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u044b \u043e\u0434\u0438\u043d\u043e\u0447\u043d\u044b\u043c\u0438 \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c\u0438. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 \u0437\u0430\u043f\u0440\u043e\u0441\u044b \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b, \u0442\u043e \u0435\u0441\u0442\u044c \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0435 \u0432\u044b\u0445\u043e\u0434\u044f\u0442 \u0437\u0430 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u0432 a \u0438 b.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0442\u0438\u043f\u0430 \u0432 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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. \u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u041e\u0447\u0435\u043d\u044c \u0447\u0430\u0441\u0442\u043e \u043f\u0440\u0438\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u043e\u0431\u044a\u0435\u043c\u044b \u0434\u0430\u043d\u043d\u044b\u0445. \u0422\u0430\u043a\u0430\u044f \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044f \u043c\u043e\u0436\u0435\u0442 \u043f\u043e\u0442\u0440\u0435\u0431\u043e\u0432\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0438\u0445 \u0437\u0430\u0442\u0440\u0430\u0442 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u044b\u0445 \u0440\u0435\u0441\u0443\u0440\u0441\u043e\u0432. \u0412 \u0441\u0432\u044f\u0437\u0438 \u0441 \u044d\u0442\u0438\u043c, \u0432 \u044d\u0442\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u0432\u0430\u043c \u043f\u0440\u0435\u0434\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u043f\u0440\u0438\u0434\u0443\u043c\u0430\u0442\u044c \u0441\u043f\u043e\u0441\u043e\u0431 \u0431\u044b\u0441\u0442\u0440\u043e\u0433\u043e \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0447\u0430\u0441\u0442\u0438 \u043e\u0434\u043d\u043e\u0433\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0447\u0438\u0441\u0435\u043b \u0432 \u0434\u0440\u0443\u0433\u043e\u0439.\n\n\u0411\u043e\u043b\u0435\u0435 \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, \u0432\u0430\u043c \u0437\u0430\u0434\u0430\u043d\u043e \u0434\u0432\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an \u0438 b1,\u2009b2,\u2009...,\u2009bn \u0434\u043b\u0438\u043d\u044b n. \u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c m \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0434\u0432\u0443\u0445 \u0442\u0438\u043f\u043e\u0432:\n\n \u0421\u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u043f\u043e\u0434\u043e\u0442\u0440\u0435\u0437\u043e\u043a \u043c\u0430\u0441\u0441\u0438\u0432\u0430 a \u0434\u043b\u0438\u043d\u044b k, \u043d\u0430\u0447\u0438\u043d\u0430\u044f \u0441 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 x, \u0432 \u043c\u0430\u0441\u0441\u0438\u0432 b, \u043d\u0430\u0447\u0438\u043d\u0430\u044f \u0441 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 y, \u0442\u043e \u0435\u0441\u0442\u044c \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c by\u2009+\u2009q\u2009=\u2009ax\u2009+\u2009q \u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0446\u0435\u043b\u044b\u0445 q (0\u2009\u2264\u2009q\u2009<\u2009k). \u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f \u0437\u0430\u0434\u0430\u043d\u0430 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e \u2014 \u043e\u0431\u0430 \u043f\u043e\u0434\u043e\u0442\u0440\u0435\u0437\u043a\u0430 \u0446\u0435\u043b\u0438\u043a\u043e\u043c \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u0441\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 a \u0438 b \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e.\n \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0432 \u043f\u043e\u0437\u0438\u0446\u0438\u0438 x \u043c\u0430\u0441\u0441\u0438\u0432\u0430 b, \u0442\u043e \u0435\u0441\u0442\u044c \u043d\u0430\u0439\u0442\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 bx. \n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0442\u0438\u043f\u0430 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u2014 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 b.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e. \u0412\u043e \u0432\u0442\u043e\u0440\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009109). \u0412 \u0442\u0440\u0435\u0442\u044c\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b b1,\u2009b2,\u2009...,\u2009bn (|bi|\u2009\u2264\u2009109).\n\n\u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 m \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u0434\u0430\u043d\u044b \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432. \u0412 i-\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0437\u0430\u0434\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e ti \u2014 \u0442\u0438\u043f i-\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 (1\u2009\u2264\u2009ti\u2009\u2264\u20092). \u0415\u0441\u043b\u0438 ti\u2009=\u20091, \u0442\u043e i-\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0435\u0441\u043b\u0438 ti\u2009=\u20092, \u0442\u043e i-\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u0432\u0437\u044f\u0442\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 b. \u0415\u0441\u043b\u0438 ti\u2009=\u20091, \u0442\u043e \u043f\u043e\u0441\u043b\u0435 \u0442\u0438\u043f\u0430 \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0442\u0440\u0438 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 xi,\u2009yi,\u2009ki (1\u2009\u2264\u2009xi,\u2009yi,\u2009ki\u2009\u2264\u2009n) \u2014 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f. \u0415\u0441\u043b\u0438 ti\u2009=\u20092, \u0442\u043e \u0441\u043b\u0435\u0434\u043e\u043c, \u043f\u043e\u0441\u043b\u0435 \u0442\u0438\u043f\u0430 \u0437\u0430\u043f\u0440\u043e\u0441\u0430, \u0432 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n) \u2014 \u043f\u043e\u0437\u0438\u0446\u0438\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 b.\n\n\u0412\u0441\u0435 \u0447\u0438\u0441\u043b\u0430 \u0432 \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u044b \u043e\u0434\u0438\u043d\u043e\u0447\u043d\u044b\u043c\u0438 \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c\u0438. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 \u0437\u0430\u043f\u0440\u043e\u0441\u044b \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b, \u0442\u043e \u0435\u0441\u0442\u044c \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0435 \u0432\u044b\u0445\u043e\u0434\u044f\u0442 \u0437\u0430 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u0432 a \u0438 b.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0442\u0438\u043f\u0430 \u0432 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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"} {"nl": {"description": "It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x\u2009-\u2009y|. Then this player adds integer |x\u2009-\u2009y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the initial number of elements in the set. The second line contains n distinct space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of the set.", "output_spec": "Print a single line with the winner's name. If Alice wins print \"Alice\", otherwise print \"Bob\" (without quotes).", "sample_inputs": ["2\n2 3", "2\n5 3", "3\n5 6 7"], "sample_outputs": ["Alice", "Alice", "Bob"], "notes": "NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice."}, "positive_code": [{"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": "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}"}, {"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": "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 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"}], "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"} {"nl": {"description": "One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold: x occurs in sequence a. Consider all positions of numbers x in the sequence a (such i, that ai\u2009=\u2009x). These numbers, sorted in the increasing order, must form an arithmetic progression. Help Jeff, find all x that meet the problem conditions.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105). The numbers are separated by spaces.", "output_spec": "In the first line print integer t \u2014 the number of valid x. On each of the next t lines print two integers x and px, where x is current suitable value, px is the common difference between numbers in the progression (if x occurs exactly once in the sequence, px must equal 0). Print the pairs in the order of increasing x.", "sample_inputs": ["1\n2", "8\n1 2 1 3 1 2 1 5"], "sample_outputs": ["1\n2 0", "4\n1 2\n2 4\n3 0\n5 0"], "notes": "NoteIn the first test 2 occurs exactly once in the sequence, ergo p2\u2009=\u20090."}, "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 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"}, {"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"} {"nl": {"description": "Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told \u2014 ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n\u2009-\u2009k\u2009+\u20091. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.", "input_spec": "The first line of the input contains two integer numbers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1,\u2009a2,\u2009... an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) \u2014 the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1,\u2009t2,\u2009... tn (0\u2009\u2264\u2009ti\u2009\u2264\u20091) \u2014 type of Mishka's behavior at the i-th minute of the lecture.", "output_spec": "Print only one integer \u2014 the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.", "sample_inputs": ["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"], "sample_outputs": ["16"], "notes": "NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Recently, Olya received a magical square with the size of $$$2^n\\times 2^n$$$.It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly $$$k$$$ splitting operations.A Splitting operation is an operation during which Olya takes a square with side $$$a$$$ and cuts it into 4 equal squares with side $$$\\dfrac{a}{2}$$$. If the side of the square is equal to $$$1$$$, then it is impossible to apply a splitting operation to it (see examples for better understanding).Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.The condition of Olya's happiness will be satisfied if the following statement is fulfilled:Let the length of the side of the lower left square be equal to $$$a$$$, then the length of the side of the right upper square should also be equal to $$$a$$$. There should also be a path between them that consists only of squares with the side of length $$$a$$$. All consecutive squares on a path should have a common side.Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly $$$k$$$ splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$)\u00a0\u2014 the number of tests. Each of the following $$$t$$$ lines contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \\le n_i \\le 10^9, 1 \\le k_i \\le 10^{18}$$$)\u00a0\u2014 the description of the $$$i$$$-th test, which means that initially Olya's square has size of $$$2^{n_i}\\times 2^{n_i}$$$ and Olya's sister asks her to do exactly $$$k_i$$$ splitting operations.", "output_spec": "Print $$$t$$$ lines, where in the $$$i$$$-th line you should output \"YES\" if it is possible to perform $$$k_i$$$ splitting operations in the $$$i$$$-th test in such a way that the condition of Olya's happiness is satisfied or print \"NO\" otherwise. If you printed \"YES\", then also print the $$$log_2$$$ of the length of the side of the squares through space, along which you can build a path from the lower left square to the upper right one. You can output each letter in any case (lower or upper). If there are multiple answers, print any.", "sample_inputs": ["3\n1 1\n2 2\n2 12"], "sample_outputs": ["YES 0\nYES 1\nNO"], "notes": "NoteIn each of the illustrations, the pictures are shown in order in which Olya applied the operations. The recently-created squares are highlighted with red.In the first test, Olya can apply splitting operations in the following order: Olya applies one operation on the only existing square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one: The length of the sides of the squares on the path is $$$1$$$. $$$log_2(1) = 0$$$.In the second test, Olya can apply splitting operations in the following order: Olya applies the first operation on the only existing square. She applies the second one on the right bottom square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one: The length of the sides of the squares on the path is $$$2$$$. $$$log_2(2) = 1$$$.In the third test, it takes $$$5$$$ operations for Olya to make the square look like this: Since it requires her to perform $$$7$$$ splitting operations, and it is impossible to perform them on squares with side equal to $$$1$$$, then Olya cannot do anything more and the answer is \"NO\"."}, "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 MAX = 31\n def divNum(x: Int) = {\n if (x == 0) 0L\n else ((1L << x * 2) - 1) / 3\n }\n\n def calc(n: Int, k: Long): Option[Int] = {\n if (n > 31) Some(n - 1) // \u4e00\u56de\u5168\u4f53\u3092\uff14\u5206\u5272\u3057\u305f\u5f8c\u3001\u53f3\u4e0b\u3060\u3051\u3067\u5168\u90e8\u6d88\u5316\u3067\u304d\u308b\n else {\n\n val S = divNum(n)\n var cur = 1\n var cnt = 0\n var i = 1\n while (i <= MAX && i <= n) {\n cnt += cur\n cur = cur * 2 + 1\n if (cnt <= k && k <= S - cur * divNum(n - i)) {\n return Some(n - i)\n }\n i += 1\n }\n None\n }\n }\n\n rep(ni()) { _ =>\n val n = ni()\n val k = nl()\n calc(n, k) match {\n case Some(lg) => out.println(s\"YES $lg\")\n case None => 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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 // todo k == 0\u306b\u6ce8\u610f\n val MAX = 31\n def divNum(x: Int) = {\n if (x == 0) 0L\n else ((1L << x * 2) - 1) / 3\n }\n\n def calc(n: Int, k: Long): Option[Int] = {\n if (k == 0) Some(n)\n else {\n val S = divNum(n)\n var cur = 1\n var cnt = 0\n var i = 1\n while (i <= MAX && i <= n) {\n cnt += cur\n cur = cur * 2 + 1\n if (cnt <= k && k <= S - cur * divNum(n - i)) {\n return Some(n - i)\n }\n i += 1\n }\n None\n }\n }\n\n rep(ni()) { _ =>\n val n = ni()\n val k = nl()\n calc(n, k) match {\n case Some(lg) => out.println(s\"YES $lg\")\n case None => 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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 MAX = 32\n def divNum(x: Int) = {\n if (x == 0) 0L\n else ((1L << x * 2) - 1) / 3\n }\n\n def calc(n: Int, k: Long): Option[Int] = {\n val S = divNum(n)\n var cur = 1\n var cnt = 0\n var i = 1\n while (i <= MAX && i <= n) {\n cnt += cur\n cur = cur * 2 + 1\n if (cnt <= k && k <= S - cur * divNum(n - i)) {\n return Some(n - i)\n }\n i += 1\n }\n None\n }\n\n rep(ni()) { _ =>\n val n = ni()\n val k = nl()\n calc(n, k) match {\n case Some(lg) => out.println(s\"YES $lg\")\n case None => 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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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": "1501b9f964f793c2746ff5977db4e607"} {"nl": {"description": "Sasha has an array of integers a1,\u2009a2,\u2009...,\u2009an. You have to perform m queries. There might be queries of two types: 1 l r x\u00a0\u2014 increase all integers on the segment from l to r by values x; 2 l r\u00a0\u2014 find , where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it modulo 109\u2009+\u20097. In this problem we define Fibonacci numbers as follows: f(1)\u2009=\u20091, f(2)\u2009=\u20091, f(x)\u2009=\u2009f(x\u2009-\u20091)\u2009+\u2009f(x\u2009-\u20092) for all x\u2009>\u20092.Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of elements in the array and the number of queries respectively. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). Then follow m lines with queries descriptions. Each of them contains integers tpi, li, ri and may be xi (1\u2009\u2264\u2009tpi\u2009\u2264\u20092, 1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n, 1\u2009\u2264\u2009xi\u2009\u2264\u2009109). Here tpi\u2009=\u20091 corresponds to the queries of the first type and tpi corresponds to the queries of the second type. It's guaranteed that the input will contains at least one query of the second type.", "output_spec": "For each query of the second type print the answer modulo 109\u2009+\u20097.", "sample_inputs": ["5 4\n1 1 2 1 1\n2 1 5\n1 2 4 2\n2 2 4\n2 1 5"], "sample_outputs": ["5\n7\n9"], "notes": "NoteInitially, array a is equal to 1, 1, 2, 1, 1.The answer for the first query of the second type is f(1)\u2009+\u2009f(1)\u2009+\u2009f(2)\u2009+\u2009f(1)\u2009+\u2009f(1)\u2009=\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u20095. After the query 1 2 4 2 array a is equal to 1, 3, 4, 3, 1.The answer for the second query of the second type is f(3)\u2009+\u2009f(4)\u2009+\u2009f(3)\u2009=\u20092\u2009+\u20093\u2009+\u20092\u2009=\u20097.The answer for the third query of the second type is f(1)\u2009+\u2009f(3)\u2009+\u2009f(4)\u2009+\u2009f(3)\u2009+\u2009f(1)\u2009=\u20091\u2009+\u20092\u2009+\u20093\u2009+\u20092\u2009+\u20091\u2009=\u20099."}, "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"}, {"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"}], "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"} {"nl": {"description": "Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.", "input_spec": "The first line contains two integers: n and d (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009d\u2009\u2264\u2009109). The next line contains n integers x1,\u2009x2,\u2009...,\u2009xn, their absolute value doesn't exceed 109 \u2014 the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.", "output_spec": "Print a single integer \u2014 the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"], "sample_outputs": ["4", "2", "1"], "notes": "NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}."}, "positive_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): Long = {\n if (last - first < 2)\n 0\n else {\n val diff: Long = last - first\n diff * (diff - 1) / 2\n }\n }\n\n val res = (1 until n).foldLeft(0, 0l) {\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 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"}, {"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"}, {"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\n val y = 1 << i\n val x = y / 2\n out.println(s\"? $x $y\")\n out.flush()\n ns() match {\n case \"x\" =>\n return (x, y)\n\n case \"y\" =>\n }\n }\n val y = 1 << 30\n val x = y / 2\n (x, y)\n }\n\n\n var (l, r) = queryRange()\n while(r - l > 1) {\n val mid = (r + l) / 2\n val x = mid\n val y = r\n out.println(s\"? $x $y\")\n out.flush()\n\n ns() match {\n case \"x\" =>\n // a > mid\n l = mid\n case \"y\" =>\n // a <= mid\n r = mid\n }\n }\n\n out.println(s\"! $r\")\n out.flush()\n true\n }\n\n var end = false\n while(!end) {\n ns() match {\n case \"start\" =>\n end = !play()\n\n case \"end\" =>\n end = true\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}"}], "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 play(): Boolean = {\n def queryRange(): (Int, Int) = {\n REP(30) { i =>\n val y = 1 << i\n val x = y / 2\n out.println(s\"? $x $y\")\n out.flush()\n ns() match {\n case \"x\" =>\n return (x, y)\n\n case \"y\" =>\n }\n }\n ???\n }\n\n\n var (l, r) = queryRange()\n while(r - l > 1) {\n val mid = (r + l) / 2\n val x = mid\n val y = r\n out.println(s\"? $x $y\")\n out.flush()\n\n ns() match {\n case \"x\" =>\n // a > mid\n l = mid\n case \"y\" =>\n // a <= mid\n r = mid\n }\n }\n\n out.println(s\"! $r\")\n out.flush()\n true\n }\n\n var end = false\n while(!end) {\n ns() match {\n case \"start\" =>\n end = !play()\n\n case \"end\" =>\n end = true\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}"}], "src_uid": "eab8e5ac203d9f10c893ea35d249fe84"} {"nl": {"description": "The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of $$$m$$$ pages.Polycarp also has $$$n$$$ cups of coffee. The coffee in the $$$i$$$-th cup Polycarp has $$$a_i$$$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks $$$k$$$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $$$a_{i_1}, a_{i_2}, \\dots, a_{i_k}$$$. Then the first cup he drinks gives him energy to write $$$a_{i_1}$$$ pages of coursework, the second cup gives him energy to write $$$max(0, a_{i_2} - 1)$$$ pages, the third cup gives him energy to write $$$max(0, a_{i_3} - 2)$$$ pages, ..., the $$$k$$$-th cup gives him energy to write $$$max(0, a_{i_k} - k + 1)$$$ pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 10^9$$$) \u2014 the number of cups of coffee and the number of pages in the coursework. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the caffeine dosage of coffee in the $$$i$$$-th cup.", "output_spec": "If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.", "sample_inputs": ["5 8\n2 3 1 1 2", "7 10\n1 3 4 2 1 4 2", "5 15\n5 5 5 5 5", "5 16\n5 5 5 5 5", "5 26\n5 5 5 5 5"], "sample_outputs": ["4", "2", "1", "2", "-1"], "notes": "NoteIn the first example Polycarp can drink fourth cup during first day (and write $$$1$$$ page), first and second cups during second day (and write $$$2 + (3 - 1) = 4$$$ pages), fifth cup during the third day (and write $$$2$$$ pages) and third cup during the fourth day (and write $$$1$$$ page) so the answer is $$$4$$$. It is obvious that there is no way to write the coursework in three or less days.In the second example Polycarp can drink third, fourth and second cups during first day (and write $$$4 + (2 - 1) + (3 - 2) = 6$$$ pages) and sixth cup during second day (and write $$$4$$$ pages) so the answer is $$$2$$$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$$$ pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$$$ pages of coursework and during second day he will write $$$5$$$ pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1."}, "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 sort(A)\n reverse(A)\n\n// debug(A)\n\n def check(x: Int): Boolean = {\n// debug(s\"check($x)\")\n var i = 0\n var m = M\n while (m > 0 && i < N) {\n val k = i / x\n val v = max(0, A(i) - k)\n m -= v\n// debug(s\"$i $k $v\")\n i += 1\n }\n m <= 0\n }\n\n val INF = N + 1\n var l = 0\n var r = INF\n while(r - l > 1) {\n val mid = (r + l) / 2\n if (check(mid)) r = mid\n else l = mid\n }\n\n if (r == INF) out.println(-1)\n else out.println(r)\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 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\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, M = ni()\n val A = na(N)\n sort(A)\n reverse(A)\n\n// debug(A)\n\n def check(x: Int): Boolean = {\n// debug(s\"check($x)\")\n var i = 0\n var m = M\n while (m > 0 && i < N) {\n val k = i / x\n val v = max(0, A(i) - k)\n m -= v\n// debug(s\"$i $k $v\")\n i += 1\n }\n m <= 0\n }\n\n var l = 0\n var r = N\n while(r - l > 1) {\n val mid = (r + l) / 2\n if (check(mid)) r = mid\n else l = mid\n }\n\n if (r == N) out.println(-1)\n else out.println(r)\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 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\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}"}], "src_uid": "1b79ff21b5c1df4c54236071a585a52e"} {"nl": {"description": "You are given a sequence a1,\u2009a2,\u2009...,\u2009an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1,\u2009r1] lies within segment [l2,\u2009r2] iff l1\u2009\u2265\u2009l2 and r1\u2009\u2264\u2009r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the number of segments. Each of the next n lines contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) \u2014 the i-th segment.", "output_spec": "Print two distinct indices i and j such that segment ai lies within segment aj. If there are multiple answers, print any of them. If no answer exists, print -1 -1.", "sample_inputs": ["5\n1 10\n2 9\n3 9\n2 3\n2 9", "3\n1 5\n2 6\n6 20"], "sample_outputs": ["2 1", "-1 -1"], "notes": "NoteIn the first example the following pairs are considered correct: (2,\u20091),\u2009(3,\u20091),\u2009(4,\u20091),\u2009(5,\u20091) \u2014 not even touching borders; (3,\u20092),\u2009(4,\u20092),\u2009(3,\u20095),\u2009(4,\u20095) \u2014 touch one border; (5,\u20092),\u2009(2,\u20095) \u2014 match exactly. "}, "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 lris = r.read[Array[(Int, Int)]](n).zipWithIndex.sorted.toList\n \n @annotation.tailrec\n def go(lri: ((Int, Int), Int), lris: List[((Int, Int), Int)]): (Int, Int) = lris match {\n case Nil => (-2, -2)\n case ((l1, r1), i1) :: lris1 => {\n val ((l, r), i) = lri\n if (l == l1) (i, i1)\n else if (r1 <= r) (i1, i)\n else go(((l1, r1), i1), lris1)\n }\n }\n \n val (i, j) = go(lris.head, lris.tail)\n println(s\"${i+1} ${j+1}\")\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": "0148aed9b07c4f65b2507fcb8b837360"} {"nl": {"description": "You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.", "sample_inputs": ["7\n1\n2\n3\n12\n12345\n15116544\n387420489"], "sample_outputs": ["0\n-1\n2\n-1\n-1\n12\n36"], "notes": "NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$: Divide by $$$6$$$ and get $$$2519424$$$; divide by $$$6$$$ and get $$$419904$$$; divide by $$$6$$$ and get $$$69984$$$; divide by $$$6$$$ and get $$$11664$$$; multiply by $$$2$$$ and get $$$23328$$$; divide by $$$6$$$ and get $$$3888$$$; divide by $$$6$$$ and get $$$648$$$; divide by $$$6$$$ and get $$$108$$$; multiply by $$$2$$$ and get $$$216$$$; divide by $$$6$$$ and get $$$36$$$; divide by $$$6$$$ and get $$$6$$$; divide by $$$6$$$ and get $$$1$$$. "}, "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"}, {"source_code": "import scala.io.StdIn.readLine\nobject Main {\n def main(args: Array[String]) = {\n val T = readLine().toInt\n for(cas <- 0 until T) {\n var n = readLine().toInt\n var c1 = 0\n var c2 = 0\n while(n % 2 == 0) {\n n /= 2\n c1 += 1\n }\n while(n % 3 == 0) {\n n /= 3\n c2 += 1\n }\n if(c1 > c2 || n != 1) {\n println(\"-1\")\n } else {\n println(c2 - c1 + c2)\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "3ae468c425c7b156983414372fd35ab8"} {"nl": {"description": "There is a frog staying to the left of the string $$$s = s_1 s_2 \\ldots s_n$$$ consisting of $$$n$$$ characters (to be more precise, the frog initially stays at the cell $$$0$$$). Each character of $$$s$$$ is either 'L' or 'R'. It means that if the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $$$0$$$.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the $$$n+1$$$-th cell. The frog chooses some positive integer value $$$d$$$ before the first jump (and cannot change it later) and jumps by no more than $$$d$$$ cells at once. I.e. if the $$$i$$$-th character is 'L' then the frog can jump to any cell in a range $$$[max(0, i - d); i - 1]$$$, and if the $$$i$$$-th character is 'R' then the frog can jump to any cell in a range $$$[i + 1; min(n + 1; i + d)]$$$.The frog doesn't want to jump far, so your task is to find the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it can jump by no more than $$$d$$$ cells at once. It is guaranteed that it is always possible to reach $$$n+1$$$ from $$$0$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case is described as a string $$$s$$$ consisting of at least $$$1$$$ and at most $$$2 \\cdot 10^5$$$ characters 'L' and 'R'. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum |s| \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it jumps by no more than $$$d$$$ at once.", "sample_inputs": ["6\nLRLRRLL\nL\nLLR\nRRRR\nLLLLLL\nR"], "sample_outputs": ["3\n2\n3\n1\n7\n1"], "notes": "NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the third test case of the example, the frog can choose $$$d=3$$$, jump to the cell $$$3$$$ from the cell $$$0$$$ and then to the cell $$$4$$$ from the cell $$$3$$$.In the fourth test case of the example, the frog can choose $$$d=1$$$ and jump $$$5$$$ times to the right.In the fifth test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the sixth test case of the example, the frog can choose $$$d=1$$$ and jump $$$2$$$ times to the right."}, "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 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"}, {"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"} {"nl": {"description": "The \"BerCorp\" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of employees and the number of languages. Then n lines follow \u2014 each employee's language list. At the beginning of the i-th line is integer ki (0\u2009\u2264\u2009ki\u2009\u2264\u2009m) \u2014 the number of languages the i-th employee knows. Next, the i-th line contains ki integers \u2014 aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009m) \u2014 the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.", "output_spec": "Print a single integer \u2014 the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).", "sample_inputs": ["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"], "sample_outputs": ["0", "2", "1"], "notes": "NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2."}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.", "input_spec": "The first line of input contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105)\u00a0\u2014 the number of boxes. Each of the next 2n lines of input starts with a string \"add\" or \"remove\". If the line starts with the \"add\", an integer x (1\u2009\u2264\u2009x\u2009\u2264\u2009n) follows, indicating that Daru should add the box with number x to the top of the stack. It is guaranteed that exactly n lines contain \"add\" operations, all the boxes added are distinct, and n lines contain \"remove\" operations. It is also guaranteed that a box is always added before it is required to be removed.", "output_spec": "Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.", "sample_inputs": ["3\nadd 1\nremove\nadd 2\nadd 3\nremove\nremove", "7\nadd 3\nadd 2\nadd 1\nremove\nadd 4\nremove\nremove\nremove\nadd 6\nadd 7\nadd 5\nremove\nremove\nremove"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample, Daru should reorder the boxes after adding box 3 to the stack.In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack."}, "positive_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 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"}, {"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"} {"nl": {"description": "Omkar is standing at the foot of Celeste mountain. The summit is $$$n$$$ meters away from him, and he can see all of the mountains up to the summit, so for all $$$1 \\leq j \\leq n$$$ he knows that the height of the mountain at the point $$$j$$$ meters away from himself is $$$h_j$$$ meters. It turns out that for all $$$j$$$ satisfying $$$1 \\leq j \\leq n - 1$$$, $$$h_j < h_{j + 1}$$$ (meaning that heights are strictly increasing).Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if $$$h_j + 2 \\leq h_{j + 1}$$$, then one square meter of dirt will slide from position $$$j + 1$$$ to position $$$j$$$, so that $$$h_{j + 1}$$$ is decreased by $$$1$$$ and $$$h_j$$$ is increased by $$$1$$$. These changes occur simultaneously, so for example, if $$$h_j + 2 \\leq h_{j + 1}$$$ and $$$h_{j + 1} + 2 \\leq h_{j + 2}$$$ for some $$$j$$$, then $$$h_j$$$ will be increased by $$$1$$$, $$$h_{j + 2}$$$ will be decreased by $$$1$$$, and $$$h_{j + 1}$$$ will be both increased and decreased by $$$1$$$, meaning that in effect $$$h_{j + 1}$$$ is unchanged during that minute.The landslide ends when there is no $$$j$$$ such that $$$h_j + 2 \\leq h_{j + 1}$$$. Help Omkar figure out what the values of $$$h_1, \\dots, h_n$$$ will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.Note that because of the large amount of input, it is recommended that your code uses fast IO.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^6$$$). The second line contains $$$n$$$ integers $$$h_1, h_2, \\dots, h_n$$$ satisfying $$$0 \\leq h_1 < h_2 < \\dots < h_n \\leq 10^{12}$$$\u00a0\u2014 the heights.", "output_spec": "Output $$$n$$$ integers, where the $$$j$$$-th integer is the value of $$$h_j$$$ after the landslide has stopped.", "sample_inputs": ["4\n2 6 7 8"], "sample_outputs": ["5 5 6 7"], "notes": "NoteInitially, the mountain has heights $$$2, 6, 7, 8$$$.In the first minute, we have $$$2 + 2 \\leq 6$$$, so $$$2$$$ increases to $$$3$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$3, 5, 7, 8$$$.In the second minute, we have $$$3 + 2 \\leq 5$$$ and $$$5 + 2 \\leq 7$$$, so $$$3$$$ increases to $$$4$$$, $$$5$$$ is unchanged, and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 5, 6, 8$$$.In the third minute, we have $$$6 + 2 \\leq 8$$$, so $$$6$$$ increases to $$$7$$$ and $$$8$$$ decreases to $$$7$$$, leaving $$$4, 5, 7, 7$$$.In the fourth minute, we have $$$5 + 2 \\leq 7$$$, so $$$5$$$ increases to $$$6$$$ and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 6, 6, 7$$$.In the fifth minute, we have $$$4 + 2 \\leq 6$$$, so $$$4$$$ increases to $$$5$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$5, 5, 6, 7$$$.In the sixth minute, nothing else can change so the landslide stops and our answer is $$$5, 5, 6, 7$$$."}, "positive_code": [{"source_code": "object F {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val hs = nextLongs(n)\n var sum = hs.sum\n\n var i = 0\n var prev = 0L\n while (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 def can(x: Long): Boolean = {\n val rem = n - i - 1\n val maxLast = x + rem\n val maxRem = (x + 1 + maxLast) * rem / 2\n x + maxRem >= sum\n }\n\n val rem = n - i\n val x = binSearch(prev, sum / rem + 1)\n hs(i) = x\n prev = x\n sum -= x\n\n i += 1\n }\n\n out.println(hs.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 F {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val hs = nextLongs(n)\n var sum = hs.sum\n\n var i = 0\n while (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 def can(x: Long): Boolean = {\n val rem = n - i - 1\n val maxLast = x + rem\n val maxRem = (x + 1 + maxLast) * rem / 2\n x + maxRem >= sum\n }\n\n val x = binSearch(0, sum)\n hs(i) = x\n sum -= x\n\n i += 1\n }\n\n out.println(hs.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": "612884cad3d52cc952f2b49674e70a08"} {"nl": {"description": "You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains: $$$a$$$ letters 'A'; $$$b$$$ letters 'B'; $$$c$$$ letters 'C'; no other letters; exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one). ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. Each of the next $$$t$$$ lines contains the description of the testcase\u00a0\u2014 four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$ ($$$1 \\le a, b, c \\le 10^8$$$; $$$0 \\le m \\le 10^8$$$).", "output_spec": "For each testcase print \"YES\" if there exists a string that satisfies all the requirements. Print \"NO\" if there are no such strings. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["3\n2 2 1 0\n1 1 1 1\n1 2 3 2"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteIn the first testcase strings \"ABCAB\" or \"BCABA\" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string \"CABBCC\" satisfies the requirements. There exist other possible strings."}, "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.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}"}, {"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"} {"nl": {"description": "Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000)\u00a0\u2014 then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009366), providing that the i-th friend can come to the party from day ai to day bi inclusive.", "output_spec": "Print the maximum number of people that may come to Famil Door's party.", "sample_inputs": ["4\nM 151 307\nF 343 352\nF 117 145\nM 24 128", "6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample, friends 3 and 4 can come on any day in range [117,\u2009128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140."}, "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 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}"}, {"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"} {"nl": {"description": "There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet \u2014 the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: alloc n \u2014 to allocate n bytes of the memory and return the allocated block's identifier x; erase x \u2014 to erase the block with the identifier x; defragment \u2014 to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.", "input_spec": "The first line of the input data contains two positive integers t and m (1\u2009\u2264\u2009t\u2009\u2264\u2009100;1\u2009\u2264\u2009m\u2009\u2264\u2009100), where t \u2014 the amount of operations given to the memory manager for processing, and m \u2014 the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment. ", "output_spec": "Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.", "sample_inputs": ["6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6"], "sample_outputs": ["1\n2\nNULL\n3"], "notes": null}, "positive_code": [{"source_code": "object P7B {\n def main(args : Array[String]) {\n val Array(t, m) = readLine split ' ' map {_.toInt}\n var b = collection.mutable.Buffer.fill(m){0}\n val curr = Iterator from 1\n val cAlloc = \"alloc (.*)\".r\n val cErase = \"erase (.*)\".r\n val cDefrag = \"defragment\".r\n for (_ <- 1 to t) readLine match {\n case cAlloc(nS) => {\n val n = nS.toInt\n val k = b.scanLeft(0){\n (p0, x) => if (x == 0) p0 + 1 else 0\n }.indexWhere(_ >= n.toInt) - 1\n if (k >= 0) {\n val x = curr.next\n println(x)\n for (i <- k - n + 1 to k) b(i) = x\n } else println(\"NULL\")\n }\n case cErase(xS) => {\n val x = xS.toInt\n if (x > 0 && (b contains x)) {\n b = b map {bi => if (bi == x) 0 else bi}\n } else println(\"ILLEGAL_ERASE_ARGUMENT\")\n }\n case cDefrag() => {\n b = b filter {_ != 0}\n while (b.size < m) b += 0\n }\n }\n }\n}\n"}], "negative_code": [{"source_code": "object P7B {\n def main(args : Array[String]) {\n val Array(t, m) = readLine split ' ' map {_.toInt}\n var b = collection.mutable.Buffer.fill(m){0}\n val curr = Iterator from 1\n val cAlloc = \"alloc (.*)\".r\n val cErase = \"erase (.*)\".r\n val cDefrag = \"defragment\".r\n for (_ <- 1 to t) readLine match {\n case cAlloc(nS) => {\n val n = nS.toInt\n val k = b.scanLeft(0){\n (p0, x) => if (x == 0) p0 + 1 else 0\n }.indexWhere(_ >= n.toInt) - 1\n if (k >= 0) {\n val x = curr.next\n println(x)\n for (i <- k - n + 1 to k) b(i) = x\n } else println(\"NULL\")\n println(b)\n }\n case cErase(xS) => {\n val x = xS.toInt\n if (b contains x) {\n b = b map {bi => if (bi == x) 0 else bi}\n } else println(\"ILLEGAL_ERASE_ARGUMENT\")\n println(b)\n }\n case cDefrag() => {\n b = b filter {_ != 0}\n while (b.size < m) b += 0\n println(b)\n }\n }\n }\n}\n"}, {"source_code": "object P7B {\n def main(args : Array[String]) {\n val Array(t, m) = readLine split ' ' map {_.toInt}\n var b = collection.mutable.Buffer.fill(m){0}\n val curr = Iterator from 1\n val cAlloc = \"alloc (.*)\".r\n val cErase = \"erase (.*)\".r\n val cDefrag = \"defragment\".r\n for (_ <- 1 to t) readLine match {\n case cAlloc(nS) => {\n val n = nS.toInt\n val k = b.scanLeft(0){\n (p0, x) => if (x == 0) p0 + 1 else 0\n }.indexWhere(_ >= n.toInt) - 1\n if (k >= 0) {\n val x = curr.next\n println(x)\n for (i <- k - n + 1 to k) b(i) = x\n } else println(\"NULL\")\n }\n case cErase(xS) => {\n val x = xS.toInt\n if (b contains x) {\n b = b map {bi => if (bi == x) 0 else bi}\n } else println(\"ILLEGAL_ERASE_ARGUMENT\")\n }\n case cDefrag() => {\n b = b filter {_ != 0}\n while (b.size < m) b += 0\n }\n }\n }\n}\n"}], "src_uid": "a6cba17c5ddb93f6741e00280fb6c54c"} {"nl": {"description": "You are given a multiset (i.\u00a0e. a set that can contain multiple equal integers) containing $$$2n$$$ integers. Determine if you can split it into exactly $$$n$$$ pairs (i.\u00a0e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i.\u00a0e. when divided by $$$2$$$, the remainder is $$$1$$$).", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\leq t\\leq 100$$$) \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\\leq n\\leq 100$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1,a_2,\\dots, a_{2n}$$$ ($$$0\\leq a_i\\leq 100$$$) \u2014 the numbers in the set.", "output_spec": "For each test case, print \"Yes\" if it can be split into exactly $$$n$$$ pairs so that the sum of the two elements in each pair is odd, and \"No\" otherwise. You can print each letter in any case.", "sample_inputs": ["5\n2\n2 3 4 5\n3\n2 3 4 5 5 5\n1\n2 4\n1\n2 3\n4\n1 5 3 2 6 7 3 4"], "sample_outputs": ["Yes\nNo\nNo\nYes\nNo"], "notes": "NoteIn the first test case, a possible way of splitting the set is $$$(2,3)$$$, $$$(4,5)$$$.In the second, third and fifth test case, we can prove that there isn't any possible way.In the fourth test case, a possible way of splitting the set is $$$(2,3)$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given strings $$$S$$$ and $$$T$$$, consisting of lowercase English letters. It is guaranteed that $$$T$$$ is a permutation of the string abc. Find string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.String $$$a$$$ is a permutation of string $$$b$$$ if the number of occurrences of each distinct character is the same in both strings.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a string $$$S$$$ ($$$1 \\le |S| \\le 100$$$), consisting of lowercase English letters. The second line of each test case contains a string $$$T$$$ that is a permutation of the string abc. (Hence, $$$|T| = 3$$$). Note that there is no limit on the sum of $$$|S|$$$ across all test cases.", "output_spec": "For each test case, output a single string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.", "sample_inputs": ["7\nabacaba\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabc\nac\nabc"], "sample_outputs": ["aaaacbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nac"], "notes": "NoteIn the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence."}, "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 s = readLine()\n val t = readLine()\n val aCount = s.count(_ == 'a')\n val bCount = s.count(_ == 'b')\n val cCount = s.count(_ == 'c')\n\n val answer = if (aCount == 0 || bCount == 0 || cCount == 0) s.sorted else {\n val remainingString = s.filter(c => c != 'a' && c != 'b' && c != 'c').sorted.mkString(\"\")\n\n def mkFragment(count: Int, letter: Char) = 1.to(count).map(_ => letter).mkString\n\n val prefix = if (t != \"abc\") mkFragment(aCount, 'a') + mkFragment(bCount, 'b') + mkFragment(cCount, 'c')\n else mkFragment(aCount, 'a') + mkFragment(cCount, 'c') + mkFragment(bCount, 'b')\n prefix + remainingString\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": [{"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 s = readLine()\n val t = readLine()\n val aCount = s.count(_ == 'a')\n val bCount = s.count(_ == 'b')\n val cCount = s.count(_ == 'c')\n val remainingString = s.filter(c => c != 'a' && c != 'b' && c != 'c').sorted.mkString(\"\")\n\n def mkFragment(count: Int, letter: Char) = 1.to(count).map(_ => letter).mkString\n\n val answer = if (aCount == 0 || bCount == 0 || cCount == 0) s else {\n val prefix = if (t != \"abc\") mkFragment(aCount, 'a') + mkFragment(bCount, 'b') + mkFragment(cCount, 'c')\n else mkFragment(aCount, 'a') + mkFragment(cCount, 'c') + mkFragment(bCount, 'b')\n prefix + remainingString\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"}], "src_uid": "419ef3579fe142c295ec4d89ee7becfc"} {"nl": {"description": "You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset. ", "input_spec": "First line contains three integers n, k and m (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the numbers in the multiset.", "output_spec": "If it is not possible to select k numbers in the desired way, output \u00abNo\u00bb (without the quotes). Otherwise, in the first line of output print \u00abYes\u00bb (without the quotes). In the second line print k integers b1,\u2009b2,\u2009...,\u2009bk\u00a0\u2014 the selected numbers. If there are multiple possible solutions, print any of them. ", "sample_inputs": ["3 2 3\n1 8 4", "3 3 3\n1 8 4", "4 3 5\n2 7 7 7"], "sample_outputs": ["Yes\n1 4", "No", "Yes\n2 7 7"], "notes": null}, "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\n\nobject B_441 { 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 l1 = readLine \n val n = l1.int\n val k = l1.int\n val m = l1.int\n val l2 = readLine\n val numbers = (1 to n).map(x => l2.int).toArray.sorted\n \n val groups = numbers.groupBy(x => x % m)\n val max = groups.values.reduce((a,b) => if (a.size > b.size) a else b) \n \n debug(\"max = \" + max.mkString(\" \"))\n \n //---------------------------- parameters reading :end\n \n val res = if (max.size >= k) {\n \"Yes\\n\" + max.take(k).mkString(\" \")\n } else {\n \"No\"\n }\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 = \"\"\"\n3 2 3\n1 8 4\n\"\"\"\n\nval sa2 = \"\"\"\n3 3 3\n1 8 4\n\"\"\"\n\nval sa3 = \"\"\"\n4 3 5\n2 7 7 7 \n\"\"\"\n}\n\n}\n\n"}], "negative_code": [], "src_uid": "55bd1849ef13b52788a0b5685c4fcdac"} {"nl": {"description": "Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string \"0011\" and string \"0110\" is |0\u2009-\u20090|\u2009+\u2009|0\u2009-\u20091|\u2009+\u2009|1\u2009-\u20091|\u2009+\u2009|1\u2009-\u20090|\u2009=\u20090\u2009+\u20091\u2009+\u20090\u2009+\u20091\u2009=\u20092.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.", "input_spec": "The first line of the input contains binary string a (1\u2009\u2264\u2009|a|\u2009\u2264\u2009200\u2009000). The second line of the input contains binary string b (|a|\u2009\u2264\u2009|b|\u2009\u2264\u2009200\u2009000). Both strings are guaranteed to consist of characters '0' and '1' only.", "output_spec": "Print a single integer\u00a0\u2014 the sum of Hamming distances between a and all contiguous substrings of b of length |a|.", "sample_inputs": ["01\n00111", "0011\n0110"], "sample_outputs": ["3", "2"], "notes": "NoteFor the first sample case, there are four contiguous substrings of b of length |a|: \"00\", \"01\", \"11\", and \"11\". The distance between \"01\" and \"00\" is |0\u2009-\u20090|\u2009+\u2009|1\u2009-\u20090|\u2009=\u20091. The distance between \"01\" and \"01\" is |0\u2009-\u20090|\u2009+\u2009|1\u2009-\u20091|\u2009=\u20090. The distance between \"01\" and \"11\" is |0\u2009-\u20091|\u2009+\u2009|1\u2009-\u20091|\u2009=\u20091. Last distance counts twice, as there are two occurrences of string \"11\". The sum of these edit distances is 1\u2009+\u20090\u2009+\u20091\u2009+\u20091\u2009=\u20093.The second sample case is described in the statement."}, "positive_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): (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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array $$$a$$$ of $$$n$$$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $$$i$$$ such that $$$1 \\leq i < n$$$ and $$$a_{i} \\neq a_{i+1}$$$, delete both $$$a_i$$$ and $$$a_{i+1}$$$ from the array and put $$$a_{i}+a_{i+1}$$$ in their place. For example, for array $$$[7, 4, 3, 7]$$$ you can choose $$$i = 2$$$ and the array will become $$$[7, 4+3, 7] = [7, 7, 7]$$$. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by $$$1$$$. What is the shortest possible length of the password after some number (possibly $$$0$$$) of operations?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the password. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},\\dots,a_{n}$$$ ($$$1 \\leq a_{i} \\leq 10^9$$$)\u00a0\u2014 the initial contents of your password. The sum of $$$n$$$ over all test cases will not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each password, print one integer: the shortest possible length of the password after some number of operations.", "sample_inputs": ["2\n4\n2 1 3 1\n2\n420 420"], "sample_outputs": ["1\n2"], "notes": "NoteIn the first test case, you can do the following to achieve a length of $$$1$$$:Pick $$$i=2$$$ to get $$$[2, 4, 1]$$$Pick $$$i=1$$$ to get $$$[6, 1]$$$Pick $$$i=1$$$ to get $$$[7]$$$In the second test case, you can't perform any operations because there is no valid $$$i$$$ that satisfies the requirements mentioned above."}, "positive_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 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}"}, {"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"} {"nl": {"description": "This is an easier version of the problem. In this version $$$n \\le 1000$$$The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \\le a_i \\le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the number of plots. The second line contains the integers $$$m_1, m_2, \\ldots, m_n$$$ ($$$1 \\leq m_i \\leq 10^9$$$)\u00a0\u2014 the limit on the number of floors for every possible number of floors for a skyscraper on each plot.", "output_spec": "Print $$$n$$$ integers $$$a_i$$$\u00a0\u2014 the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.", "sample_inputs": ["5\n1 2 3 2 1", "3\n10 6 8"], "sample_outputs": ["1 2 3 2 1", "10 6 6"], "notes": "NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal."}, "positive_code": [{"source_code": "case class Solution(sum: Long, heights: List[Long])\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val n = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toLong).toList\n val s1 = solve(data)\n val s2 = solve(data.reverse)\n val max = (0 to n).map(i => solve(data, i)).maxBy(_.sum)\n println(max.heights.mkString(\" \"))\n\n def solve(data: List[Long], index: Int): Solution = {\n val firstPart = solve(data.take(index).reverse)\n val secondPart = solve(data.drop(index - 1))\n firstPart.heights match {\n case Nil => secondPart\n case _ => Solution(firstPart.sum + secondPart.sum - firstPart.heights.head, firstPart.heights.tail.reverse ::: secondPart.heights)\n }\n }\n\n def solve(data: List[Long]): Solution =\n data match {\n case Nil => Solution(0, Nil)\n case _ => val heights = data.tail.foldLeft(data.head, List(data.head)) {\n case ((max, list), nHeigh) => (Math.min(max, nHeigh), Math.min(max, nHeigh) :: list)\n }._2.reverse\n Solution(heights.sum, heights)\n }\n}\n\n"}], "negative_code": [{"source_code": "case class Solution(sum: Long, heights: List[Long])\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val n = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toLong).toList\n val s1 = solve(data)\n val s2 = solve(data.reverse)\n val max = (0 to n).map(i => solve(data, i)).maxBy(_.sum)\n println(max.heights.mkString(\" \"))\n\n def solve(data: List[Long], index: Int): Solution = {\n val firstPart = solve(data.take(index).reverse)\n val secondPart = solve(data.drop(index - 1))\n firstPart.heights match {\n case Nil => secondPart\n case _ => Solution(firstPart.sum + secondPart.sum, firstPart.heights.tail.reverse ::: secondPart.heights)\n }\n }\n\n def solve(data: List[Long]): Solution =\n data match {\n case Nil => Solution(0, Nil)\n case _ => val heights = data.tail.foldLeft(data.head, List(data.head)) {\n case ((max, list), nHeigh) => (Math.min(max, nHeigh), Math.min(max, nHeigh) :: list)\n }._2.reverse\n Solution(heights.sum, heights)\n }\n}\n\n"}, {"source_code": "case class Solution(sum: Int, heights: List[Int])\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val n = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toInt).toList\n val s1 = solve(data)\n val s2 = solve(data.reverse)\n val max = (0 to n).map(i => solve(data, i)).maxBy(_.sum)\n println(max.heights.mkString(\" \"))\n\n def solve(data: List[Int], index: Int): Solution = {\n val firstPart = solve(data.take(index).reverse)\n val secondPart = solve(data.drop(index - 1))\n firstPart.heights match {\n case Nil => secondPart\n case _ => Solution(firstPart.sum + secondPart.sum, firstPart.heights.tail.reverse ::: secondPart.heights)\n }\n }\n\n def solve(data: List[Int]): Solution =\n data match {\n case Nil => Solution(0, Nil)\n case _ => val heights = data.tail.foldLeft(data.head, List(data.head)) {\n case ((max, list), nHeigh) => (Math.min(max, nHeigh), Math.min(max, nHeigh) :: list)\n }._2.reverse\n Solution(heights.sum, heights)\n }\n}\n\n"}], "src_uid": "88e6cd9ef45b956be8bee5d4fedd5725"} {"nl": {"description": "Little Vasya has received a young builder\u2019s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.", "input_spec": "The first line contains an integer N (1\u2009\u2264\u2009N\u2009\u2264\u20091000) \u2014 the number of bars at Vasya\u2019s disposal. The second line contains N space-separated integers li \u2014 the lengths of the bars. All the lengths are natural numbers not exceeding 1000.", "output_spec": "In one line output two numbers \u2014 the height of the largest tower and their total number. Remember that Vasya should use all the bars.", "sample_inputs": ["3\n1 2 3", "4\n6 5 6 7"], "sample_outputs": ["1 3", "2 3"], "notes": null}, "positive_code": [{"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.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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn\u2019t think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the 2t pieces he ended up with t tickets, each of which was lucky.When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest.Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123.What maximum number of tickets could Vasya get after that?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009104) \u2014 the number of pieces. The second line contains n space-separated numbers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009108) \u2014 the numbers on the pieces. Vasya can only glue the pieces in pairs. Even if the number of a piece is already lucky, Vasya should glue the piece with some other one for it to count as lucky. Vasya does not have to use all the pieces. The numbers on the pieces an on the resulting tickets may coincide.", "output_spec": "Print the single number \u2014 the maximum number of lucky tickets that will be able to be restored. Don't forget that every lucky ticket is made of exactly two pieces glued together.", "sample_inputs": ["3\n123 123 99", "6\n1 1 1 23 10 3"], "sample_outputs": ["1", "1"], "notes": null}, "positive_code": [{"source_code": "object P043C extends App {\n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n val r0 = a.count(_%3 == 0)\n val r1 = a.count(_%3 == 1)\n val r2 = a.count(_%3 == 2)\n println(r0/2 + math.min(r1, r2))\n}\n"}], "negative_code": [], "src_uid": "8d7355b3f6aebe43c7975744263f5cf8"} {"nl": {"description": "There are n stone quarries in Petrograd.Each quarry owns mi dumpers (1\u2009\u2264\u2009i\u2009\u2264\u2009n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi\u2009+\u20091 stones in it, the third has xi\u2009+\u20092, and the mi-th dumper (the last for the i-th quarry) has xi\u2009+\u2009mi\u2009-\u20091 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone \u00abtolik\u00bb and the other one \u00abbolik\u00bb.", "input_spec": "The first line of the input contains one integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1\u2009\u2264\u2009xi,\u2009mi\u2009\u2264\u20091016) \u2014 the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.", "output_spec": "Output \u00abtolik\u00bb if the oligarch who takes a stone first wins, and \u00abbolik\u00bb otherwise.", "sample_inputs": ["2\n2 1\n3 2", "4\n1 1\n1 1\n1 1\n1 1"], "sample_outputs": ["tolik", "bolik"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nobject Nim extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val result = (0 until n).foldLeft(0L) {(acc, a) =>\n val xi = s.nextLong()\n val m = s.nextLong()\n val end = xi + m - 1\n acc ^ xoredSum(end) ^ xoredSum(xi - 1)\n }\n\n if (result > 0) {\n println(\"tolik\")\n } else {\n println(\"bolik\")\n }\n\n def xoredSum(a: Long): Long = {\n val b = a - 1\n (b - b % 4 to a).foldLeft(0L)(_ ^ _)\n }\n\n}\n"}], "negative_code": [], "src_uid": "55099493c66b003d4261310bf2cc8f93"} {"nl": {"description": "The integers shop sells $$$n$$$ segments. The $$$i$$$-th of them contains all integers from $$$l_i$$$ to $$$r_i$$$ and costs $$$c_i$$$ coins.Tomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of all segments in it.After shopping, Vasya will get some more integers as a gift. He will get integer $$$x$$$ as a gift if and only if all of the following conditions are satisfied: Vasya hasn't bought $$$x$$$. Vasya has bought integer $$$l$$$ that is less than $$$x$$$. Vasya has bought integer $$$r$$$ that is greater than $$$x$$$. Vasya can get integer $$$x$$$ as a gift only once so he won't have the same integers after receiving a gift.For example, if Vasya buys segment $$$[2, 4]$$$ for $$$20$$$ coins and segment $$$[7, 8]$$$ for $$$22$$$ coins, he spends $$$42$$$ coins and receives integers $$$2, 3, 4, 7, 8$$$ from these segments. He also gets integers $$$5$$$ and $$$6$$$ as a gift.Due to the technical issues only the first $$$s$$$ segments (that is, segments $$$[l_1, r_1], [l_2, r_2], \\ldots, [l_s, r_s]$$$) will be available tomorrow in the shop.Vasya wants to get (to buy or to get as a gift) as many integers as possible. If he can do this in differents ways, he selects the cheapest of them.For each $$$s$$$ from $$$1$$$ to $$$n$$$, find how many coins will Vasya spend if only the first $$$s$$$ segments will be available.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the number of segments in the shop. Each of next $$$n$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$, $$$c_i$$$ ($$$1 \\leq l_i \\leq r_i \\leq 10^9, 1 \\leq c_i \\leq 10^9$$$)\u00a0\u2014 the ends of the $$$i$$$-th segments and its cost. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output $$$n$$$ integers: the $$$s$$$-th ($$$1 \\leq s \\leq n$$$) of them should be the number of coins Vasia will spend in the shop if only the first $$$s$$$ segments will be available.", "sample_inputs": ["3\n2\n2 4 20\n7 8 22\n2\n5 11 42\n5 11 42\n6\n1 4 4\n5 8 9\n7 8 7\n2 10 252\n1 11 271\n1 10 1"], "sample_outputs": ["20\n42\n42\n42\n4\n13\n11\n256\n271\n271"], "notes": "NoteIn the first test case if $$$s = 1$$$ then Vasya can buy only the segment $$$[2, 4]$$$ for $$$20$$$ coins and get $$$3$$$ integers.The way to get $$$7$$$ integers for $$$42$$$ coins in case $$$s = 2$$$ is described in the statement.In the second test case note, that there can be the same segments in the shop."}, "positive_code": [{"source_code": "object B extends App {\r\n val A = (1e9 + 1).toInt\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 (0 until n).foldLeft((A, A), (0, A), (0, A)) { case (((l, lc), (r, rc), (s, sc)), _) =>\r\n val Array(li, ri, ci) = nextInts(3)\r\n val si = ri - li + 1\r\n\r\n val (ln, lnc) =\r\n if (li < l) (li, ci)\r\n else if (li == l) (li, ci min lc)\r\n else (l, lc)\r\n\r\n val (rn, rnc) =\r\n if (ri > r) (ri, ci)\r\n else if (ri == r) (ri, ci min rc)\r\n else (r, rc)\r\n\r\n val (sn, snc) =\r\n if (si > s) (si, ci)\r\n else if (si == s) (si, ci min sc)\r\n else (s, sc)\r\n\r\n val cost =\r\n if (sn == rn - ln + 1) snc.min(lnc + rnc)\r\n else (lnc + rnc)\r\n\r\n out.println(cost)\r\n\r\n ((ln, lnc), (rn, rnc), (sn, snc))\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": [{"source_code": "object B extends App {\r\n val A = (1e9 + 1).toInt\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 (0 until n).foldLeft((A, A), (0, A), (0, A)) { case (((l, lc), (r, rc), (s, sc)), _) =>\r\n val Array(li, ri, ci) = nextInts(3)\r\n val si = ri - li + 1\r\n\r\n val (ln, lnc) =\r\n if (li < l) (li, ci)\r\n else if (li == l) (li, ci min lc)\r\n else (l, lc)\r\n\r\n val (rn, rnc) =\r\n if (ri > r) (ri, ci)\r\n else if (ri == r) (ri, ri min rc)\r\n else (r, rc)\r\n\r\n val (sn, snc) =\r\n if (si > s) (si, ci)\r\n else if (si == s) (si, ci min sc)\r\n else (s, sc)\r\n\r\n val cost =\r\n if (sn == rn - ln + 1) snc min (lnc + rnc)\r\n else lnc + rnc\r\n\r\n out.println(cost)\r\n\r\n ((ln, lnc), (rn, rnc), (sn, snc))\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"}, {"source_code": "object B 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\r\n val segments = Array.fill(n)((0, 0, 0))\r\n (0 until n).foreach { i =>\r\n val Array(li, ri, ci) = nextInts(3)\r\n segments(i) = (li, ri, ci)\r\n }\r\n\r\n val prefixes = segments.zipWithIndex.drop(1).scanLeft((0, 0)) {\r\n case ((p, q), ((li, ri, ci), i)) if p != q =>\r\n val (lp, _, cp) = segments(p)\r\n val (_, rq, cq) = segments(q)\r\n\r\n if (li == lp && ri == rq) if (ci <= cp + cq) (i, i) else (p, q)\r\n else if (li == lp && ri > rq || li < lp && ri == rq) (i, i)\r\n else\r\n (\r\n if (li < lp) i\r\n else if (li == lp) if (ci <= cp) i else p\r\n else p,\r\n if (ri > rq) i\r\n else if (ri == rq) if (ci <= cq) i else q\r\n else q\r\n )\r\n case ((j, _), ((li, ri, ci), i)) =>\r\n val (lj, rj, cj) = segments(j)\r\n\r\n if (li < lj && ri > rj) (i, i)\r\n else if (li < lj) (i, if (ri > rj) i else if (ri == rj) if (ci <= cj) i else j else j)\r\n else if (ri > rj) (if (li < lj) i else if (li == lj) if (ci <= cj) i else j else j, i)\r\n else (j, j)\r\n }\r\n\r\n val costs = prefixes.map {\r\n case (i, j) if i != j => segments(i)._3 + segments(j)._3\r\n case (i, _) => segments(i)._3\r\n }\r\n\r\n costs.foreach(out.println)\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"}], "src_uid": "ee773d908fc297cc692aaecf6af299c9"} {"nl": {"description": "While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface. Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$?", "input_spec": "The only line contains two integers $$$H$$$ and $$$L$$$ ($$$1 \\le H < L \\le 10^{6}$$$).", "output_spec": "Print a single number\u00a0\u2014 the depth of the lake at point $$$A$$$. The absolute or relative error should not exceed $$$10^{-6}$$$. Formally, let your answer be $$$A$$$, and the jury's answer be $$$B$$$. Your answer is accepted if and only if $$$\\frac{|A - B|}{\\max{(1, |B|)}} \\le 10^{-6}$$$.", "sample_inputs": ["1 2", "3 5"], "sample_outputs": ["1.5000000000000", "2.6666666666667"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of n words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section).The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph x (1\u2009\u2264\u2009x\u2009\u2264\u2009c\u2009-\u20091) is replaced with hieroglyph (x\u2009+\u20091), and hieroglyph c is replaced with hieroglyph 1.Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically.", "input_spec": "The first line of the input contains two integers n and c (2\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000, 1\u2009\u2264\u2009c\u2009\u2264\u2009106)\u00a0\u2014 the number of words, written on the lock, and the number of different hieroglyphs. Each of the following n lines contains the description of one word. The i-th of these lines starts with integer li (1\u2009\u2264\u2009li\u2009\u2264\u2009500\u2009000), that denotes the length of the i-th word, followed by li integers wi,\u20091, wi,\u20092, ..., wi,\u2009li (1\u2009\u2264\u2009wi,\u2009j\u2009\u2264\u2009c)\u00a0\u2014 the indices of hieroglyphs that make up the i-th word. Hieroglyph with index 1 is the smallest in the alphabet and with index c\u00a0\u2014 the biggest. It's guaranteed, that the total length of all words doesn't exceed 106.", "output_spec": "If it is possible to open the door by rotating the round switch, print integer x (0\u2009\u2264\u2009x\u2009\u2264\u2009c\u2009-\u20091) that defines the required number of clockwise rotations. If there are several valid x, print any of them. If it is impossible to open the door by this method, print \u2009-\u20091.", "sample_inputs": ["4 3\n2 3 2\n1 1\n3 2 3 1\n4 2 3 1 2", "2 5\n2 4 2\n2 4 2", "4 4\n1 2\n1 3\n1 4\n1 2"], "sample_outputs": ["1", "0", "-1"], "notes": "NoteWord a1,\u2009a2,\u2009...,\u2009am of length m is lexicographically not greater than word b1,\u2009b2,\u2009...,\u2009bk of length k, if one of two conditions hold: at first position i, such that ai\u2009\u2260\u2009bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character in the first position where they differ; if there is no such position i and m\u2009\u2264\u2009k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.In the first sample, after the round switch is rotated 1 position clockwise the words look as follows:1 323 1 23 1 2 3In the second sample, words are already sorted in lexicographical order.In the last sample, one can check that no shift of the alphabet will work."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by allen on 16-11-2.\n */\nobject Main {\n\n class SegT {\n var tag : Array[Int] = new Array[Int](1000002 * 2)\n var arr : Array[Int] = new Array[Int](1000002 * 2)\n def ida(l : Int, r : Int) : Int = (l + r) | (if(l != r) 1 else 0)\n def reset() : Unit = for(i <- 0 until 1000002*2) { arr(i) = 0; tag(i) = 0; }\n def pushdown(l : Int, r : Int) : Unit = {\n val id = ida(l, r)\n if(tag(id) != 0) {\n val mid = (l + r) >> 1\n val lc = ida(l, mid)\n if(lc != id) {\n tag(lc) += tag(id)\n arr(lc) += tag(id) * (mid - l + 1)\n }\n val rc = ida(mid + 1, r)\n if (mid + 1 <= r && rc != id) {\n tag(rc) += tag(id)\n arr(rc) += tag(id) * (r - mid)\n }\n tag(id) = 0\n }\n }\n def add(v : Int, ql : Int, qr : Int, l : Int, r : Int) : Unit = {\n val id = ida(l, r)\n pushdown(l, r)\n if(ql == l && qr == r) {\n tag(id) = tag(id) + v\n arr(id) = arr(id) + (r - l + 1) * v\n return\n }\n val m = l + r >> 1\n if(qr <= m) add(v, ql, qr, l, m)\n else if(m < ql) add(v, ql, qr, m + 1, r)\n else {\n add(v, ql, m, l, m)\n add(v, m + 1, qr, m + 1, r)\n }\n }\n\n def pushdownall(l : Int, r : Int) : Unit = {\n pushdown(l, r)\n if(l == r) return\n val m = l + r >> 1\n pushdownall(l, m)\n pushdownall(m + 1, r)\n }\n\n def query(l : Int, r : Int) : Int = arr(ida(l, r))\n\n }\n\n class Input(val n : Int, val c : Int, var arr : Array[Array[Int]]) {\n\n }\n\n def read(): Input = {\n val n::c::_ = StdIn.readLine().split(' ').map((a:String) => { a.toInt }).toList\n val arr = (for(i <- 0 until n) yield StdIn.readLine.split(' ').map((a:String) => { a.toInt }).drop(1)).toArray\n new Input(n, c, arr)\n }\n\n def alter(a1: Array[Int], a2: Array[Int]) : Unit = {\n val sz = if(a1.length < a2.length) a1.length else a2.length\n def x(): Boolean = {\n for (i <- 0 until sz) {\n //printf(\"%d vs %d \\n\", a1(i), a2(i))\n if (a1(i) != a2(i)) {\n if (a1(i) < a2(i)) {\n st.add(1, 0 + 1, dt.c - a2(i) + 1, 1, n + 1)\n //printf(\"[%d, %d]\\n\", 0, dt.c - a2(i))\n if (a1(i) > 1) {\n //printf(\"%d???\", a1(i))\n st.add(1, 1 + dt.c - a1(i) + 1, 1 + dt.c - a1(i) + 1 + a1(i) - 2, 1, n + 1)\n //printf(\"[%d, %d]\\n\", dt.c - a1(i) + 1, dt.c - a1(i) + 1 + a1(i) - 2)\n }\n else Unit\n } else {\n val base = dt.c - a1(i) + 1; // base to 1\n st.add(1, 1 + base, 1 + dt.c - a2(i), 1, n + 1)\n\n //printf(\"[%d, %d]\\n\", base, dt.c - (a2(i)))\n }\n return true\n }\n }\n return false\n }\n if(!x && a1.length <= a2.length) {\n st.add(1, 1, n + 1, 1, n + 1)\n //printf(\"[%d, %d]\\n\", 0, n)\n }\n //printf(\"---\\n\")\n }\n\n var st = new SegT()\n val dt = read()\n val n = dt.c\n def main(args: Array[String]): Unit = {\n st.reset()\n for(i <- 1 until dt.n) {\n alter(dt.arr(i - 1), dt.arr(i))\n }\n st.pushdownall(1, n + 1)\n def x() : Unit = {\n for(i <- 1 to n + 1) {\n //printf(\"%d\\n\", st.query(i, i))\n if(st.query(i, i) == dt.n - 1) {\n printf(\"%d\\n\", i - 1)\n return\n }\n }\n printf(\"-1\\n\")\n }\n x()\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * Created by allen on 16-11-2.\n */\nobject Main {\n\n class SegT {\n var tag : Array[Int] = new Array[Int](1000002 * 2)\n var arr : Array[Int] = new Array[Int](1000002 * 2)\n def ida(l : Int, r : Int) : Int = l + r | (if(l != r) 1 else 0)\n def reset() : Unit = for(i <- 0 until 1000002*2) { arr(i) = 0; tag(i) = 0; }\n def pushdown(l : Int, r : Int) : Unit = {\n val id = ida(l, r)\n if(tag(id) != 0) {\n val mid = l + r >> 1\n val lc = ida(l, mid)\n if(lc != id) {\n tag(lc) += tag(id)\n arr(lc) += tag(id) * (mid - l + 1)\n }\n val rc = ida(mid + 1, r)\n if (mid + 1 <= r && rc != id) {\n tag(rc) += tag(rc)\n arr(rc) += tag(id) * (r - mid)\n }\n tag(id) = 0\n }\n }\n def add(v : Int, ql : Int, qr : Int, l : Int, r : Int) : Unit = {\n val id = ida(l, r)\n pushdown(l, r)\n if(ql == l && qr == r) {\n tag(id) = tag(id) + v\n arr(id) = arr(id) + (r - l + 1) * v\n return\n }\n val m = l + r >> 1\n if(qr <= m) add(v, ql, qr, l, m)\n else if(m < ql) add(v, ql, qr, m + 1, r)\n else {\n add(v, ql, m, l, m)\n add(v, m + 1, qr, m + 1, r)\n }\n }\n\n def pushdownall(l : Int, r : Int) : Unit = {\n pushdown(l, r)\n val m = l + r >> 1\n pushdown(l, m)\n pushdown(m + 1, r)\n if(l == r) return\n pushdownall(l, m)\n pushdownall(m + 1, r)\n }\n\n def query(l : Int, r : Int) : Int = arr(ida(l, r))\n\n }\n\n class Input(val n : Int, val c : Int, var arr : Array[Array[Int]]) {\n\n }\n\n def read(): Input = {\n val n::c::_ = StdIn.readLine().split(' ').map((a:String) => { a.toInt }).toList\n val arr = (for(i <- 0 until n) yield StdIn.readLine.split(' ').map((a:String) => { a.toInt }).drop(1)).toArray\n new Input(n, c, arr)\n }\n\n def alter(a1: Array[Int], a2: Array[Int]) : Unit = {\n val sz = if(a1.length < a2.length) a1.length else a2.length\n def x(): Boolean = {\n for (i <- 0 until sz) {\n //printf(\"%d vs %d \\n\", a1(i), a2(i))\n if (a1(i) != a2(i)) {\n if (a1(i) < a2(i)) {\n st.add(1, 0 + 1, dt.c - a2(i) + 1, 1, n + 1)\n //printf(\"[%d, %d]\\n\", 0, dt.c - a2(i))\n if (a1(i) > 1) {\n //printf(\"%d???\", a1(i))\n st.add(1, 1 + dt.c - a1(i) + 1, 1 + dt.c - a1(i) + 1 + a1(i) - 2, 1, n + 1)\n //printf(\"[%d, %d]\\n\", dt.c - a1(i), dt.c - a1(i) + 1 + a1(i) - 2)\n }\n else Unit\n } else {\n val base = dt.c - a1(i) + 1; // base to 1\n st.add(1, 1 + base, 1 + dt.c - a2(i), 1, n + 1)\n\n //printf(\"[%d, %d]\\n\", base, dt.c - (a2(i)))\n }\n return true\n }\n }\n return false\n }\n if(!x && a1.length <= a2.length) {\n st.add(1, 1, n + 1, 1, n + 1)\n //printf(\"[%d, %d]\\n\", 0, n)\n }\n //printf(\"---\\n\")\n }\n\n var st = new SegT()\n val dt = read()\n val n = dt.c\n def main(args: Array[String]): Unit = {\n st.reset()\n for(i <- 1 until dt.n) {\n alter(dt.arr(i - 1), dt.arr(i))\n }\n st.pushdownall(1, n + 1)\n def x() : Unit = {\n for(i <- 1 to n + 1) {\n //printf(\"%d\\n\", st.query(i, i))\n if(st.query(i, i) == dt.n - 1) {\n printf(\"%d\\n\", i - 1)\n return\n }\n }\n printf(\"-1\\n\")\n }\n x()\n }\n}\n"}], "src_uid": "040171969b25ad9be015d95586890cf0"} {"nl": {"description": "Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), which represents how many numbers the array has. The next line contains n space-separated integers \u2014 the array's description. All elements of the array lie in the range from 1 to 109, inclusive.", "output_spec": "Print n space-separated integers \u2014 the minimum possible values of each array element after one replacement and the sorting are performed.", "sample_inputs": ["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"], "sample_outputs": ["1 1 2 3 4", "1 2 3 4 5", "1 2 2"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "You are given an equation: Ax2\u2009+\u2009Bx\u2009+\u2009C\u2009=\u20090. Your task is to find the number of distinct roots of the equation and print all of them in ascending order.", "input_spec": "The first line contains three integer numbers A,\u2009B and C (\u2009-\u2009105\u2009\u2264\u2009A,\u2009B,\u2009C\u2009\u2264\u2009105). Any coefficient may be equal to 0.", "output_spec": "In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.", "sample_inputs": ["1 -5 6"], "sample_outputs": ["2\n2.0000000000\n3.0000000000"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?Note that outcome of a match can not be a draw, it has to be either win or loss.", "input_spec": "The first line of the input contains a single integer corresponding to number of test cases t (1\u2009\u2264\u2009t\u2009\u2264\u2009105). Each of the next t lines will contain four space-separated integers n,\u2009k,\u2009d1,\u2009d2 (1\u2009\u2264\u2009n\u2009\u2264\u20091012;\u00a00\u2009\u2264\u2009k\u2009\u2264\u2009n;\u00a00\u2009\u2264\u2009d1,\u2009d2\u2009\u2264\u2009k) \u2014 data for the current test case.", "output_spec": "For each test case, output a single line containing either \"yes\" if it is possible to have no winner of tournament, or \"no\" otherwise (without quotes).", "sample_inputs": ["5\n3 0 0 0\n3 3 0 0\n6 4 1 0\n6 3 3 0\n3 3 3 2"], "sample_outputs": ["yes\nyes\nyes\nno\nno"], "notes": "NoteSample 1. There has not been any match up to now (k\u2009=\u20090,\u2009d1\u2009=\u20090,\u2009d2\u2009=\u20090). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.Sample 2. You missed all the games (k\u2009=\u20093). As d1\u2009=\u20090 and d2\u2009=\u20090, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is \"yes\".Sample 3. You missed 4 matches, and d1\u2009=\u20091,\u2009d2\u2009=\u20090. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins)."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1,\u2009a2,\u2009... an. Nicholas does not want to break the sticks or glue them together. To make a h\u2009\u00d7\u2009w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h\u2009=\u2009w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009100).", "output_spec": "Print the single number \u2014 the maximum number of frames Nicholas can make for his future canvases.", "sample_inputs": ["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"], "sample_outputs": ["1", "3", "0"], "notes": null}, "positive_code": [{"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.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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "f9b56b3fddcd5db0d0671714df3f8646"} {"nl": {"description": "You are given $$$n$$$ numbers $$$a_1, a_2, \\dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \\cdot a_2$$$ $$$\\dots$$$ $$$\\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\\cdot (-1) \\cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$)\u00a0\u2014 the numbers.", "output_spec": "Output a single number\u00a0\u2014 the minimal number of coins you need to pay to make the product equal to $$$1$$$.", "sample_inputs": ["2\n-1 1", "4\n0 0 0 0", "5\n-5 -3 5 3 0"], "sample_outputs": ["2", "4", "13"], "notes": "NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are organizing a boxing tournament, where $$$n$$$ boxers will participate ($$$n$$$ is a power of $$$2$$$), and your friend is one of them. All boxers have different strength from $$$1$$$ to $$$n$$$, and boxer $$$i$$$ wins in the match against boxer $$$j$$$ if and only if $$$i$$$ is stronger than $$$j$$$.The tournament will be organized as follows: $$$n$$$ boxers will be divided into pairs; the loser in each pair leaves the tournament, and $$$\\frac{n}{2}$$$ winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.Furthermore, during each stage you distribute the boxers into pairs as you wish.The boxer with strength $$$i$$$ can be bribed if you pay him $$$a_i$$$ dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 2^{18}$$$) \u2014 the number of boxers. $$$n$$$ is a power of $$$2$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ is the number of dollars you have to pay if you want to bribe the boxer with strength $$$i$$$. Exactly one of $$$a_i$$$ is equal to $$$-1$$$ \u2014 it means that the boxer with strength $$$i$$$ is your friend. All other values are in the range $$$[1, 10^9]$$$.", "output_spec": "Print one integer \u2014 the minimum number of dollars you have to pay so your friend wins.", "sample_inputs": ["4\n3 9 1 -1", "8\n11 -1 13 19 24 7 17 5"], "sample_outputs": ["0", "12"], "notes": "NoteIn the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.In the second test case you can distribute boxers as follows (your friend is number $$$2$$$):$$$1 : 2, 8 : 5, 7 : 3, 6 : 4$$$ (boxers $$$2, 8, 7$$$ and $$$6$$$ advance to the next stage);$$$2 : 6, 8 : 7$$$ (boxers $$$2$$$ and $$$8$$$ advance to the next stage, you have to bribe the boxer with strength $$$6$$$);$$$2 : 8$$$ (you have to bribe the boxer with strength $$$8$$$);"}, "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 /**\n * log2\u3057\u3066\u5c0f\u6570\u70b9\u5207\u308a\u6368\u3066\u305f\u3082\u306e\n */\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N - 1)\n val ix = A.indexWhere(_ == -1)\n TO(ix, N - 2) { i =>\n B(i) = A(i + 1)\n }\n\n var k = log2(N) - 1\n val minimum = new java.util.PriorityQueue[Int]\n var ans = B(N - 2).toLong\n var i = N - 3\n while(k > 0) {\n REP(1 << k) { _ =>\n minimum.add(B(i))\n i -= 1\n }\n ans += minimum.poll()\n k -= 1\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[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 /**\n * log2\u3057\u3066\u5c0f\u6570\u70b9\u5207\u308a\u6368\u3066\u305f\u3082\u306e\n */\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n i\n }\n\n case class Entry(a: Int, i: 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util\n import java.util.Comparator\n val N = ni()\n val A = na(N)\n val ix = A.indexWhere(_ == -1)\n\n var ans = 0L\n val q = new util.TreeSet[Entry](new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = {\n if (o1.a == o2.a) {\n Integer.compare(o2.i, o1.i) // \u964d\u9806\n } else {\n Integer.compare(o2.a, o1.a) // \u964d\u9806\n }\n }\n })\n val remains = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = Integer.compare(o2, o1) // \u964d\u9806\n })\n TO(ix + 1, N - 1) { i =>\n q.add(Entry(A(i), i))\n remains.add(i)\n }\n\n var k = log2(N) - 1\n while(!remains.isEmpty) {\n val i = remains.pollFirst()\n q.remove(Entry(A(i), i))\n debug(s\"k:$k A(i):${A(i)}\")\n ans += A(i)\n REP(min(q.size(), (1 << k) - 1)) { _ =>\n val entry = q.pollFirst()\n remains.remove(entry.i)\n }\n k -= 1\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[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 /**\n * log2\u3057\u3066\u5c0f\u6570\u70b9\u5207\u308a\u6368\u3066\u305f\u3082\u306e\n */\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val B = Array.ofDim[Int](N - 1)\n val ix = A.indexWhere(_ == -1)\n TO(ix, N - 2) { i =>\n B(i) = A(i + 1)\n }\n\n var k = log2(N) - 1\n val minimum = new java.util.PriorityQueue[Int]\n var ans = B(N - 2)\n var i = N - 3\n while(k > 0) {\n REP(1 << k) { _ =>\n minimum.add(B(i))\n i -= 1\n }\n ans += minimum.poll()\n k -= 1\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[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 /**\n * log2\u3057\u3066\u5c0f\u6570\u70b9\u5207\u308a\u6368\u3066\u305f\u3082\u306e\n */\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n i\n }\n\n case class Entry(a: Int, i: 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util\n import java.util.Comparator\n val N = ni()\n val A = na(N)\n val ix = A.indexWhere(_ == -1)\n\n var ans = 0L\n val q = new util.TreeSet[Entry](new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = {\n if (o1.a == o2.a) {\n Integer.compare(o1.i, o2.i)\n } else {\n Integer.compare(o2.a, o1.a) // \u964d\u9806\n }\n }\n })\n val remains = new util.TreeSet[Int](new Comparator[Int] {\n override def compare(o1: Int, o2: Int): Int = Integer.compare(o2, o1) // \u964d\u9806\n })\n TO(ix + 1, N - 1) { i =>\n q.add(Entry(A(i), i))\n remains.add(i)\n }\n\n var k = log2(N) - 1\n while(!remains.isEmpty) {\n val i = remains.pollFirst()\n q.remove(Entry(A(i), i))\n debug(s\"k:$k A(i):${A(i)}\")\n ans += A(i)\n REP((1 << k) - 1) { _ =>\n val entry = q.pollFirst()\n remains.remove(entry.i)\n }\n k -= 1\n }\n\n out.println(ans)\n }\n}"}], "src_uid": "6b61c546e4bf5bd22e744ce1377cf569"} {"nl": {"description": "Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui,\u2009vi)\u2009<\u2009x\u2009<\u2009max(ui,\u2009vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k\u2009-\u20091 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u200980)\u00a0\u2014 the number of crossroads (and offices) and the number of offices Oleg wants to visit. The second line contains single integer m (0\u2009\u2264\u2009m\u2009\u2264\u20092000)\u00a0\u2014 the number of bicycle lanes in Bankopolis. The next m lines contain information about the lanes. The i-th of these lines contains three integers ui, vi and ci (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, 1\u2009\u2264\u2009ci\u2009\u2264\u20091000), denoting the crossroads connected by the i-th road and its difficulty.", "output_spec": "In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.", "sample_inputs": ["7 4\n4\n1 6 2\n6 2 2\n2 4 2\n2 7 1", "4 3\n4\n2 1 2\n1 3 2\n3 4 2\n4 1 1"], "sample_outputs": ["6", "3"], "notes": "NoteIn the first example Oleg visiting banks by path 1\u2009\u2192\u20096\u2009\u2192\u20092\u2009\u2192\u20094.Path 1\u2009\u2192\u20096\u2009\u2192\u20092\u2009\u2192\u20097 with smaller difficulity is incorrect because crossroad 2\u2009\u2192\u20097 passes near already visited office on the crossroad 6.In the second example Oleg can visit banks by path 4\u2009\u2192\u20091\u2009\u2192\u20093."}, "positive_code": [{"source_code": "import scala.collection.mutable\n// package main\n\n/**\n * Created by velizar on 12/05/17.\n */\nobject Main extends App {\n\n import scala.io.Source\n import collection.mutable.Map\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(n, k) = input(0)\n val Array(m) = input(1)\n val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }\n .filter{ case (from, to, _) => from != to }\n val nAug = n + 1\n val maxValue = 1000 * 80 + 20000 // = 100000\n\n // edges(from) = ArrayBuffer[(to, cost])\n val edges: Array[Vector[(Int, Int)]] = Array.fill(nAug)(Vector.empty)\n inputEdges.foreach { case (from, to, cost) =>\n val existingEdge = edges(from).find { case(dst, _) => dst == to }\n existingEdge match {\n case Some((_, prevCost)) if cost < prevCost =>\n val idx = edges(from).indexOf((to, prevCost))\n edges(from) = edges(from).updated(idx, (to, cost))\n case _ =>\n edges(from) = edges(from) :+ ((to, cost))\n }\n }\n for (i <- 0 until n)\n edges(n) = edges(n) :+ ((i, 0))\n\n /*\n val boundEdges = for {\n pos <- 0 until nAug\n } yield for {\n bound <- 0 until nAug\n } yield {\n val edgesPosB = for {\n (next, cost) <- edges(pos)\n if next != pos\n if bound != pos\n isLower = bound < pos\n if (isLower && next >= bound && next < pos) || (!isLower && next <= bound && next > pos)\n } yield (next, cost)\n edgesPosB.view.sortBy(_._2)\n }\n */\n\n val boundUnsortedEdges = for {\n pos <- 0 until nAug\n } yield for {\n bound <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if next != pos\n if bound != pos\n isLower = bound < pos\n if (isLower && next >= bound && next < pos) || (!isLower && next <= bound && next > pos)\n } yield (next, cost)\n\n\n /*\n // (cost, bound, pos, k)\n type State2 = (Int, Int, Int, Int)\n def nextEdges2(bound: Int, pos: Int, k: Int,\n costAcc: Int = 0, offset: Int = 0):\n Stream[State2] = {\n val (next, cost) = boundEdges(pos)(bound).lift(offset).getOrElse((0, maxValue))\n if (cost == maxValue)\n Stream.Empty\n else\n (costAcc + cost, bound min pos+1, next, k - 1) #::\n (costAcc + cost, pos-1 max bound, next, k - 1) #::\n nextEdges2(bound, pos, k, costAcc, offset + 1)\n }\n\n // (cost, lb, ub, pos, k)\n type State = (Int, Int, Int, Int, Int)\n def nextEdges(lb: Int, ub: Int, pos: Int, k: Int,\n costAcc: Int = 0, offsetS: Int = 0, offsetL: Int = 0):\n Stream[State] = {\n val smaller = smallerEdges(pos)(lb).lift(offsetS).getOrElse((0, maxValue))\n val larger = largerEdges(pos)(ub).lift(offsetL).getOrElse((0, maxValue))\n val (next, cost) = Seq(smaller, larger).minBy(_._2)\n if (cost == maxValue)\n Stream.Empty\n else if (cost == smaller._2)\n (costAcc + cost, lb, pos - 1, next, k - 1) #::\n nextEdges(lb, ub, pos, k, costAcc, offsetS + 1, offsetL)\n else\n (costAcc + cost, pos + 1, ub, next, k - 1) #::\n nextEdges(lb, ub, pos, k, costAcc, offsetS, offsetL + 1)\n }\n\n def solveDijkstra(lb: Int, ub: Int, pos: Int, k: Int): Option[Int] = {\n if (k == 0)\n return Some(0)\n val pq = mutable.PriorityQueue.empty[(State, Stream[State])](Ordering.by(-_._1._1))\n val firstState #:: firstStream = nextEdges(lb, ub, pos, k)\n pq += ((firstState, firstStream))\n var endState: Option[State] = None\n while (endState.isEmpty && pq.nonEmpty) {\n val ((cost, lb, ub, pos, k), currentStream) = pq.dequeue\n if (k == 0)\n endState = Some(cost, lb, ub, pos, k)\n val nextStream = nextEdges(lb, ub, pos, k, costAcc = cost)\n Seq(currentStream, nextStream).foreach {\n case Stream.Empty =>\n case (value #:: stream) => pq += ((value, stream))\n }\n }\n endState match {\n case Some((cost, _, _, _, _)) => Some(cost)\n case None => None\n }\n }\n */\n\n val memo = Map.empty[(Int, Int, Int), Int]\n\n def solveInner(bound: Int, pos: Int, k: Int): Int = {\n val minCost = boundUnsortedEdges(pos)(bound).map { case (next, cost) =>\n cost + solve(bound min pos+1, next, k - 1) min\n cost + solve(pos-1 max bound, next, k - 1)\n }.fold(maxValue)(_ min _)\n memo((bound, pos, k)) = minCost\n minCost\n }\n\n def solve(bound: Int, pos: Int, k: Int): Int = {\n if (k == 0) {\n 0\n } else {\n memo.get(bound, pos, k) match {\n case Some(s) => s\n case None => solveInner(bound, pos, k)\n }\n }\n }\n\n val res = solve(0, n, k)\n if (res == maxValue)\n print(-1)\n else\n print(res)\n}"}], "negative_code": [{"source_code": "// package main\n\n/**\n * Created by velizar on 12/05/17.\n */\nobject Main extends App {\n\n import scala.io.Source\n import collection.mutable.{ArrayBuffer, Map}\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(n, k) = input(0)\n val Array(m) = input(1)\n val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }\n .filter{ case (from, to, _) => from != to }\n val nAug = n + 1\n val maxValue = 1000 * 80 + 10000\n\n // edges(from) = ArrayBuffer[(to, cost])\n val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)\n inputEdges.foreach { case (from, to, cost) =>\n val existingEdge = edges(from).find { case(dst, _) => dst == to }\n existingEdge match {\n case Some((s: Int, prevCost: Int)) if prevCost < cost =>\n val idx = edges(from).indexOf((to, prevCost))\n edges(from)(idx) = (to, cost)\n case _ =>\n edges(from) += ((to, cost))\n }\n }\n for (i <- 0 until n)\n edges(n) += ((i, 0))\n\n val smallerEdges = for {\n pos <- 0 until nAug\n } yield for {\n lb <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if lb <= next\n if next < pos\n } yield (next, cost)\n\n val largerEdges = for {\n pos <- 0 until nAug\n } yield for {\n ub <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if pos < next\n if next <= ub\n } yield (next, cost)\n\n val memo = Map.empty[(Int, Int, Int, Int), Int]\n\n def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>\n cost + solve(lb, pos - 1, next, k - 1)\n }\n val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>\n cost + solve(pos + 1, ub, next, k - 1)\n }\n val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min\n memo((lb, ub, pos, k)) = minAns\n minAns\n }\n\n def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n if (k == 0) {\n 0\n } else {\n memo.get(lb, ub, pos, k) match {\n case Some(s) => s\n case None => solveInner(lb, ub, pos, k)\n }\n }\n }\n\n val res = solve(0, n - 1, n, k)\n val printableRes = if (res >= maxValue) -1 else res\n print(printableRes)\n}"}, {"source_code": "// package main\n\n/**\n * Created by velizar on 12/05/17.\n */\nobject Main extends App {\n\n import scala.io.Source\n import collection.mutable.{ArrayBuffer, Map}\n\n val input = Source.fromInputStream(System.in).getLines.toVector.dropRight(2).map(_.split(\" \").map(_.toInt))\n val Array(n, k) = input(0)\n val Array(m) = input(1)\n val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }\n .filter{ case (from, to, _) => from != to }\n val nAug = n + 1\n val maxValue = 1000 * 80 + 10000\n\n // edges(from) = ArrayBuffer[(to, cost])\n val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)\n inputEdges.foreach { case (from, to, cost) =>\n val existingEdge = edges(from).find { case(dst, _) => dst == to }\n existingEdge match {\n case Some((_, prevCost)) if prevCost < cost =>\n val idx = edges(from).indexOf((to, prevCost))\n edges(from)(idx) = (to, cost)\n case None =>\n edges(from) += ((to, cost))\n }\n }\n for (i <- 0 until n)\n edges(n) += ((i, 0))\n\n val smallerEdges = for {\n pos <- 0 until nAug\n } yield for {\n lb <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if lb <= next\n if next < pos\n } yield (next, cost)\n\n val largerEdges = for {\n pos <- 0 until nAug\n } yield for {\n ub <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if pos < next\n if next <= ub\n } yield (next, cost)\n\n val memo = Map.empty[(Int, Int, Int, Int), Int]\n\n def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>\n cost + solve(lb, pos - 1, next, k - 1)\n }\n val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>\n cost + solve(pos + 1, ub, next, k - 1)\n }\n val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min\n memo((lb, ub, pos, k)) = minAns\n minAns\n }\n\n def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n if (k == 0) {\n 0\n } else {\n memo.get(lb, ub, pos, k) match {\n case Some(s) => s\n case None => solveInner(lb, ub, pos, k)\n }\n }\n }\n\n val res = solve(0, n - 1, n, k)\n val printableRes = if (res >= maxValue) -1 else res\n print(printableRes)\n}\n"}, {"source_code": "// package main\n\n/**\n * Created by velizar on 12/05/17.\n */\nobject Main extends App {\n\n import scala.io.Source\n import collection.mutable.{ArrayBuffer, Map}\n\n val input = Source.fromInputStream(System.in).getLines.toVector.init.map(_.split(\" \").map(_.toInt))\n val Array(n, k) = input(0)\n val Array(m) = input(1)\n val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }\n .filter{ case (from, to, _) => from != to }\n val nAug = n + 1\n val maxValue = 1000 * 80 + 10000\n\n // edges(from) = ArrayBuffer[(to, cost])\n val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)\n inputEdges.foreach { case (from, to, cost) =>\n val existingEdge = edges(from).find { case(dst, _) => dst == to }\n existingEdge match {\n case Some((_, prevCost)) if prevCost < cost =>\n val idx = edges(from).indexOf((to, prevCost))\n edges(from)(idx) = (to, cost)\n case None =>\n edges(from) += ((to, cost))\n }\n }\n for (i <- 0 until n)\n edges(n) += ((i, 0))\n\n val smallerEdges = for {\n pos <- 0 until nAug\n } yield for {\n lb <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if lb <= next\n if next < pos\n } yield (next, cost)\n\n val largerEdges = for {\n pos <- 0 until nAug\n } yield for {\n ub <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if pos < next\n if next <= ub\n } yield (next, cost)\n\n val memo = Map.empty[(Int, Int, Int, Int), Int]\n\n def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>\n cost + solve(lb, pos - 1, next, k - 1)\n }\n val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>\n cost + solve(pos + 1, ub, next, k - 1)\n }\n val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min\n memo((lb, ub, pos, k)) = minAns\n minAns\n }\n\n def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n if (k == 0) {\n 0\n } else {\n memo.get(lb, ub, pos, k) match {\n case Some(s) => s\n case None => solveInner(lb, ub, pos, k)\n }\n }\n }\n\n val res = solve(0, n - 1, n, k)\n val printableRes = if (res >= maxValue) -1 else res\n print(printableRes)\n}\n"}, {"source_code": "// package main\n\n/**\n * Created by velizar on 12/05/17.\n */\nobject Main extends App {\n\n import scala.io.Source\n import collection.mutable.{ArrayBuffer, Map}\n\n val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(\" \").map(_.toInt))\n val Array(n, k) = input(0)\n val Array(m) = input(1)\n val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }\n .filter{ case (from, to, _) => from != to }\n val nAug = n + 1\n val maxValue = 1000 * 80 + 10000\n\n // edges(from) = ArrayBuffer[(to, cost])\n val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)\n inputEdges.foreach { case (from, to, cost) =>\n val existingEdge = edges(from).find { case(dst, _) => dst == to }\n existingEdge match {\n case Some((_, prevCost)) if cost < prevCost =>\n val idx = edges(from).indexOf((to, prevCost))\n edges(from)(idx) = (to, cost)\n case _ =>\n edges(from) += ((to, cost))\n }\n }\n for (i <- 0 until n)\n edges(n) += ((i, 0))\n\n val smallerEdges = for {\n pos <- 0 until nAug\n } yield for {\n lb <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if lb <= next\n if next < pos\n } yield (next, cost)\n\n val largerEdges = for {\n pos <- 0 until nAug\n } yield for {\n ub <- 0 until nAug\n } yield for {\n (next, cost) <- edges(pos)\n if pos < next\n if next <= ub\n } yield (next, cost)\n\n val memo = Map.empty[(Int, Int, Int, Int), Int]\n\n def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>\n cost + solve(lb, pos - 1, next, k - 1)\n }\n val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>\n cost + solve(pos + 1, ub, next, k - 1)\n }\n val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min\n memo((lb, ub, pos, k)) = minAns\n println((lb, ub, pos, k, minAns))\n minAns\n }\n\n def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {\n if (k == 0) {\n 0\n } else {\n memo.get(lb, ub, pos, k) match {\n case Some(s) => s\n case None => solveInner(lb, ub, pos, k)\n }\n }\n }\n\n val res = solve(0, n - 1, n, k)\n val printableRes = if (res >= maxValue) -1 else res\n print(printableRes)\n}"}], "src_uid": "aa0e8640f3930cfde32d98b82e789ff3"} {"nl": {"description": "After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $$$n$$$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string $$$s$$$ of length $$$n$$$, where $$$s_i = \\texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \\texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $$$s_1$$$) and his goal is to get to the last crossroad (which corresponds to $$$s_n$$$).If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \\ldots, j-1$$$ there is a bus station, one can pay $$$a$$$ roubles for the bus ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the bus (it is not necessary to have a bus station at the $$$j$$$-th crossroad). Formally, paying $$$a$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \\texttt{A}$$$ for all $$$i \\le t < j$$$. If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \\ldots, j-1$$$ there is a tram station, one can pay $$$b$$$ roubles for the tram ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the tram (it is not necessary to have a tram station at the $$$j$$$-th crossroad). Formally, paying $$$b$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \\texttt{B}$$$ for all $$$i \\le t < j$$$.For example, if $$$s$$$=\"AABBBAB\", $$$a=4$$$ and $$$b=3$$$ then Petya needs: buy one bus ticket to get from $$$1$$$ to $$$3$$$, buy one tram ticket to get from $$$3$$$ to $$$6$$$, buy one bus ticket to get from $$$6$$$ to $$$7$$$. Thus, in total he needs to spend $$$4+3+4=11$$$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $$$s_n$$$) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the $$$n$$$-th crossroad. After the party he has left with $$$p$$$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad $$$i$$$ to go on foot the first, so he has enough money to get from the $$$i$$$-th crossroad to the $$$n$$$-th, using only tram and bus tickets.", "input_spec": "Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). The first line of each test case consists of three integers $$$a, b, p$$$ ($$$1 \\le a, b, p \\le 10^5$$$)\u00a0\u2014 the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string $$$s$$$, where $$$s_i = \\texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \\texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad ($$$2 \\le |s| \\le 10^5$$$). It is guaranteed, that the sum of the length of strings $$$s$$$ by all test cases in one test doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print one number\u00a0\u2014 the minimal index $$$i$$$ of a crossroad Petya should go on foot. The rest of the path (i.e. from $$$i$$$ to $$$n$$$ he should use public transport).", "sample_inputs": ["5\n2 2 1\nBB\n1 1 1\nAB\n3 2 8\nAABBBBAABB\n5 3 4\nBBBBB\n2 1 1\nABABAB"], "sample_outputs": ["2\n1\n3\n1\n6"], "notes": null}, "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 cost = Array(0,0,0)\n val A = Array.fill(100001)(0)\n val DP = Array.fill(100001)(Array.fill(3)(0L))\n (1 to t).foreach{ _ =>\n val (a,b,p) = (in.nextInt(),in.nextInt(),in.nextInt())\n cost(0) = 0\n cost(1) = a\n cost(2) = b\n val s = in.next()\n s.zipWithIndex.foreach{ case (ch,i) =>\n A(i) = ch match {\n case 'A' => 1\n case 'B' => 2\n case _ => throw new IllegalArgumentException(\"wtf\")\n }\n }\n\n val n = s.length-1\n DP(n)(0) = 0L\n DP(n)(1) = 0L\n DP(n)(2) = 0L\n for{\n i <- (0 until n).reverse\n prev <- (0 to 2)\n }yield{\n if(A(i) == prev){\n DP(i)(prev) = 0L+DP(i+1)(prev)\n }else{\n DP(i)(prev) = cost(A(i)) + DP(i+1)(A(i))\n }\n }\n //println((0 to n).map(i => DP(i)(0)).mkString(\" - \"))\n val stationsOk = (0 to n).takeWhile(i => DP(i)(0) > p)\n out.println(stationsOk.length+1)\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": "0e4c297fcacdd0a304310882cd7c8a44"} {"nl": {"description": "There is a programming language in which every program is a non-empty sequence of \"<\" and \">\" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. Current character pointer (CP); Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence. If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. If CP is pointing to \"<\" or \">\" then the direction of DP changes to \"left\" or \"right\" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is \"<\" or \">\" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1,\u2009s2,\u2009...,\u2009sn of \"<\", \">\" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl,\u2009sl\u2009+\u20091,\u2009...,\u2009sr as an independent program in this language.", "input_spec": "The first line of input contains two integers n and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009105) \u2014 represents the length of the sequence s and the number of queries. The second line contains s, a sequence of \"<\", \">\" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces. The next q lines each contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) \u2014 the i-th query.", "output_spec": "For each query print 10 space separated integers: x0,\u2009x1,\u2009...,\u2009x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.", "sample_inputs": ["7 4\n1>3>22<\n1 3\n4 7\n7 7\n1 7"], "sample_outputs": ["0 1 0 1 0 0 0 0 0 0\n2 2 2 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n2 3 2 1 0 0 0 0 0 0"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings \"pop\", \"noon\", \"x\", and \"kkkkkk\" are palindromes, while strings \"moon\", \"tv\", and \"abab\" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 50$$$) \u2014 the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.", "output_spec": "In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.", "sample_inputs": ["3 3\ntab\none\nbat", "4 2\noo\nox\nxo\nxx", "3 5\nhello\ncodef\norces", "9 4\nabab\nbaba\nabcd\nbcde\ncdef\ndefg\nwxyz\nzyxw\nijji"], "sample_outputs": ["6\ntabbat", "6\noxxxxo", "0", "20\nababwxyzijjizyxwbaba"], "notes": "NoteIn the first example, \"battab\" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string."}, "positive_code": [{"source_code": "import collection.mutable.HashMap\n\nobject Main {\n def main(args: Array[String]) = {\n val Array(n, m) = readLine.split(\" \").map(_.toInt)\n val a = Array.tabulate(n)((_) => readLine)\n val x = f1(a)\n println(x.length)\n println(x)\n }\n def f1(a: Array[String]): String = {\n val f = HashMap[String, Int]()\n val b = HashMap[String, Int]()\n a.indices.foreach((i) => {\n if (a(i) == a(i).reverse) b.update(a(i), b.getOrElse(a(i), 0) + 1)\n a.indices.foreach((j) =>\n if (i != j && a(i) == a(j).reverse) {\n f.update(a(i), f.getOrElse(a(i), 0) + 1)\n }\n )\n })\n var pre = \"\"\n var post = \"\"\n while (f.size != 0) {\n val x = f.keySet.head\n val y = x.reverse\n val k = Math.min(f(x), f(y))\n pre = pre + (x * k)\n post = (y * k) + post\n if (b.contains(x)) {\n b.update(x, b(x) - k)\n }\n if (b.contains(y)) {\n b.update(y, b(y) - k)\n }\n f.remove(x)\n f.remove(y)\n }\n b.find { case (k, v) => v > 0 } match {\n case None => pre + post\n case Some((k, v)) => pre + k + post\n }\n }\n}\n"}], "negative_code": [], "src_uid": "554115bec46bb436a0a1ddf8c05a2d08"} {"nl": {"description": "One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.", "input_spec": "The first line contains five non-negative integers NS,\u2009NM,\u2009NL,\u2009NXL,\u2009NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1\u2009\u2264\u2009K\u2009\u2264\u20091000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS\u2009+\u2009NM\u2009+\u2009NL\u2009+\u2009NXL\u2009+\u2009NXXL\u2009\u2265\u2009K.", "output_spec": "For each contestant, print a line containing the size of the T-shirt he/she got.", "sample_inputs": ["1 0 2 0 1\n3\nXL\nXXL\nM"], "sample_outputs": ["XXL\nL\nL"], "notes": null}, "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 val n = in.next().toInt\n val map = List(\"S\", \"M\", \"L\", \"XL\", \"XXL\").zipWithIndex.toMap\n val mapReverse = map.map(i => i._2 -> i._1)\n val res = (1 to n).map(_ => in.next()).map {\n case v if data(map(v)) != 0 =>\n data(map(v)) -= 1\n v\n case v if map(v) != 4 && data(map(v) + 1) != 0 =>\n data(map(v) + 1) -= 1\n mapReverse(map(v) + 1)\n case v if map(v) != 0 && data(map(v) - 1) != 0 =>\n data(map(v) - 1) -= 1\n mapReverse(map(v) - 1)\n case v if map(v) < 3 && data(map(v) + 2) != 0 =>\n data(map(v) + 2) -= 1\n mapReverse(map(v) + 2)\n case v if map(v) > 1 && data(map(v) - 2) != 0 =>\n data(map(v) - 2) -= 1\n mapReverse(map(v) - 2)\n case v if map(v) < 2 && data(map(v) + 3) != 0 =>\n data(map(v) + 3) -= 1\n mapReverse(map(v) + 3)\n case v if map(v) > 2 && data(map(v) - 3) != 0 =>\n data(map(v) - 3) -= 1\n mapReverse(map(v) - 3)\n case v if map(v) < 1 && data(map(v) + 4) != 0 =>\n data(map(v) + 4) -= 1\n mapReverse(map(v) + 4)\n case v if map(v) > 3 && data(map(v) - 4) != 0 =>\n data(map(v) - 4) -= 1\n mapReverse(map(v) - 4)\n }\n println(res.mkString(\"\\n\"))\n}\n"}], "negative_code": [], "src_uid": "3c9d1de13e21ed16a7e5cbd2d67f4ce7"} {"nl": {"description": "You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \\le p_i \\le n$$$, $$$0 \\le c_i \\le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.", "output_spec": "In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.", "sample_inputs": ["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"], "sample_outputs": ["1 2 4", "-1", "5"], "notes": "NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way: "}, "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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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}"}], "negative_code": [], "src_uid": "1b975c5a13a2ad528b668a7c68c089f6"} {"nl": {"description": "The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: \"how many floors should be added to the i-th house to make it luxurious?\" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other \u2014 the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).", "input_spec": "The first line of the input contains a single number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009109), where hi equals the number of floors in the i-th house. ", "output_spec": "Print n integers a1,\u2009a2,\u2009...,\u2009an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.", "sample_inputs": ["5\n1 2 3 1 2", "4\n3 2 1 4"], "sample_outputs": ["3 2 0 2 0", "2 3 4 0"], "notes": null}, "positive_code": [{"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"}, {"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": "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": "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"}, {"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": "/**\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": "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}"}], "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"} {"nl": {"description": "A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).Find a way to cover some cells with sand so that exactly k islands appear on the n\u2009\u00d7\u2009n map, or determine that no such way exists. ", "input_spec": "The single line contains two positive integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 0\u2009\u2264\u2009k\u2009\u2264\u2009n2) \u2014 the size of the map and the number of islands you should form.", "output_spec": "If the answer doesn't exist, print \"NO\" (without the quotes) in a single line. Otherwise, print \"YES\" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands.", "sample_inputs": ["5 2", "5 25"], "sample_outputs": ["YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS", "NO"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$. Consider graph on $$$n$$$ nodes, in which nodes $$$i$$$, $$$j$$$ ($$$i\\neq j$$$) are connected if and only if, $$$a_i$$$ AND $$$a_j\\neq 0$$$, where AND denotes the bitwise AND operation.Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.", "input_spec": "The first line contains one integer $$$n$$$ $$$(1 \\le n \\le 10^5)$$$\u00a0\u2014 number of numbers. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^{18}$$$).", "output_spec": "If the graph doesn't have any cycles, output $$$-1$$$. Else output the length of the shortest cycle.", "sample_inputs": ["4\n3 6 28 9", "5\n5 12 9 16 48", "4\n1 2 4 8"], "sample_outputs": ["4", "3", "-1"], "notes": "NoteIn the first example, the shortest cycle is $$$(9, 3, 6, 28)$$$.In the second example, the shortest cycle is $$$(5, 12, 9)$$$.The graph has no cycles in the third example."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport 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\n val Array(n) = readInts(1)\n val as = readLongs(n).filterNot(_ == 0)\n\n val edges = ArrayBuffer.empty[ArrayBuffer[Int]]\n val bits = Array.fill(64)(0)\n\n var res = -1\n\n var i = 0\n while (i < as.length) {\n val a = as(i)\n edges += ArrayBuffer.empty[Int]\n for (j <- 0 until i) {\n if ((a & as(j)) != 0) {\n edges(i) += j\n edges(j) += i\n }\n }\n for (b <- 0 to 63) {\n val bit = 1L << b\n if ((a & bit) != 0) {\n bits(b) += 1\n if (bits(b) >= 3) {\n i = n\n res = 3\n }\n }\n }\n i += 1\n }\n\n val visited = mutable.BitSet.empty\n\n def dfs(start: Int, u: Int, prev: Int, depth: Int): Unit = {\n if (u == start && prev >= 0) {\n if (res == -1 || depth < res) {\n res = depth\n }\n } else if (res == -1 || depth + 1 < res) {\n visited(u) = true\n for (v <- edges(u)) {\n if ((!visited(v) || v == start) && v != prev) dfs(start, v, u, depth + 1)\n }\n visited(u) = false\n }\n }\n\n if (res == -1) {\n for (u <- edges.indices) dfs(u, u, -1, 0)\n }\n\n println(res)\n}\n"}], "negative_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\n val Array(n) = readInts(1)\n //val as = Array.fill(n)(Long.MaxValue)\n val as = readLongs(n)\n\n val edges = Array.fill(64, 64)(0)\n val edges2 = Array.fill(64, 64)(0)\n\n var res = -1\n\n var k = 0\n while (k < n) {\n val a = as(k)\n var i = 0\n while (i < 63) {\n val bit = 1L << i\n if ((a & bit) != 0) {\n var j = i + 1\n while (j < 64) {\n val bit2 = 1L << j\n if ((a & bit2) != 0) {\n edges(i)(j) += 1\n edges(j)(i) += 1\n edges2(i)(j) = k\n edges2(j)(i) = k\n if (edges(i)(j) >= 3) {\n k = n\n res = 3\n }\n }\n j += 1\n }\n }\n i += 1\n }\n k += 1\n }\n\n val visited = Array.fill(64)(false)\n //val used = Array.fill(n)(false)\n\n def dfs(start: Int, u: Int, prev: Int, depth: Int, prevA: Int): Unit = {\n //println(start, u, prev, depth)\n if (u == start && prev >= 0) {\n if (res == -1 || depth < res) {\n //println((0 to 63).filter(visited), depth)\n res = depth\n }\n } else if (res == -1 || depth + 1 < res) {\n //println(start, u, prev, depth)\n //if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = true\n var v = 0\n while (v < 64) {\n if ((!visited(v) || v == start) && v != prev &&\n (edges(u)(v) > 1 || (edges(u)(v) == 1 && edges2(u)(v) != prevA))) dfs(start, v, u, depth + 1, edges2(u)(v))\n v += 1\n }\n //if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = false\n }\n }\n\n\n if (res == -1) {\n for (u <- 0 until 64) dfs(u, u, -1, 0, -1)\n }\n\n// val range = 0 until\n// for (k <- range) {\n// for (i <- range) if (w(i)(k) != Int.MaxValue) {\n// for (j <- range) if (w(k)(j) != Int.MaxValue) {\n// val ww = w(i)(k) + w(k)(j)\n// if (ww < w(i)(j)) {\n// w(i)(j) = ww\n// next(i)(j) = k\n// // The path from i to j is the path from i to next(i)(j), followed by the path from next(i)(j) to j\n// }\n// }\n// }\n// }\n//\n println(res)\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\n val Array(n) = readInts(1)\n //val as = Array.fill(n)(Long.MaxValue)\n val as = readLongs(n)\n\n val edges = Array.fill(64, 64)(0)\n val edges2 = Array.fill(64, 64)(0)\n val bits = Array.fill(64)(0)\n\n var res = -1\n\n var k = 0\n while (k < n) {\n val a = as(k)\n var i = 0\n while (i < 63) {\n val bit = 1L << i\n if ((a & bit) != 0) {\n bits(i) += 1\n if (bits(i) >= 3) {\n k = n\n res = 3\n }\n var j = i + 1\n while (j < 64) {\n val bit2 = 1L << j\n if ((a & bit2) != 0) {\n edges(i)(j) += 1\n edges(j)(i) += 1\n edges2(i)(j) = k\n edges2(j)(i) = k\n }\n j += 1\n }\n }\n i += 1\n }\n k += 1\n }\n\n val visited = Array.fill(64)(false)\n val used = Array.fill(n)(false)\n\n def dfs(start: Int, u: Int, prev: Int, depth: Int, prevA: Int): Unit = {\n if (u == start && prev >= 0) {\n if (res == -1 || depth < res) {\n res = depth\n }\n } else if (res == -1 || depth < res) {\n visited(u) = true\n var v = 0\n while (v < 64) {\n if ((!visited(v) || v == start) && v != prev &&\n (edges(u)(v) > 1 || (edges(u)(v) == 1 && edges2(u)(v) != prevA))) dfs(start, v, u, depth + 1, edges2(u)(v))\n v += 1\n }\n visited(u) = false\n }\n }\n\n if (res == -1) {\n for (u <- 0 until 64) dfs(u, u, -1, 0, -1)\n }\n\n println(res)\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\n val Array(n) = readInts(1)\n //val as = Array.fill(n)(Long.MaxValue)\n val as = readLongs(n)\n\n val edges = Array.fill(64, 64)(0)\n val edges2 = Array.fill(64, 64)(0)\n\n var res = -1\n\n var k = 0\n while (k < n) {\n val a = as(k)\n var i = 0\n while (i < 63) {\n val bit = 1L << i\n if ((a & bit) != 0) {\n var j = i + 1\n while (j < 64) {\n val bit2 = 1L << j\n if ((a & bit2) != 0) {\n edges(i)(j) += 1\n edges(j)(i) += 1\n edges2(i)(j) = k\n edges2(j)(i) = k\n if (edges(i)(j) >= 3) {\n k = n\n res = 3\n }\n }\n j += 1\n }\n }\n i += 1\n }\n k += 1\n }\n\n val visited = Array.fill(64)(false)\n val used = Array.fill(n)(false)\n\n def dfs(start: Int, u: Int, prev: Int, depth: Int): Unit = {\n //println(start, u, prev, depth)\n if (u == start && prev >= 0) {\n if (res == -1 || depth < res) {\n //println((0 to 63).filter(visited), depth)\n res = depth\n }\n } else if (res == -1 || depth + 1 < res) {\n //println(start, u, prev, depth)\n if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = true\n var v = 0\n while (v < 64) {\n if ((!visited(v) || v == start) && v != prev &&\n (edges(u)(v) > 1 || (edges(u)(v) == 1 && !used(edges2(u)(v))))) dfs(start, v, u, depth + 1)\n v += 1\n }\n if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = false\n }\n }\n\n\n if (res == -1) {\n for (u <- 0 until 64) dfs(u, u, -1, 0)\n }\n\n// val range = 0 until\n// for (k <- range) {\n// for (i <- range) if (w(i)(k) != Int.MaxValue) {\n// for (j <- range) if (w(k)(j) != Int.MaxValue) {\n// val ww = w(i)(k) + w(k)(j)\n// if (ww < w(i)(j)) {\n// w(i)(j) = ww\n// next(i)(j) = k\n// // The path from i to j is the path from i to next(i)(j), followed by the path from next(i)(j) to j\n// }\n// }\n// }\n// }\n//\n println(res)\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\n val Array(n) = readInts(1)\n //val as = Array.fill(n)(Long.MaxValue)\n val as = readLongs(n)\n\n val edges = Array.fill(64, 64)(0)\n val edges2 = Array.fill(64, 64)(0)\n\n var k = 0\n while (k < n) {\n val a = as(k)\n var i = 0\n while (i < 63) {\n val bit = 1L << i\n if ((a & bit) != 0) {\n var j = i + 1\n while (j < 64) {\n val bit2 = 1L << j\n if ((a & bit2) != 0) {\n edges(i)(j) += 1\n edges(j)(i) += 1\n edges2(i)(j) = k\n edges2(j)(i) = k\n if (edges(i)(j) >= 3) k = n\n }\n j += 1\n }\n }\n i += 1\n }\n k += 1\n }\n\n var res = -1\n val visited = Array.fill(64)(false)\n //val used = Array.fill(n)(false)\n\n def dfs(start: Int, u: Int, prev: Int, depth: Int, prevA: Int): Unit = {\n //println(start, u, prev, depth)\n if (u == start && prev >= 0) {\n if (res == -1 || depth < res) {\n //println((0 to 63).filter(visited), depth)\n res = depth\n }\n } else if (res == -1 || depth + 1 < res) {\n //println(start, u, prev, depth)\n //if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = true\n var v = 0\n while (v < 64) {\n if ((!visited(v) || v == start) && v != prev &&\n (edges(u)(v) > 1 || (edges(u)(v) == 1 && edges2(u)(v) != prevA))) dfs(start, v, u, depth + 1, edges2(u)(v))\n v += 1\n }\n //if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = false\n }\n }\n\n\n for (i <- 0 until 64) {\n for (j <- i + 1 until 63) {\n if (edges(i)(j) >= 3) res = 3\n }\n }\n\n if (res == -1) {\n for (u <- 0 until 64) dfs(u, u, -1, 0, -1)\n }\n\n// val range = 0 until\n// for (k <- range) {\n// for (i <- range) if (w(i)(k) != Int.MaxValue) {\n// for (j <- range) if (w(k)(j) != Int.MaxValue) {\n// val ww = w(i)(k) + w(k)(j)\n// if (ww < w(i)(j)) {\n// w(i)(j) = ww\n// next(i)(j) = k\n// // The path from i to j is the path from i to next(i)(j), followed by the path from next(i)(j) to j\n// }\n// }\n// }\n// }\n//\n println(res)\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\n val Array(n) = readInts(1)\n //val as = Array.fill(n)(Long.MaxValue)\n val as = readLongs(n)\n\n val edges = Array.fill(64, 64)(0)\n val edges2 = Array.fill(64, 64)(0)\n\n var res = -1\n\n var k = 0\n while (k < n) {\n val a = as(k)\n var i = 0\n while (i < 63) {\n val bit = 1L << i\n if ((a & bit) != 0) {\n var j = i + 1\n while (j < 64) {\n val bit2 = 1L << j\n if ((a & bit2) != 0) {\n edges(i)(j) += 1\n edges(j)(i) += 1\n edges2(i)(j) = k\n edges2(j)(i) = k\n if (edges(i)(j) >= 3) {\n k = n\n res = 3\n }\n }\n j += 1\n }\n }\n i += 1\n }\n k += 1\n }\n\n val visited = Array.fill(64)(false)\n val used = Array.fill(n)(false)\n\n def dfs(start: Int, u: Int, prev: Int, depth: Int, prevA: Int): Unit = {\n //println(start, u, prev, depth)\n if (u == start && prev >= 0) {\n if (res == -1 || depth < res) {\n //println((0 to 63).filter(visited), depth)\n res = depth\n }\n } else if (res == -1 || depth < res) {\n //println(start, u, prev, depth)\n //if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = true\n var v = 0\n while (v < 64) {\n if ((!visited(v) || v == start) && v != prev &&\n (edges(u)(v) > 1 || (edges(u)(v) == 1 && edges2(u)(v) != prevA))) dfs(start, v, u, depth + 1, edges2(u)(v))\n v += 1\n }\n //if (prev >= 0) used(edges2(u)(prev)) = true\n visited(u) = false\n }\n }\n \n if (res == -1) {\n for (u <- 0 until 64) dfs(u, u, -1, 0, -1)\n }\n\n// val range = 0 until\n// for (k <- range) {\n// for (i <- range) if (w(i)(k) != Int.MaxValue) {\n// for (j <- range) if (w(k)(j) != Int.MaxValue) {\n// val ww = w(i)(k) + w(k)(j)\n// if (ww < w(i)(j)) {\n// w(i)(j) = ww\n// next(i)(j) = k\n// // The path from i to j is the path from i to next(i)(j), followed by the path from next(i)(j) to j\n// }\n// }\n// }\n// }\n//\n println(res)\n}\n"}], "src_uid": "480db1d8e2fadc75fd07693c22254fc1"} {"nl": {"description": "Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm: take the password $$$p$$$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $$$p'$$$ ($$$p'$$$ can still be equal to $$$p$$$); generate two random strings, consisting of lowercase Latin letters, $$$s_1$$$ and $$$s_2$$$ (any of these strings can be empty); the resulting hash $$$h = s_1 + p' + s_2$$$, where addition is string concatenation. For example, let the password $$$p =$$$ \"abacaba\". Then $$$p'$$$ can be equal to \"aabcaab\". Random strings $$$s1 =$$$ \"zyx\" and $$$s2 =$$$ \"kjh\". Then $$$h =$$$ \"zyxaabcaabkjh\".Note that no letters could be deleted or added to $$$p$$$ to obtain $$$p'$$$, only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password $$$p$$$ and the hash $$$h$$$, check that $$$h$$$ can be the hash for the password $$$p$$$.Your program should answer $$$t$$$ independent test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The first line of each test case contains a non-empty string $$$p$$$, consisting of lowercase Latin letters. The length of $$$p$$$ does not exceed $$$100$$$. The second line of each test case contains a non-empty string $$$h$$$, consisting of lowercase Latin letters. The length of $$$h$$$ does not exceed $$$100$$$.", "output_spec": "For each test case print the answer to it \u2014 \"YES\" if the given hash $$$h$$$ could be obtained from the given password $$$p$$$ or \"NO\" otherwise.", "sample_inputs": ["5\nabacaba\nzyxaabcaabkjh\nonetwothree\nthreetwoone\none\nzzonneyy\none\nnone\ntwenty\nten"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO"], "notes": "NoteThe first test case is explained in the statement.In the second test case both $$$s_1$$$ and $$$s_2$$$ are empty and $$$p'=$$$ \"threetwoone\" is $$$p$$$ shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case $$$s_1=$$$ \"n\", $$$s_2$$$ is empty and $$$p'=$$$ \"one\" is $$$p$$$ shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "negative_code": [], "src_uid": "48151011c3d380ab303ae38d0804176a"} {"nl": {"description": "Valera had two bags of potatoes, the first of these bags contains x (x\u2009\u2265\u20091) potatoes, and the second \u2014 y (y\u2009\u2265\u20091) potatoes. Valera \u2014 very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x\u2009+\u2009y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.", "input_spec": "The first line of input contains three integers y, k, n (1\u2009\u2264\u2009y,\u2009k,\u2009n\u2009\u2264\u2009109; \u2009\u2264\u2009105).", "output_spec": "Print the list of whitespace-separated integers \u2014 all possible values of x in ascending order. You should print each possible value of x exactly once. If there are no such values of x print a single integer -1.", "sample_inputs": ["10 1 10", "10 6 40"], "sample_outputs": ["-1", "2 8 14 20 26"], "notes": null}, "positive_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 = (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 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": "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}"}, {"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": "\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 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}"}, {"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}"}], "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"} {"nl": {"description": "Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot!For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $$$2$$$ cosplayers, the number of males does not exceed the number of females (obviously).Currently, the line has $$$n$$$ cosplayers which can be described by a binary string $$$s$$$. The $$$i$$$-th cosplayer is male if $$$s_i = 0$$$ and female if $$$s_i = 1$$$. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.Marin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$) \u2014 the number of test cases. The first line of each test case contains a positive integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$) \u2014 the number of cosplayers in the initial line. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ \u2014 describing the cosplayers already in line. Each character of the string is either 0 describing a male, or 1 describing a female. Note that there is no limit on the sum of $$$n$$$.", "output_spec": "For each test case, print the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful.", "sample_inputs": ["9\n\n3\n\n000\n\n3\n\n001\n\n3\n\n010\n\n3\n\n011\n\n3\n\n100\n\n3\n\n101\n\n3\n\n110\n\n3\n\n111\n\n19\n\n1010110000100000101"], "sample_outputs": ["4\n2\n1\n0\n2\n0\n0\n0\n17"], "notes": "NoteIn the first test case, for each pair of adjacent cosplayers, you can invite two female cosplayers to stand in between them. Then, $$$000 \\rightarrow 0110110$$$.In the third test case, you can invite one female cosplayer to stand next to the second cosplayer. Then, $$$010 \\rightarrow 0110$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def solve() = {\r\n\r\n def recur(s: String, count: Int = 0): Int = {\r\n if (s.isEmpty) 0\r\n else if (s.head == '1') recur(s.tail, count + 1)\r\n else if (count < 2) 2 - count + recur(s.tail, 0)\r\n else recur(s.tail, 0)\r\n }\r\n val cos = readLine().toInt\r\n val line = readLine()\r\n // male, female\r\n recur(line.dropWhile(_ == '1'), '1')\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 ) println(solve())\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "9966bfdc9677a9dd558684a00977cd58"} {"nl": {"description": "While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.", "input_spec": "The first line of the input consists of two integers, the number of robots n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) and the number of rap battles m (). The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots. It is guaranteed that at least one ordering of the robots satisfies all m relations.", "output_spec": "Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.", "sample_inputs": ["4 5\n2 1\n1 3\n2 3\n4 2\n4 3", "3 2\n1 2\n3 2"], "sample_outputs": ["4", "-1"], "notes": "NoteIn the first sample, the robots from strongest to weakest must be (4,\u20092,\u20091,\u20093), which Bessie can deduce after knowing the results of the first four rap battles.In the second sample, both (1,\u20093,\u20092) and (3,\u20091,\u20092) are possible orderings of the robots from strongest to weakest after both rap battles."}, "positive_code": [{"source_code": "import java.util\n\nimport scala.collection._\n\nobject D extends App {\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 val preceedingBuilders, onStepBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (step <- 1 to m) {\n val Array(u, v) = readInts(2).map(_ - 1)\n preceedingBuilders(u) += v\n onStepBuilders(u) += step\n }\n\n val preceeding = preceedingBuilders.map(_.result)\n val onStep = onStepBuilders.map(_.result)\n\n def can(toStep: Int): Boolean = {\n\n val sortedBuilder = new mutable.ArrayBuilder.ofInt\n val color = Array.fill(n)(0)\n\n def dfs1(u: Int): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n if (onStep(u)(i) <= toStep) {\n val v = preceeding(u)(i)\n if (color(v) == 0) dfs1(v)\n }\n i += 1\n }\n color(u) = 2\n sortedBuilder += u\n }\n\n for (i <- 0 until n) {\n if (color(i) == 0) dfs1(i)\n }\n\n val sorted = sortedBuilder.result\n val topologicalOrder = Array.ofDim[Int](n)\n for (i <- sorted.indices) topologicalOrder(sorted(i)) = i\n\n val maxDepth = Array.fill(n){ -1 }\n\n def dfs2(u: Int): Int = {\n if (maxDepth(u) < 0){\n var depth = 0\n var i = 0\n while (i < preceeding(u).length) {\n val v = preceeding(u)(i)\n if (onStep(u)(i) <= toStep && topologicalOrder(v) < topologicalOrder(u)) {\n depth = depth max dfs2(v)\n }\n i += 1\n }\n maxDepth(u) = depth + 1\n }\n maxDepth(u)\n }\n //println(sorted.mkString(\" \"), dfs2(sorted.last))\n dfs2(sorted.last) == n\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\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 if (!can(m)) println(-1)\n else println(binSearch(0, m))\n}\n"}], "negative_code": [{"source_code": "import java.util\n\nimport scala.collection._\n\nobject D extends App {\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 val preceedingBuilders, onStepBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (step <- 1 to m) {\n val Array(u, v) = readInts(2).map(_ - 1)\n preceedingBuilders(u) += v\n onStepBuilders(u) += step\n }\n\n val preceeding = preceedingBuilders.map(_.result)\n val onStep = onStepBuilders.map(_.result)\n\n def can(toStep: Int): Boolean = {\n\n val sb1, sb2, sb3, sb4 = new mutable.ArrayBuilder.ofInt\n val c1, c2, c3, c4 = Array.fill(n)(0)\n\n def dfs1(u: Int, sb: mutable.ArrayBuilder.ofInt, color: Array[Int]): Unit = {\n color(u) = 1\n var i = 0\n while (i < preceeding(u).length) {\n if (onStep(u)(i) <= toStep) {\n val v = preceeding(u)(i)\n if (color(v) == 0) dfs1(v, sb, color)\n }\n i += 1\n }\n color(u) = 2\n sb += u\n }\n\n def dfs2(u: Int, sb: mutable.ArrayBuilder.ofInt, color: Array[Int]): Unit = {\n color(u) = 1\n var i = preceeding(u).length - 1\n while (i >= 0) {\n if (onStep(u)(i) <= toStep) {\n val v = preceeding(u)(i)\n if (color(v) == 0) dfs2(v, sb, color)\n }\n i -= 1\n }\n color(u) = 2\n sb += u\n }\n\n for (i <- 0 until n) {\n if (c1(i) == 0) dfs1(i, sb1, c1)\n if (c2(i) == 0) dfs2(i, sb2, c2)\n }\n\n for (i <- n - 1 to 0 by -1) {\n if (c3(i) == 0) dfs1(i, sb3, c3)\n if (c4(i) == 0) dfs2(i, sb4, c4)\n }\n\n val ts1 = sb1.result\n val ts2 = sb2.result\n val ts3 = sb3.result\n val ts4 = sb4.result\n ////println(toStep, ts1.mkString(\" \"), ts2.mkString(\" \"))\n util.Arrays.equals(ts1, ts2) && util.Arrays.equals(ts1, ts3) && util.Arrays.equals(ts1, ts4)\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\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 if (!can(m)) println(-1)\n else println(binSearch(0, m))\n}\n"}], "src_uid": "5337df1fb8a9b96ab7b66aa197a5b910"} {"nl": {"description": "There is a graph of $$$n$$$ rows and $$$10^6 + 2$$$ columns, where rows are numbered from $$$1$$$ to $$$n$$$ and columns from $$$0$$$ to $$$10^6 + 1$$$: Let's denote the node in the row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$.Initially for each $$$i$$$ the $$$i$$$-th row has exactly one obstacle \u2014 at node $$$(i, a_i)$$$. You want to move some obstacles so that you can reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $$$u$$$ or $$$v$$$ coins, as below: If there is an obstacle in the node $$$(i, j)$$$, you can use $$$u$$$ coins to move it to $$$(i-1, j)$$$ or $$$(i+1, j)$$$, if such node exists and if there is no obstacle in that node currently. If there is an obstacle in the node $$$(i, j)$$$, you can use $$$v$$$ coins to move it to $$$(i, j-1)$$$ or $$$(i, j+1)$$$, if such node exists and if there is no obstacle in that node currently. Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from $$$(1,1)$$$ to $$$(0,1)$$$. Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$u$$$ and $$$v$$$ ($$$2 \\le n \\le 100$$$, $$$1 \\le u, v \\le 10^9$$$)\u00a0\u2014 the number of rows in the graph and the numbers of coins needed to move vertically and horizontally respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$)\u00a0\u2014 where $$$a_i$$$ represents that the obstacle in the $$$i$$$-th row is in node $$$(i, a_i)$$$. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^4$$$.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles. It can be shown that under the constraints of the problem there is always a way to make such a trip possible.", "sample_inputs": ["3\n2 3 4\n2 2\n2 3 4\n3 2\n2 4 3\n3 2"], "sample_outputs": ["7\n3\n3"], "notes": "NoteIn the first sample, two obstacles are at $$$(1, 2)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(2, 2)$$$ to $$$(2, 3)$$$, then to $$$(1, 3)$$$. The total cost is $$$u+v = 7$$$ coins. In the second sample, two obstacles are at $$$(1, 3)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(1, 3)$$$ to $$$(2, 3)$$$. The cost is $$$u = 3$$$ coins. "}, "positive_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n, u, v = nextInt\n val as = nextInts(n)\n val minA = as.min\n val maxA = as.max\n var res = 0\n if (minA == maxA) {\n res = Math.min(2 * v, u + v)\n } else {\n var gap = false\n for (i <- 1 until as.length) {\n if (Math.abs(as(i) - as(i - 1)) > 1) gap = true\n }\n res = if (gap) 0 else Math.min(u, v)\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": [], "src_uid": "7f502f2fd150a2ded948826960d123cd"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \\le a, b \\le 1000$$$).", "output_spec": "Print $$$t$$$ integers \u2014 the required numbers $$$a+b$$$.", "sample_inputs": ["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"], "sample_outputs": ["6\n329\n0\n1110"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject A {\n\n def solution(a: Int, b: Int): Int = {\n a + b\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val Seq(a, b) = readLine.split(\" \").toSeq.map(_.toInt)\n println(solution(a, b))\n }\n }\n}"}], "negative_code": [], "src_uid": "27ddccc777ef9040284ab6314cbd70e7"} {"nl": {"description": "Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).", "input_spec": "The first input line contains four integer numbers n, t1, t2, k (1\u2009\u2264\u2009n,\u2009t1,\u2009t2\u2009\u2264\u20091000;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009100) \u2014 the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly. Each of the following n lines contains two integers. The i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) line contains space-separated integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the speeds which the participant number i chose.", "output_spec": "Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.", "sample_inputs": ["2 3 3 50\n2 4\n4 2", "4 1 1 1\n544 397\n280 101\n280 101\n693 970"], "sample_outputs": ["1 15.00\n2 15.00", "4 1656.07\n1 937.03\n2 379.99\n3 379.99"], "notes": "Note First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2\u00b73\u00b70.5\u2009+\u20094\u00b73\u2009>\u20094\u00b73\u00b70.5\u2009+\u20092\u00b73. "}, "positive_code": [{"source_code": "object B\n{\n def main(args: Array[String])\n {\n val input = readLine.split(\" \").map{_.toInt}\n val n = input(0)\n val t1 = input(1)*(100-input(3))\n val t2 = input(2)*100\n \n var dwarves = Array.tabulate(n){i: Int => (0,0)}\n \n for(i <- 0 until n)\n {\n val speed = readLine.split(\" \").map{_.toInt}\n dwarves(i) = (i+1, (speed(0)*t1+speed(1)*t2) max (speed(0)*t2+speed(1)*t1))\n }\n val rankedDwarves = dwarves.sortWith((d1,d2) => d1._2>d2._2)\n for((i,h) <- rankedDwarves)\n {\n println(\"%d %d.%02d\".format(i, h/100, h%100))\n }\n }\n}\n"}], "negative_code": [], "src_uid": "a89f9310996eb23254d07e52544e30ae"} {"nl": {"description": "Mishka has got n empty boxes. For every i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met: i-th box is not put into another box; j-th box doesn't contain any other boxes; box i is smaller than box j (ai\u2009<\u2009aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the side length of i-th box.", "output_spec": "Print the minimum possible number of visible boxes.", "sample_inputs": ["3\n1 2 3", "4\n4 2 4 3"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A|\u2009<\u2009|B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of strings. The second line contains n integers ci (0\u2009\u2264\u2009ci\u2009\u2264\u2009109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100\u2009000.", "output_spec": "If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print \u2009-\u20091. Otherwise, print the minimum total amount of energy Vasiliy has to spent.", "sample_inputs": ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"], "sample_outputs": ["1", "1", "-1", "-1"], "notes": "NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is \u2009-\u20091.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string \"aa\" should go before string \"aaa\", thus the answer is \u2009-\u20091."}, "positive_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().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"}, {"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": "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"}], "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 \u043c\u0441 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"} {"nl": {"description": "Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.", "input_spec": "The first line contains a single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of days. The second line contains n space-separated integers m1,\u2009m2,\u2009...,\u2009mn (0\u2009\u2264\u2009mi\u2009<\u2009i)\u00a0\u2014 the number of marks strictly above the water on each day.", "output_spec": "Output one single integer\u00a0\u2014 the minimum possible sum of the number of marks strictly below the water level among all days.", "sample_inputs": ["6\n0 1 0 3 0 2", "5\n0 1 2 1 2", "5\n0 1 1 2 2"], "sample_outputs": ["6", "1", "0"], "notes": "NoteIn the first example, the following figure shows an optimal case. Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0\u2009+\u20090\u2009+\u20092\u2009+\u20090\u2009+\u20093\u2009+\u20091\u2009=\u20096.In the second example, the following figure shows an optimal case. "}, "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) = readInts(1)\n val ms = readInts(n)\n\n var res = 0L\n\n val totals = Array.ofDim[Int](n)\n\n totals(0) = ms(0) + 1\n for (i <- 1 until n) {\n totals(i) = Math.max(totals(i - 1), ms(i) + 1)\n }\n\n var total = totals.last\n\n for (i <- ms.indices.reverse) {\n total = Math.max(totals(i), total - 1)\n res += (total - ms(i) - 1)\n //println(i + 1, total - ms(i) - 1, res, total)\n //if (total > i) total = i\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "d4909bd6c23312ac3968d81cb6340035"} {"nl": {"description": "Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1,\u2009...,\u2009an and p1,\u2009...,\u2009pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days. ", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1\u2009\u2264\u2009ai,\u2009pi\u2009\u2264\u2009100), the amount of meat Duff needs and the cost of meat in that day.", "output_spec": "Print the minimum money needed to keep Duff happy for n days, in one line.", "sample_inputs": ["3\n1 3\n2 2\n3 1", "3\n1 3\n2 1\n3 2"], "sample_outputs": ["10", "8"], "notes": "NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day."}, "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": "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"}, {"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"} {"nl": {"description": "VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.", "input_spec": "The first line of input consists of single integer $$$n$$$\u00a0\u2014 the number of news categories ($$$1 \\le n \\le 200\\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$\u00a0\u2014 the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \\le a_i \\le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \\le t_i \\le 10^5)$$$.", "output_spec": "Print one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.", "sample_inputs": ["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"], "sample_outputs": ["6", "0"], "notes": "NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications."}, "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 n = in.nextInt()\n val aC = (1 to n).map{ _ => in.nextInt()}\n val aT = (1 to n).map{ _ => in.nextLong()}\n val aCT = (aC.zip(aT)).sorted.toArray\n val limits = Array.fill(n+1)(0)\n val v = Array.fill(n+1)(0)\n var M = 0\n aCT.indices.foreach{ i =>\n val (c,_) = aCT(i)\n if(i == 0){\n limits(M) = i\n v(M) = c\n M += 1\n }else{\n if(v(M-1) == c){\n limits(M-1) = i\n }else{\n limits(M) = i\n v(M) = c\n M += 1\n }\n }\n }\n val m2i = (0 to M).map{ i =>\n v(i) -> i\n }.toMap\n\n val arST: Array[Long] = aCT.map{case (_,tt) => tt}\n val st = new SegmentTree(n+2)\n st.build(arST)\n var ans = 0L\n\n var pos = 0\n\n while(pos < n){\n //doing here is bc all prev was good\n var indx = m2i(aCT(pos)._1)\n val startingValue = v(indx)\n val start = pos\n var end = limits(indx)\n\n var currentValue = startingValue\n var loopsNeeded = end-start\n while(loopsNeeded>0){\n\n val (i,sum) = st.query(start,end+1)\n ans += sum-arST(i)\n\n st.update(i,0L)\n currentValue += 1\n loopsNeeded -= 1\n if(indx+1 < M && currentValue == v(indx+1)){\n //increase range\n indx += 1\n end = limits(indx)\n loopsNeeded += limits(indx)-limits(indx-1)\n }\n }\n pos = end+1\n\n\n }\n\n out.println(ans)\n\n\n\n }\n\n trait Node[T]{\n def + (other: Node[T]): Node[T]\n def value: T\n }\n\n case class MaxSum(value: (Int,Long,Long)) extends Node[(Int,Long,Long)]{\n override def +(other: Node[(Int,Long,Long)]): Node[(Int,Long,Long)] = {\n val (i,a,b) = value\n val (j,x,y) = other.value\n MaxSum((if(a>x) i else j,Math.max(a,x),b+y))\n }\n }\n class SegmentTree(maxN: Int){\n\n val sumRange: Array[Long] = Array.fill(maxN*4+2)(0L)\n val indxMaxValue: Array[Int] = Array.fill(maxN*4+2)(0)\n var actualValues: Array[Long] = Array.empty[Long]\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n actualValues = nodes\n build(nodes,0,N,0)\n }\n private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={\n if(left+1 == right){\n sumRange(n) = nodes(left)\n indxMaxValue(n) = left\n\n }else{\n val m = (left+right)/2\n build(nodes,left,m,n*2+1)\n build(nodes,m,right,n*2+2)\n sumRange(n) = sumRange(n*2+1)+sumRange(n*2+2)\n indxMaxValue(n) = {\n if(actualValues(indxMaxValue(n*2+1)) > actualValues(indxMaxValue(n*2+2))){\n indxMaxValue(n*2+1)\n }else{\n indxMaxValue(n*2+2)\n }\n }\n }\n }\n\n def query(left: Int, right: Int): (Int,Long) = query(0,0,N,left,right)\n private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): (Int,Long) = {\n\n if(n0 == left && nn == right) {\n (indxMaxValue(n),sumRange(n))\n } else{\n val m = (n0+nn)/2\n if(left >= m){\n query(n*2+2,m,nn,left,right)\n }else{\n if( right <= m){\n query(n*2+1,n0,m,left,right)\n }else{\n val (i,sumLeft) = query(n*2+1,n0,m,left,m)\n val (j,sumRight) = query(n*2+2,m,nn,m,right)\n val k = {\n if(actualValues(i) > actualValues(j)){\n i\n }else{\n j\n }\n }\n (k,sumLeft+sumRight)\n }\n }\n }\n }\n\n def update(i: Int, value: Long): Unit = update(0,i,0,N,value)\n\n private def update(n: Int, pos: Int, left: Int, right: Int, v: Long): Unit = {\n if(pos >= left && pos < right){\n if (left + 1 == right) {\n sumRange(n) = v\n actualValues(left) = v\n } else {\n val m = (left + right) / 2\n update(n*2+1,pos,left,m,v)\n update(n*2+2,pos,m,right,v)\n sumRange(n) = sumRange(n * 2 + 1) + sumRange(n * 2 + 2)\n indxMaxValue(n) = {\n if(actualValues(indxMaxValue(n*2+1)) > actualValues(indxMaxValue(n*2+2))){\n indxMaxValue(n*2+1)\n }else{\n indxMaxValue(n*2+2)\n }\n }\n }\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": "6bceaf308c38d234ba931c13e4f70929"} {"nl": {"description": "There is a game called \"I Wanna Be the Guy\", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009\u2009n\u2009\u2264\u2009100). The next line contains an integer p (0\u2009\u2264\u2009p\u2009\u2264\u2009n) at first, then follows p distinct integers a1,\u2009a2,\u2009...,\u2009ap (1\u2009\u2264\u2009ai\u2009\u2264\u2009n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.", "output_spec": "If they can pass all the levels, print \"I become the guy.\". If it's impossible, print \"Oh, my keyboard!\" (without the quotes).", "sample_inputs": ["4\n3 1 2 3\n2 2 4", "4\n3 1 2 3\n2 2 3"], "sample_outputs": ["I become the guy.", "Oh, my keyboard!"], "notes": "NoteIn the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.In the second sample, no one can pass level 4."}, "positive_code": [{"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}"}, {"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": "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"}, {"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}"}], "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"} {"nl": {"description": "PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k\u2009-\u20091 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009104)\u00a0\u2014 the number of Balls living in the forest. The second line contains a sequence p1,\u2009p2,\u2009...,\u2009pn of length n, where (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009104)\u00a0\u2014 the number of Balls and the integer m (0\u2009\u2264\u2009m\u2009<\u2009n)\u00a0\u2014 the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5", "output_spec": "You should output the number of trees in the forest where PolandBall lives.", "sample_inputs": ["5\n2 1 5 3 3", "1\n1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree."}, "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"}, {"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"}], "negative_code": [], "src_uid": "6d940cb4b54f63a7aaa82f21e4c5b994"} {"nl": {"description": "It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of tasks. The second line contains n integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u20092000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.", "output_spec": "In the first line print \"YES\" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line \"NO\" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form. If there are multiple possible answers, you can print any of them.", "sample_inputs": ["4\n1 3 3 1", "5\n2 4 1 4 8"], "sample_outputs": ["YES\n1 4 2 3 \n4 1 2 3 \n4 1 3 2", "NO"], "notes": "NoteIn the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.In the second sample there are only two sequences of tasks that meet the conditions \u2014 [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks."}, "positive_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+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"}, {"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": "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"}], "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"} {"nl": {"description": "Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $$$n$$$ problems of distinct difficulty, the difficulties are numbered from $$$1$$$ to $$$n$$$.To hold a round Arkady needs $$$n$$$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $$$1$$$ to $$$n$$$ and puts it into the problems pool.At each moment when Arkady can choose a set of $$$n$$$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^5$$$)\u00a0\u2014 the number of difficulty levels and the number of problems Arkady created. The second line contains $$$m$$$ integers $$$a_1, a_2, \\ldots, a_m$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the problems' difficulties in the order Arkady created them.", "output_spec": "Print a line containing $$$m$$$ digits. The $$$i$$$-th digit should be $$$1$$$ if Arkady held the round after creation of the $$$i$$$-th problem, and $$$0$$$ otherwise.", "sample_inputs": ["3 11\n2 3 1 2 2 2 3 2 2 3 1", "4 8\n4 1 3 3 2 3 3 3"], "sample_outputs": ["00100000001", "00001000"], "notes": "NoteIn the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem."}, "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, 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) // \u30ab\u30a6\u30f3\u30c8\u306e\u30ab\u30a6\u30f3\u30c8\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}"}, {"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"} {"nl": {"description": "Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.Filya is given an array of non-negative integers a1,\u2009a2,\u2009...,\u2009an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.Now he wonders if it's possible to pick such integer x and change some elements of the array using this x in order to make all elements equal.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of integers in the Filya's array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 elements of the array.", "output_spec": "If it's impossible to make all elements of the array equal using the process given in the problem statement, then print \"NO\" (without quotes) in the only line of the output. Otherwise print \"YES\" (without quotes).", "sample_inputs": ["5\n1 3 3 2 1", "5\n1 2 3 4 5"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample Filya should select x\u2009=\u20091, then add it to the first and the last elements of the array and subtract from the second and the third elements."}, "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"}, {"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"}], "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"} {"nl": {"description": "You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operation on it as many times as you want: Pick two integers $$$i$$$ and $$$j$$$ $$$(1 \\le i,j \\le n)$$$ such that $$$a_i+a_j$$$ is odd, then swap $$$a_i$$$ and $$$a_j$$$. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \\le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{n}$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "The only line contains $$$n$$$ space-separated integers, the lexicographically smallest array you can obtain.", "sample_inputs": ["3\n4 1 7", "2\n1 1"], "sample_outputs": ["1 4 7", "1 1"], "notes": "NoteIn the first example, we can swap $$$1$$$ and $$$4$$$ since $$$1+4=5$$$, which is odd."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form \"command ip;\" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. Each ip is of form \"a.b.c.d\" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is \"command ip;\" Dustin has to replace it with \"command ip; #name\" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.", "input_spec": "The first line of input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000). The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1\u2009\u2264\u2009|name|\u2009\u2264\u200910, name only consists of English lowercase letters). It is guaranteed that all ip are distinct. The next m lines contain the commands in the configuration file. Each line is of form \"command ip;\" (1\u2009\u2264\u2009|command|\u2009\u2264\u200910, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.", "output_spec": "Print m lines, the commands in the configuration file after Dustin did his task.", "sample_inputs": ["2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;", "3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.33.27;\nunblock 8.8.8.8;\ncheck 138.197.64.57;"], "sample_outputs": ["block 192.168.0.1; #replica\nproxy 192.168.0.2; #main", "redirect 138.197.64.57; #server\nblock 8.8.8.8; #google\ncf 212.193.33.27; #codeforces\nunblock 8.8.8.8; #google\ncheck 138.197.64.57; #server"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \\le n \\le 50$$$)\u00a0\u2014 length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$).", "output_spec": "For each test case print: YES if the such a partition exists, NO otherwise. The letters in the words YES and NO can be displayed in any case.", "sample_inputs": ["7\n4\n11 14 16 12\n2\n1 8\n4\n1 1 1 1\n4\n1 2 5 6\n2\n12 13\n6\n1 6 3 10 5 8\n6\n1 12 3 10 5 8"], "sample_outputs": ["YES\nNO\nYES\nYES\nYES\nYES\nNO"], "notes": "NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given an angle $$$\\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\\angle{abc} = \\text{ang}$$$ or report that there is no such $$$n$$$-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 180$$$) \u2014 the number of queries. Each of the next $$$T$$$ lines contains one integer $$$\\text{ang}$$$ ($$$1 \\le \\text{ang} < 180$$$) \u2014 the angle measured in degrees. ", "output_spec": "For each query print single integer $$$n$$$ ($$$3 \\le n \\le 998244353$$$) \u2014 minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.", "sample_inputs": ["4\n54\n50\n2\n178"], "sample_outputs": ["10\n18\n90\n180"], "notes": "NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\\angle{v_2 v_1 v_6} = 50^{\\circ}$$$.The example angle for the third query is $$$\\angle{v_{11} v_{10} v_{12}} = 2^{\\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$)."}, "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 ans = Array.fill[Int](181)(-1)\n 3 to 360 foreach { n =>\n REP(n - 2, 1) { cnt =>\n if (cnt * 180 % n == 0) {\n val angle = cnt * 180 / n\n if (ans(angle) == -1) ans(angle) = n\n }\n }\n }\n\n// debug(ans)\n\n REP(ni()) { _ =>\n val angle = ni()\n out.println(ans(angle))\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": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n 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 ans = Array.fill[Int](181)(-1)\n 3 to 180 foreach { n =>\n if (180 % n == 0) {\n val unit = 180 / n\n REP(n - 2, 1) { cnt =>\n val angle = cnt * unit\n if (ans(angle) == -1) ans(angle) = n\n }\n }\n }\n\n ans(179) = 360\n// debug(ans)\n\n REP(ni()) { _ =>\n val angle = ni()\n out.println(ans(angle))\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": "d11b56fe172110d5dfafddf880e48f18"} {"nl": {"description": "After returning from the army Makes received a gift \u2014 an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i,\u2009\u00a0j,\u2009\u00a0k) (i\u2009<\u2009j\u2009<\u2009k), such that ai\u00b7aj\u00b7ak is minimum possible, are there in the array? Help him with it!", "input_spec": "The first line of input contains a positive integer number n\u00a0(3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of elements in array a. The second line contains n positive integer numbers ai\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of a given array.", "output_spec": "Print one number \u2014 the quantity of triples (i,\u2009\u00a0j,\u2009\u00a0k) such that i,\u2009\u00a0j and k are pairwise distinct and ai\u00b7aj\u00b7ak is minimum possible.", "sample_inputs": ["4\n1 1 1 1", "5\n1 3 2 3 4", "6\n1 3 3 1 3 2"], "sample_outputs": ["4", "2", "1"], "notes": "NoteIn the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.In the second example a triple of numbers (1,\u20092,\u20093) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.In the third example a triple of numbers (1,\u20091,\u20092) is chosen, and there's only one way to choose indices."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given an array a1,\u2009a2,\u2009...,\u2009an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009\u2009105) \u2014 the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an (\u2009-\u2009109\u2009\u2009\u2264\u2009\u2009ai\u2009\u2264\u2009\u2009109).", "output_spec": "Print single integer \u2014 the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.", "sample_inputs": ["5 2\n1 2 3 4 5", "5 1\n-4 -5 -3 -2 -1"], "sample_outputs": ["5", "-5"], "notes": "NoteA subsegment [l,\u2009\u2009r] (l\u2009\u2264\u2009r) of array a is the sequence al,\u2009\u2009al\u2009+\u20091,\u2009\u2009...,\u2009\u2009ar.Splitting of array a of n elements into k subsegments [l1,\u2009r1], [l2,\u2009r2], ..., [lk,\u2009rk] (l1\u2009=\u20091, rk\u2009=\u2009n, li\u2009=\u2009ri\u2009-\u20091\u2009+\u20091 for all i\u2009>\u20091) is k sequences (al1,\u2009...,\u2009ar1),\u2009...,\u2009(alk,\u2009...,\u2009ark).In the first example you should split the array into subsegments [1,\u20094] and [5,\u20095] that results in sequences (1,\u20092,\u20093,\u20094) and (5). The minimums are min(1,\u20092,\u20093,\u20094)\u2009=\u20091 and min(5)\u2009=\u20095. The resulting maximum is max(1,\u20095)\u2009=\u20095. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1,\u20095], that results in one sequence (\u2009-\u20094,\u2009\u2009-\u20095,\u2009\u2009-\u20093,\u2009\u2009-\u20092,\u2009\u2009-\u20091). The only minimum is min(\u2009-\u20094,\u2009\u2009-\u20095,\u2009\u2009-\u20093,\u2009\u2009-\u20092,\u2009\u2009-\u20091)\u2009=\u2009\u2009-\u20095. The resulting maximum is \u2009-\u20095."}, "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, k) = readInts(2)\n val as = readInts(n)\n\n val res = if (k == 1) as.min\n else if (k > 2) as.max\n else as.last max as.head\n\n println(res)\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "ec1a29826209a0820e8183cccb2d2f01"} {"nl": {"description": "You are given three strings $$$s$$$, $$$t$$$ and $$$p$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from $$$p$$$, erase it from $$$p$$$ and insert it into string $$$s$$$ (you may insert this character anywhere you want: in the beginning of $$$s$$$, in the end or between any two consecutive characters). For example, if $$$p$$$ is aba, and $$$s$$$ is de, then the following outcomes are possible (the character we erase from $$$p$$$ and insert into $$$s$$$ is highlighted): aba $$$\\rightarrow$$$ ba, de $$$\\rightarrow$$$ ade; aba $$$\\rightarrow$$$ ba, de $$$\\rightarrow$$$ dae; aba $$$\\rightarrow$$$ ba, de $$$\\rightarrow$$$ dea; aba $$$\\rightarrow$$$ aa, de $$$\\rightarrow$$$ bde; aba $$$\\rightarrow$$$ aa, de $$$\\rightarrow$$$ dbe; aba $$$\\rightarrow$$$ aa, de $$$\\rightarrow$$$ deb; aba $$$\\rightarrow$$$ ab, de $$$\\rightarrow$$$ ade; aba $$$\\rightarrow$$$ ab, de $$$\\rightarrow$$$ dae; aba $$$\\rightarrow$$$ ab, de $$$\\rightarrow$$$ dea; Your goal is to perform several (maybe zero) operations so that $$$s$$$ becomes equal to $$$t$$$. Please determine whether it is possible.Note that you have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2014 the number of queries. Each query is represented by three consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \\le |s| \\le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \\le |t| \\le 100$$$) consisting of lowercase Latin letters. The third line of each query contains the string $$$p$$$ ($$$1 \\le |p| \\le 100$$$) consisting of lowercase Latin letters.", "output_spec": "For each query print YES if it is possible to make $$$s$$$ equal to $$$t$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["4\nab\nacxb\ncax\na\naaaa\naaabbcc\na\naaaa\naabbcc\nab\nbaaa\naaaaa"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first test case there is the following sequence of operation: $$$s = $$$ ab, $$$t = $$$ acxb, $$$p = $$$ cax; $$$s = $$$ acb, $$$t = $$$ acxb, $$$p = $$$ ax; $$$s = $$$ acxb, $$$t = $$$ acxb, $$$p = $$$ a. In the second test case there is the following sequence of operation: $$$s = $$$ a, $$$t = $$$ aaaa, $$$p = $$$ aaabbcc; $$$s = $$$ aa, $$$t = $$$ aaaa, $$$p = $$$ aabbcc; $$$s = $$$ aaa, $$$t = $$$ aaaa, $$$p = $$$ abbcc; $$$s = $$$ aaaa, $$$t = $$$ aaaa, $$$p = $$$ bbcc. "}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s, t, p = ns()\n var i = 0\n var j = -1\n val flg = Array.ofDim[Boolean](t.length)\n while(i < s.length) {\n j = t.indexOf(s(i), j + 1)\n if (j != -1) {\n flg(j) = true\n i += 1\n } else {\n i = s.length\n }\n }\n\n val cnt = Array.ofDim[Int](26)\n REP(p.length) { i =>\n cnt(p(i)-'a') += 1\n }\n\n debug(flg)\n debug(cnt)\n\n def existsAllMissing = {\n flg.zipWithIndex.filter(!_._1).map(_._2).foreach { i =>\n cnt(t(i)-'a') -= 1\n }\n cnt.forall(_ >= 0)\n }\n\n if (j != -1 && existsAllMissing) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s, t, p = ns()\n var i, j = 0\n val flg = Array.ofDim[Boolean](t.length)\n while(i < s.length && j != -1) {\n j = t.indexOf(s(i), j)\n if (j != -1) flg(j) = true\n i += 1\n }\n\n val cnt = Array.ofDim[Int](26)\n REP(p.length) { i =>\n cnt(p(i)-'a') += 1\n }\n\n debug(flg)\n debug(cnt)\n\n def existsAllMissing = {\n flg.zipWithIndex.filter(!_._1).map(_._2).foreach { i =>\n cnt(t(i)-'a') -= 1\n }\n cnt.forall(_ >= 0)\n }\n\n if (i != -1 && existsAllMissing) {\n out.println(\"YES\")\n } else {\n out.println(\"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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s, t, p = ns()\n var i = 0\n var j = -1\n val flg = Array.ofDim[Boolean](t.length)\n while(i < s.length) {\n j = t.indexOf(s(i), j + 1)\n if (j != -1) {\n flg(j) = true\n i += 1\n } else {\n i = s.length\n }\n }\n\n val cnt = Array.ofDim[Int](26)\n REP(p.length) { i =>\n cnt(p(i)-'a') += 1\n }\n\n debug(flg)\n debug(cnt)\n\n def existsAllMissing = {\n flg.zipWithIndex.filter(!_._1).map(_._2).foreach { i =>\n cnt(t(i)-'a') -= 1\n }\n cnt.forall(_ >= 0)\n }\n\n if (i != -1 && existsAllMissing) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n }\n}"}], "src_uid": "a27ad7c21cd6402bfd082da4f6c7ab9d"} {"nl": {"description": "Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n\u2009\u00d7\u2009n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.", "input_spec": "In the first line of the input, you are given a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.", "output_spec": "Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.", "sample_inputs": ["3\n.CC\nC..\nC.C", "4\nCC..\nC..C\n.CC.\n.CC."], "sample_outputs": ["4", "9"], "notes": "NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are: (1,\u20092) and (1,\u20093) (3,\u20091) and (3,\u20093) Pieces that share the same column are: (2,\u20091) and (3,\u20091) (1,\u20093) and (3,\u20093) "}, "positive_code": [{"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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1,\u2009a2,\u2009...,\u2009an. He remembered that he calculated gcd(ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj) for every 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.", "input_spec": "The first line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the size of the set S. The second line contains m integers s1,\u2009s2,\u2009...,\u2009sm (1\u2009\u2264\u2009si\u2009\u2264\u2009106)\u00a0\u2014 the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1\u2009<\u2009s2\u2009<\u2009...\u2009<\u2009sm.", "output_spec": "If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.", "sample_inputs": ["4\n2 4 6 12", "2\n2 3"], "sample_outputs": ["3\n4 6 12", "-1"], "notes": "NoteIn the first example 2\u2009=\u2009gcd(4,\u20096), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj) for every 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n."}, "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 val magicMod = 1000000007\n\n def doCase() : Unit = {\n val Array(n) = readIntLine()\n val nums = readBigIntLine()\n val numSet = nums.toSet\n val baseGCD = nums.reduce(_.gcd(_))\n if (!(numSet contains baseGCD)) {\n println(-1)\n } else {\n println(numSet.size * 2 - 1)\n println(numSet.mkString(s\" $baseGCD \"))\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": [], "src_uid": "dfe5af743c9e23e98e6c9c5c319d2126"} {"nl": {"description": "There are $$$n$$$ districts in the town, the $$$i$$$-th district belongs to the $$$a_i$$$-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build $$$n-1$$$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build $$$n-1$$$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $$$n-1$$$ roads to satisfy all the conditions.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \\le n \\le 5000$$$) \u2014 the number of districts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the gang the $$$i$$$-th district belongs to. It is guaranteed that the sum of $$$n$$$ does not exceed $$$5000$$$ ($$$\\sum n \\le 5000$$$).", "output_spec": "For each test case, print: NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement. YES on the first line and $$$n-1$$$ roads on the next $$$n-1$$$ lines. Each road should be presented as a pair of integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n; x_i \\ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are two districts the $$$i$$$-th road connects. For each road $$$i$$$, the condition $$$a[x_i] \\ne a[y_i]$$$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).", "sample_inputs": ["4\n5\n1 2 2 1 3\n3\n1 1 1\n4\n1 1000 101 1000\n4\n1 2 3 4"], "sample_outputs": ["YES\n1 3\n3 5\n5 4\n1 2\nNO\nYES\n1 2\n2 3\n3 4\nYES\n1 2\n1 3\n1 4"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contests._1433\n\nobject DistrictsConnection {\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 digits = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val groups = (1 to n).groupBy(i => digits(i - 1)).values.toIndexedSeq\n\n if (groups.size <= 1) \"NO\" else {\n val first = groups.head\n val last = groups.last\n\n val temp = groups.tail\n .foldLeft((new StringBuilder(\"YES\"), first)) { case ((sb, prevG), currG) =>\n (sb.append(prevG.map(\"\\n\" + _ + \" \" + currG.head).mkString(\"\")), currG)\n }\n\n temp._1.append(last.tail.map(\"\\n\" + _ + \" \" + first.head).mkString(\"\")).toString()\n }\n }\n }.mkString(\"\\n\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "d8136eb72931851f501c5ce9042ce4eb"} {"nl": {"description": " As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive \u2014 convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor! ", "input_spec": "The first line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 a number of rod-blanks. The second line contains n integers li (1\u2009\u2264\u2009li\u2009\u2264\u2009109) \u2014 lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.", "output_spec": "Print the only integer z \u2014 the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n\u2009+\u20091) vertices and nonzero area from all of the rods.", "sample_inputs": ["3\n1 2 1", "5\n20 4 3 2 1"], "sample_outputs": ["1", "11"], "notes": "NoteIn the first example triangle with sides {1\u2009+\u20091\u2009=\u20092,\u20092,\u20091} can be formed from a set of lengths {1,\u20091,\u20091,\u20092}. In the second example you can make a triangle with lengths {20,\u200911,\u20094\u2009+\u20093\u2009+\u20092\u2009+\u20091\u2009=\u200910}. "}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!Initially, each test in that problem is just an array. The maximum size of an array is $$$k$$$. For simplicity, the contents of arrays don't matter. You have $$$n$$$ tests \u2014 the $$$i$$$-th test is an array of size $$$m_i$$$ ($$$1 \\le m_i \\le k$$$).Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than $$$c_1$$$ arrays of size greater than or equal to $$$1$$$ ($$$\\ge 1$$$), no more than $$$c_2$$$ arrays of size greater than or equal to $$$2$$$, $$$\\dots$$$, no more than $$$c_k$$$ arrays of size greater than or equal to $$$k$$$. Also, $$$c_1 \\ge c_2 \\ge \\dots \\ge c_k$$$.So now your goal is to create the new testcases in such a way that: each of the initial arrays appears in exactly one testcase; for each testcase the given conditions hold; the number of testcases is minimum possible. Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of initial tests and the limit for the size of each array. The second line contains $$$n$$$ integers $$$m_1, m_2, \\dots, m_n$$$ ($$$1 \\le m_i \\le k$$$)\u00a0\u2014 the sizes of the arrays in the original tests. The third line contains $$$k$$$ integers $$$c_1, c_2, \\dots, c_k$$$ ($$$n \\ge c_1 \\ge c_2 \\ge \\dots \\ge c_k \\ge 1$$$); $$$c_i$$$ is the maximum number of arrays of size greater than or equal to $$$i$$$ you can have in a single testcase.", "output_spec": "In the first line print a single integer $$$ans$$$ ($$$1 \\le ans \\le n$$$)\u00a0\u2014 the minimum number of testcases you can achieve. Each of the next $$$ans$$$ lines should contain the description of a testcase in the following format: $$$t$$$ $$$a_1$$$ $$$a_2$$$ $$$\\dots$$$ $$$a_{t}$$$ ($$$1 \\le t\\le n$$$)\u00a0\u2014 the testcase includes $$$t$$$ arrays, $$$a_i$$$ is the size of the $$$i$$$-th array in that testcase. Each of the initial arrays should appear in exactly one testcase. In particular, it implies that the sum of $$$t$$$ over all $$$ans$$$ testcases should be equal to $$$n$$$. Note that the answer always exists due to $$$c_k \\ge 1$$$ (and therefore $$$c_1 \\ge 1$$$). If there are multiple answers, you can output any one of them.", "sample_inputs": ["4 3\n1 2 2 3\n4 1 1", "6 10\n5 8 1 10 8 7\n6 6 4 4 3 2 2 2 1 1", "5 1\n1 1 1 1 1\n5", "5 1\n1 1 1 1 1\n1"], "sample_outputs": ["3\n1 2\n2 1 3\n1 2", "2\n3 8 5 7\n3 10 8 1", "1\n5 1 1 1 1 1", "5\n1 1\n1 1\n1 1\n1 1\n1 1"], "notes": "NoteIn the first example there is no way to distribute the tests into less than $$$3$$$ testcases. The given answer satisfies the conditions: each of the testcases includes no more than $$$4$$$ arrays of size greater than or equal to $$$1$$$ and no more than $$$1$$$ array of sizes greater than or equal to $$$2$$$ and $$$3$$$.Note that there are multiple valid answers for this test. For example, testcases with sizes $$$[[2], [1, 2], [3]]$$$ would also be correct.However, testcases with sizes $$$[[1, 2], [2, 3]]$$$ would be incorrect because there are $$$2$$$ arrays of size greater than or equal to $$$2$$$ in the second testcase.Note the difference between the third and the fourth examples. You can include up to $$$5$$$ arrays of size greater than or equal to $$$1$$$ in the third example, so you can put all arrays into a single testcase. And you can have only up to $$$1$$$ array in the fourth example. Thus, every array should be included in a separate testcase."}, "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}"}, {"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"}], "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"} {"nl": {"description": "You have n devices that you want to use simultaneously.The i-th device uses ai units of power per second. This usage is continuous. That is, in \u03bb seconds, the device will use \u03bb\u00b7ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for \u03bb seconds, it will gain \u03bb\u00b7p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.", "input_spec": "The first line contains two integers, n and p (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009p\u2009\u2264\u2009109)\u00a0\u2014 the number of devices and the power of the charger. This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the power of the device and the amount of power stored in the device in the beginning.", "output_spec": "If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20094. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .", "sample_inputs": ["2 1\n2 2\n2 1000", "1 100\n1 1", "3 5\n4 3\n5 2\n6 1"], "sample_outputs": ["2.0000000000", "-1", "0.5000000000"], "notes": "NoteIn sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.In sample test 2, you can use the device indefinitely.In sample test 3, we can charge the third device for 2\u2009/\u20095 of a second, then switch to charge the second device for a 1\u2009/\u200910 of a second."}, "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\n val Array(n, p) = readInts(2)\n val as, bs = Array.ofDim[Long](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n as(i) = a\n bs(i) = b\n }\n\n val aSum = as.sum\n\n def can(t: Double): Boolean = {\n var i = 0\n var sum = 0d\n while (i < n) {\n sum += Math.min(as(i) * t, bs(i))\n i += 1\n }\n (aSum - p) * t <= sum\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n val mid = (lo + hi) / 2\n if (depth > 130) mid\n else {\n if (can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n if (aSum <= p) println(-1)\n else {\n val res = binSearchD(0, Long.MaxValue, 0)\n\n println(res)\n }\n}\n"}], "negative_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\n val Array(n, p) = readInts(2)\n val as, bs = Array.ofDim[Long](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n as(i) = a\n bs(i) = b\n }\n\n val aSum = as.sum\n\n def can(t: Double): Boolean = {\n var need = aSum * t\n var i = 0\n while (i < n) {\n need -= Math.min(as(i) * t, bs(i))\n i += 1\n }\n need <= t * p\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n val mid = (lo + hi) / 2\n if (hi - lo < 0.0001d) mid\n else {\n if (can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n if (aSum <= p) println(-1)\n else {\n val res = binSearchD(0, Long.MaxValue, 0)\n\n println(res)\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, p) = readInts(2)\n val as, bs = Array.ofDim[Long](n)\n\n for (i <- 0 until n) {\n val Array(a, b) = readLongs(2)\n as(i) = a\n bs(i) = b\n }\n\n val aSum = as.sum\n\n def can(t: Double): Boolean = {\n var need = aSum * t\n var i = 0\n while (i < n) {\n need -= Math.min(as(i) * t, bs(i))\n i += 1\n }\n need <= t * p\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n val mid = (lo + hi) / 2\n if (depth > 200) mid\n else {\n if (can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n if (aSum <= p) println(-1)\n else {\n val res = binSearchD(0, Long.MaxValue, 0)\n\n println(res)\n }\n}\n"}], "src_uid": "1c2fc9449989d14d9eb02a390f36b7a6"} {"nl": {"description": "Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm \u2009\u00d7\u2009 h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.Leonid offers to divide the labor \u2014 he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?", "input_spec": "The first line contains three integers w,\u2009h,\u2009n (2\u2009\u2264\u2009w,\u2009h\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000). Next n lines contain the descriptions of the cuts. Each description has the form H\u00a0y or V\u00a0x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1\u2009\u2264\u2009y\u2009\u2264\u2009h\u2009-\u20091) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1\u2009\u2264\u2009x\u2009\u2264\u2009w\u2009-\u20091) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.", "output_spec": "After each cut print on a single line the area of the maximum available glass fragment in mm2.", "sample_inputs": ["4 3 4\nH 2\nV 2\nV 3\nV 1", "7 6 5\nH 4\nV 3\nV 5\nH 2\nV 1"], "sample_outputs": ["8\n4\n4\n2", "28\n16\n12\n6\n4"], "notes": "NotePicture for the first sample test: Picture for the second sample test: "}, "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"}, {"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"} {"nl": {"description": "You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \\dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time: Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \\dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 10^{18}$$$) \u2014 the number of vertices in a plot of a piecewise function and the area we need to obtain.", "output_spec": "Print one integer \u2014 the minimum possible height of a plot consisting of $$$2n+1$$$ vertices and with an area equals $$$k$$$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.", "sample_inputs": ["4 3", "4 12", "999999999999999999 999999999999999986"], "sample_outputs": ["1", "3", "1"], "notes": "NoteOne of the possible answers to the first example: The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example: The area of this plot is 12, the height of this plot is 3."}, "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 {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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"} {"nl": {"description": "Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words \"lios\", \"liala\", \"etr\" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.", "input_spec": "The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.", "output_spec": "If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print \"NO\" (without the quotes). Otherwise, print \"YES\" (without the quotes).", "sample_inputs": ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"], "sample_outputs": ["YES", "NO", "YES"], "notes": null}, "positive_code": [{"source_code": "import scala.util.parsing.combinator._\n\nobject CF114B extends RegexParsers {\n def maleStatement = rep(maleAdj) ~> maleNoun <~ rep(maleVerb)\n def femaleStatement = rep(femaleAdj) ~> femaleNoun <~ rep(femaleVerb)\n \n def word = maleAdj | maleNoun | maleVerb | femaleAdj | femaleNoun | femaleVerb\n def maleAdj = \"\"\"\\w*lios\"\"\".r\n def maleNoun = \"\"\"\\w*etr\"\"\".r\n def maleVerb = \"\"\"\\w*initis\"\"\".r\n def femaleAdj = \"\"\"\\w*liala\"\"\".r\n def femaleNoun = \"\"\"\\w*etra\"\"\".r\n def femaleVerb = \"\"\"\\w*inites\"\"\".r\n \n def main(args: Array[String]) {\n val s = readLine\n val success = List(maleStatement, femaleStatement, word) exists (rule => parseAll(rule, s).successful)\n println(if (success) \"YES\" else \"NO\")\n }\n}"}], "negative_code": [{"source_code": "import scala.util.parsing.combinator._\n\nobject CF114B extends RegexParsers {\n def maleStatement = rep(maleAdj) ~> maleNoun <~ rep(maleVerb)\n def femaleStatement = rep(femaleAdj) ~> femaleNoun <~ rep(femaleVerb)\n \n def word = maleAdj | maleNoun | maleVerb | femaleAdj | femaleNoun | femaleVerb\n def maleAdj = \".*lios\".r\n def maleNoun = \".*etr\".r\n def maleVerb = \".*initis\".r\n def femaleAdj = \".*liala\".r\n def femaleNoun = \".*etra\".r\n def femaleVerb = \".*inites\".r\n \n def main(args: Array[String]) {\n val s = readLine\n val success = List(maleStatement, femaleStatement, word) exists (rule => parseAll(rule, s).successful)\n println(if (success) \"YES\" else \"NO\")\n }\n}"}, {"source_code": "import scala.util.parsing.combinator._\n\nobject CF114B extends RegexParsers {\n def maleStatement = rep(maleAdj) ~> maleNoun <~ rep(maleVerb)\n def femaleStatement = rep(femaleAdj) ~> femaleNoun <~ rep(femaleVerb)\n \n def maleAdj = \".*lios\".r\n def maleNoun = \".*etr\".r\n def maleVerb = \".*initis\".r\n def femaleAdj = \".*liala\".r\n def femaleNoun = \".*etra\".r\n def femaleVerb = \".*inites\".r\n \n def main(args: Array[String]) {\n val s = readLine\n val success = parseAll(maleStatement, s).successful || parseAll(femaleStatement, s).successful\n println(if (success) \"YES\" else \"NO\")\n }\n}"}], "src_uid": "0c9550a09f84de6bed529d007ccb4ae8"} {"nl": {"description": "Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps: the character attacks the monster, decreasing the monster's health by $$$d_C$$$; the monster attacks the character, decreasing the character's health by $$$d_M$$$; the character attacks the monster, decreasing the monster's health by $$$d_C$$$; the monster attacks the character, decreasing the character's health by $$$d_M$$$; and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i.\u2009e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5 \\cdot 10^4$$$) \u2014 the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \\le h_C \\le 10^{15}$$$; $$$1 \\le d_C \\le 10^9$$$) \u2014 the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \\le h_M \\le 10^{15}$$$; $$$1 \\le d_M \\le 10^9$$$) \u2014 the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \\le k \\le 2 \\cdot 10^5$$$; $$$0 \\le w \\le 10^4$$$; $$$0 \\le a \\le 10^{10}$$$) \u2014 the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.", "sample_inputs": ["4\n25 4\n9 20\n1 1 10\n25 4\n12 20\n1 1 10\n100 1\n45 2\n0 4 10\n9 2\n69 2\n4 2 7"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \\rightarrow (25, 4) \\rightarrow (5, 4) \\rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor."}, "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"}, {"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"}], "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"} {"nl": {"description": "Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print \"YES\" or \"NO\" accordingly, without the quotes.", "input_spec": "The first line of the input contain two integers n and m (3\u2009\u2264\u2009n\u2009\u2264\u2009150\u2009000, )\u00a0\u2014 the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.", "output_spec": "If the given network is reasonable, print \"YES\" in a single line (without the quotes). Otherwise, print \"NO\" in a single line (without the quotes).", "sample_inputs": ["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"], "sample_outputs": ["YES", "NO", "YES", "NO"], "notes": "NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is \"NO\" in the second sample because members (2,\u20093) are friends and members (3,\u20094) are friends, while members (2,\u20094) are not. "}, "positive_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(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"}, {"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"} {"nl": {"description": "Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string $$$s$$$, you have to delete minimum number of characters from this string so that it becomes good.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of characters in $$$s$$$. The second line contains the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "In the first line, print one integer $$$k$$$ ($$$0 \\le k \\le n$$$) \u2014 the minimum number of characters you have to delete from $$$s$$$ to make it good. In the second line, print the resulting string $$$s$$$. If it is empty, you may leave the second line blank, or not print it at all.", "sample_inputs": ["4\ngood", "4\naabc", "3\naaa"], "sample_outputs": ["0\ngood", "2\nab", "3"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Ctask560 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n\n line = new Scanner(StdIn.readLine())\n val word = line.next.chars().toArray\n\n var click = 1\n var amount = 0\n var result = new ArrayBuffer[Char]()\n for (i <- 0 until n) {\n if ((i + click) % 2 == 1) {\n if (i + 1 != n && word(i) != word(i + 1)) {\n result.append(word(i).toChar)\n } else {\n amount += 1\n click += 1\n }\n } else {\n result.append(word(i).toChar)\n }\n }\n if (result.length() % 2 == 1) {\n result.remove(result.length() - 1)\n amount += 1\n }\n println(amount)\n println(result.mkString(\"\"))\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Ctask560 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n\n line = new Scanner(StdIn.readLine())\n val word = line.next.chars().toArray\n\n var click = 1\n var amount = 0\n var result = new ArrayBuffer[Char]()\n for (i <- 0 until n) {\n if (i + click % 2 == 1) {\n if (i + 1 != n && word(i) != word(i + 1)) {\n result.append(word(i).toChar)\n } else {\n amount += 1\n click += 1\n }\n } else {\n result.append(word(i).toChar)\n }\n }\n if (result.length() % 2 == 1) {\n result.remove(result.length() - 1)\n amount += 1\n }\n println(amount)\n println(result.mkString(\"\"))\n}"}], "src_uid": "c11d67f223eb49c6e8315e2c88dd680d"} {"nl": {"description": "You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of segments and the value of k. The next n lines contain two integers li,\u2009ri (\u2009-\u2009109\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) each \u2014 the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.", "output_spec": "First line contains integer m \u2014 the smallest number of segments. Next m lines contain two integers aj,\u2009bj (aj\u2009\u2264\u2009bj) \u2014 the ends of j-th segment in the answer. The segments should be listed in the order from left to right.", "sample_inputs": ["3 2\n0 5\n-3 2\n3 8", "3 2\n0 5\n-3 3\n3 8"], "sample_outputs": ["2\n0 2\n3 5", "1\n0 5"], "notes": null}, "positive_code": [{"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}"}, {"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}) //\u76f8\u5f53\u4e8ebuf[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 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: \u6240\u6709\u7c7b\u578b\u7684\u5b50\u7c7b\n //Nil: \u7a7a\u7684List\u5373List[Nothing]\n //Null: \u5f15\u7528\u7684\u7a7a\u503c\n //None: \u7a7a\u7684object\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}) //\u76f8\u5f53\u4e8ebuf[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: \u6240\u6709\u7c7b\u578b\u7684\u5b50\u7c7b\n //Nil: \u7a7a\u7684List\u5373List[Nothing]\n //Null: \u5f15\u7528\u7684\u7a7a\u503c\n //None: \u7a7a\u7684object\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}) //\u76f8\u5f53\u4e8ebuf[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}"}], "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\u907f\u514d\u4e24\u4e2a\u70b9\u91cd\u590d\n (x0*2,1)::(x1*2+1,-1)::Input(scan,n-1)\n }\n }\n\n//Nothing: \u6240\u6709\u7c7b\u578b\u7684\u5b50\u7c7b\n//Nil: \u7a7a\u7684List\u5373List[Nothing]\n//Null: \u5f15\u7528\u7684\u7a7a\u503c\n//None: \u7a7a\u7684object\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: \u6240\u6709\u7c7b\u578b\u7684\u5b50\u7c7b\n //Nil: \u7a7a\u7684List\u5373List[Nothing]\n //Null: \u5f15\u7528\u7684\u7a7a\u503c\n //None: \u7a7a\u7684object\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}) //\u76f8\u5f53\u4e8ebuf[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\u907f\u514d\u4e24\u4e2a\u70b9\u91cd\u590d\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\u907f\u514d\u4e24\u4e2a\u70b9\u91cd\u590d\n Input(scan,n-1,inList:::List((x0*2,1),(x1*2+1,-1)))\n }\n }\n//Nothing: \u6240\u6709\u7c7b\u578b\u7684\u5b50\u7c7b\n//Nil: \u7a7a\u7684List\u5373List[Nothing]\n//Null: \u5f15\u7528\u7684\u7a7a\u503c\n//None: \u7a7a\u7684object\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\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}"}, {"source_code": "import java.util.Scanner\nimport scala.collection.immutable.HashSet\n\n/**\n * Created by hama_du on 2014/02/24.\n */\nobject ProblemB extends App {\n val in = new Scanner(System.in)\n\n val n,m = in.nextInt()\n in.nextLine()\n val diffs = (0 until n).map(_ => 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"}], "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"} {"nl": {"description": "Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si\u2009-\u20091\u2009\u2264\u2009si for any i\u2009>\u20091. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.", "input_spec": "The first line of the input contains two space-separated integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7k\u2009\u2264\u2009100\u2009000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009s1\u2009\u2264\u2009s2\u2009\u2264\u2009...\u2009\u2264\u2009sn\u2009\u2264\u20091\u2009000\u2009000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.", "output_spec": "Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.", "sample_inputs": ["2 1\n2 5", "4 3\n2 3 5 9", "3 2\n3 5 7"], "sample_outputs": ["7", "9", "8"], "notes": "NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2,\u20093}, {5} and {9}.In the third sample, the optimal solution is {3,\u20095} and {7}."}, "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)\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}"}, {"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": "/*\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}"}], "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"} {"nl": {"description": "Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000). The second line contains n non-negative integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009<\u2009n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.", "output_spec": "Print a single number \u2014 the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.", "sample_inputs": ["3\n0 2 0", "5\n4 2 3 0 1", "7\n0 3 1 0 5 2 6"], "sample_outputs": ["1", "3", "2"], "notes": "NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7."}, "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 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"}, {"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"}, {"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": "\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}"}], "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"} {"nl": {"description": "You have an $$$n \\times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \\leq x \\leq n$$$ and $$$1 \\leq y \\leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side. Such arrangement of $$$3$$$ rooks on the $$$4 \\times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \\times n$$$ chessboard or report that there is no such arrangement.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \\leq k \\leq n \\leq 40$$$)\u00a0\u2014 the size of the chessboard and the number of rooks.", "output_spec": "If there is a stable arrangement of $$$k$$$ rooks on the $$$n \\times n$$$ chessboard, output $$$n$$$ lines of symbols . and R. The $$$j$$$-th symbol of the $$$i$$$-th line should be equals R if and only if there is a rook on the cell $$$(i, j)$$$ in your arrangement. If there are multiple solutions, you may output any of them. If there is no stable arrangement, output $$$-1$$$.", "sample_inputs": ["5\n\n3 2\n\n3 3\n\n1 1\n\n5 2\n\n40 33"], "sample_outputs": ["..R\n...\nR..\n-1\nR\n.....\nR....\n.....\n....R\n.....\n-1"], "notes": "NoteIn the first test case, you should find stable arrangement of $$$2$$$ rooks on the $$$3 \\times 3$$$ chessboard. Placing them in cells $$$(3, 1)$$$ and $$$(1, 3)$$$ gives stable arrangement.In the second test case it can be shown that it is impossbile to place $$$3$$$ rooks on the $$$3 \\times 3$$$ chessboard to get stable arrangement."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There is a rectangular grid of size $$$n \\times m$$$. Each cell has a number written on it; the number on the cell ($$$i, j$$$) is $$$a_{i, j}$$$. Your task is to calculate the number of paths from the upper-left cell ($$$1, 1$$$) to the bottom-right cell ($$$n, m$$$) meeting the following constraints: You can move to the right or to the bottom only. Formally, from the cell ($$$i, j$$$) you may move to the cell ($$$i, j + 1$$$) or to the cell ($$$i + 1, j$$$). The target cell can't be outside of the grid. The xor of all the numbers on the path from the cell ($$$1, 1$$$) to the cell ($$$n, m$$$) must be equal to $$$k$$$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and \"xor\" in Pascal). Find the number of such paths in the given grid.", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n, m \\le 20$$$, $$$0 \\le k \\le 10^{18}$$$) \u2014 the height and the width of the grid, and the number $$$k$$$. The next $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{i, j}$$$ ($$$0 \\le a_{i, j} \\le 10^{18}$$$).", "output_spec": "Print one integer \u2014 the number of paths from ($$$1, 1$$$) to ($$$n, m$$$) with xor sum equal to $$$k$$$.", "sample_inputs": ["3 3 11\n2 1 5\n7 10 0\n12 6 4", "3 4 2\n1 3 3 3\n0 3 3 2\n3 0 1 1", "3 4 1000000000000000000\n1 3 3 3\n0 3 3 2\n3 0 1 1"], "sample_outputs": ["3", "5", "0"], "notes": "NoteAll the paths from the first example: $$$(1, 1) \\rightarrow (2, 1) \\rightarrow (3, 1) \\rightarrow (3, 2) \\rightarrow (3, 3)$$$; $$$(1, 1) \\rightarrow (2, 1) \\rightarrow (2, 2) \\rightarrow (2, 3) \\rightarrow (3, 3)$$$; $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 2) \\rightarrow (3, 2) \\rightarrow (3, 3)$$$. All the paths from the second example: $$$(1, 1) \\rightarrow (2, 1) \\rightarrow (3, 1) \\rightarrow (3, 2) \\rightarrow (3, 3) \\rightarrow (3, 4)$$$; $$$(1, 1) \\rightarrow (2, 1) \\rightarrow (2, 2) \\rightarrow (3, 2) \\rightarrow (3, 3) \\rightarrow (3, 4)$$$; $$$(1, 1) \\rightarrow (2, 1) \\rightarrow (2, 2) \\rightarrow (2, 3) \\rightarrow (2, 4) \\rightarrow (3, 4)$$$; $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 2) \\rightarrow (2, 3) \\rightarrow (3, 3) \\rightarrow (3, 4)$$$; $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (1, 3) \\rightarrow (2, 3) \\rightarrow (3, 3) \\rightarrow (3, 4)$$$. "}, "positive_code": [{"source_code": "import scala.collection.mutable\n\n/*\n\nlink- http://codeforces.com/problemset/problem/1006/F\n\nThere is a rectangular grid of size n\u00d7m. Each cell has a number written on it; the number on the cell (i,j) is a(i,j).\nYour task is to calculate the number of paths from the upper-left cell (1,1) to the bottom-right cell (n,m) meeting the\nfollowing constraints:\n\nYou can move to the right or to the bottom only. Formally, from the cell (i,j) you may move to the\ncell (i,j+1) or to the cell (i+1,j). The target cell can't be outside of the grid. The xor of all the numbers on the path\nfrom the cell (1,1) to the cell (n,m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented\nas '^' in Java or C++ and \"xor\" in Pascal).Find the number of such paths in the given grid.InputThe first line of the\ninput contains three integers n, m and k (1\u2264n,m\u226420, 0\u2264k\u22641018) \u2014 the height and the width of the grid, and the number k.\n\nThe next n lines contain m integers each, the j-th element in the i-th line is ai,j (0\u2264ai,j\u22641018). OutputPrint one integer-\nthe number of paths from (1,1) to (n,m) with xor sum equal to k.\n\nMeet in the Middle\n\n */\nobject XorPaths {\n\n def main(args: Array[String]): Unit = {\n\n var arr = io.StdIn.readLine.split(\" \").map(_.toLong)\n val n = arr(0).toInt\n val m = arr(1).toInt\n val k = arr(2)\n\n val source = Array.ofDim[Long](n, m)\n for (i <- 0 until n) io.StdIn.readLine.split(\" \").map(_.toLong).zipWithIndex.foreach { case (x, j) => source(i)(j) = x }\n\n def recurForward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Unit = {\n if (depth == 1) {\n val res = xor ^ source(x)(y)\n val count: mutable.Map[Long, Int] = middle.getOrElseUpdate((x, y), collection.mutable.Map[Long, Int]())\n count(res) = count.getOrElse(res, 0) + 1\n\n } else {\n if (x + 1 < n) {\n recurForward(x + 1, y, xor ^ source(x)(y), depth - 1)\n }\n if (y + 1 < m) {\n recurForward(x, y + 1, xor ^ source(x)(y), depth - 1)\n }\n }\n }\n\n def recurBackward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Long = {\n if (depth == 1) middle.getOrElse((x, y), collection.mutable.Map[Long, Int]()).getOrElse(xor ^ k, 0).toLong\n else {\n var ans: Long = 0\n if (x - 1 >= 0) {\n ans += recurBackward(x - 1, y, xor ^ source(x)(y), depth - 1)\n }\n if (y - 1 >= 0) {\n ans += recurBackward(x, y - 1, xor ^ source(x)(y), depth - 1)\n }\n\n ans\n }\n }\n\n implicit val middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]] = collection.mutable.Map[(Int, Int), collection.mutable.Map[Long, Int]]()\n val depth = (n + m) >> 1\n\n recurForward(0, 0, 0, depth)\n println(recurBackward(n - 1, m - 1, 0, n + m - depth))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\n/*\n\nlink- http://codeforces.com/problemset/problem/1006/F\n\nThere is a rectangular grid of size n\u00d7m. Each cell has a number written on it; the number on the cell (i,j) is a(i,j).\nYour task is to calculate the number of paths from the upper-left cell (1,1) to the bottom-right cell (n,m) meeting the\nfollowing constraints:\n\nYou can move to the right or to the bottom only. Formally, from the cell (i,j) you may move to the\ncell (i,j+1) or to the cell (i+1,j). The target cell can't be outside of the grid. The xor of all the numbers on the path\nfrom the cell (1,1) to the cell (n,m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented\nas '^' in Java or C++ and \"xor\" in Pascal).Find the number of such paths in the given grid.InputThe first line of the\ninput contains three integers n, m and k (1\u2264n,m\u226420, 0\u2264k\u22641018) \u2014 the height and the width of the grid, and the number k.\n\nThe next n lines contain m integers each, the j-th element in the i-th line is ai,j (0\u2264ai,j\u22641018). OutputPrint one integer-\nthe number of paths from (1,1) to (n,m) with xor sum equal to k.\n\nMeet in the Middle\n\n */\nobject XorPaths {\n\n def main(args: Array[String]): Unit = {\n\n var arr = io.StdIn.readLine.split(\" \").map(_.toLong)\n val n = arr(0).toInt\n val m = arr(1).toInt\n val k = arr(2)\n\n val source = Array.ofDim[Long](n, m)\n for (i <- 0 until n) io.StdIn.readLine.split(\" \").map(_.toLong).zipWithIndex.foreach { case (x, j) => source(i)(j) = x }\n\n def recurForward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Unit = {\n if (depth == 1) {\n val res = xor ^ source(x)(y)\n val count: mutable.Map[Long, Int] = middle.getOrElseUpdate((x, y), collection.mutable.Map[Long, Int]())\n count(res) = count.getOrElse(res, 0) + 1\n\n } else {\n if (x + 1 < n) {\n recurForward(x + 1, y, xor ^ source(x)(y), depth - 1)\n }\n if (y + 1 < m) {\n recurForward(x, y + 1, xor ^ source(x)(y), depth - 1)\n }\n }\n }\n\n def recurBackward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Int = {\n if (depth == 1) middle.getOrElse((x, y), collection.mutable.Map[Long, Int]()).getOrElse(xor ^ k, 0)\n else {\n var ans = 0\n if (x - 1 >= 0) {\n ans += recurBackward(x - 1, y, xor ^ source(x)(y), depth - 1)\n }\n if (y - 1 >= 0) {\n ans += recurBackward(x, y - 1, xor ^ source(x)(y), depth - 1)\n }\n\n ans\n }\n }\n\n implicit val middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]] = collection.mutable.Map[(Int, Int), collection.mutable.Map[Long, Int]]()\n val depth = (n + m) >> 1\n\n recurForward(0, 0, 0, depth)\n println(recurBackward(n - 1, m - 1, 0, n + m - depth))\n }\n}\n"}], "src_uid": "5642e74bc558ca3187d062ebac6e3a95"} {"nl": {"description": "Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room\u00a0\u2014 five windows, and a seven-room\u00a0\u2014 seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples: if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \\cdot 3 + 2 \\cdot 5 + 2 \\cdot 7 = 30$$$; if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \\cdot 3 + 5 \\cdot 5 + 3 \\cdot 7 = 67$$$; if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows. ", "input_spec": "Th first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the number of windows in the building.", "output_spec": "For each test case, if a building with the new layout and the given number of windows just can't exist, print $$$-1$$$. Otherwise, print three non-negative integers\u00a0\u2014 the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.", "sample_inputs": ["4\n30\n67\n4\n14"], "sample_outputs": ["2 2 2\n7 5 3\n-1\n0 0 2"], "notes": null}, "positive_code": [{"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"}, {"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": "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"}], "negative_code": [], "src_uid": "b43dee2f223c869a35b1b11ceb9d2b6b"} {"nl": {"description": "Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.In the bookshop, Jack decides to buy two books of different genres.Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.The books are given by indices of their genres. The genres are numbered from 1 to m.", "input_spec": "The first line contains two positive integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u20092\u2009\u2264\u2009m\u2009\u2264\u200910) \u2014 the number of books in the bookstore and the number of genres. The second line contains a sequence a1,\u2009a2,\u2009...,\u2009an, where ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009m) equals the genre of the i-th book. It is guaranteed that for each genre there is at least one book of that genre.", "output_spec": "Print the only integer \u2014 the number of ways in which Jack can choose books. It is guaranteed that the answer doesn't exceed the value 2\u00b7109.", "sample_inputs": ["4 3\n2 1 3 1", "7 4\n4 2 3 1 2 4 3"], "sample_outputs": ["5", "18"], "notes": "NoteThe answer to the first test sample equals 5 as Sasha can choose: the first and second books, the first and third books, the first and fourth books, the second and third books, the third and fourth books. "}, "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": "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"}, {"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"} {"nl": {"description": "As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...", "input_spec": "The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).", "output_spec": "Output YES if the string s contains heidi as a subsequence and NO otherwise.", "sample_inputs": ["abcheaibcdi", "hiedi"], "sample_outputs": ["YES", "NO"], "notes": "NoteA string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\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 val s = readLine()\n\n val heidi = \"heidi\"\n\n var i = 0\n var j = 0\n while ((i < s.length) && (j < heidi.length)) {\n if (s(i) == heidi(j)) j += 1\n i += 1\n }\n\n if (j == heidi.length) println(\"YES\") else println(\"NO\")\n}\n"}], "negative_code": [], "src_uid": "a457e22fc8ff882c15ac57bca6960657"} {"nl": {"description": "Polycarp is a head of a circus troupe. There are $$$n$$$\u00a0\u2014 an even number\u00a0\u2014 artists in the troupe. It is known whether the $$$i$$$-th artist can perform as a clown (if yes, then $$$c_i = 1$$$, otherwise $$$c_i = 0$$$), and whether they can perform as an acrobat (if yes, then $$$a_i = 1$$$, otherwise $$$a_i = 0$$$).Split the artists into two performances in such a way that: each artist plays in exactly one performance, the number of artists in the two performances is equal (i.e. equal to $$$\\frac{n}{2}$$$), the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 5\\,000$$$, $$$n$$$ is even)\u00a0\u2014 the number of artists in the troupe. The second line contains $$$n$$$ digits $$$c_1 c_2 \\ldots c_n$$$, the $$$i$$$-th of which is equal to $$$1$$$ if the $$$i$$$-th artist can perform as a clown, and $$$0$$$ otherwise. The third line contains $$$n$$$ digits $$$a_1 a_2 \\ldots a_n$$$, the $$$i$$$-th of which is equal to $$$1$$$, if the $$$i$$$-th artist can perform as an acrobat, and $$$0$$$ otherwise.", "output_spec": "Print $$$\\frac{n}{2}$$$ distinct integers\u00a0\u2014 the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer $$$-1$$$.", "sample_inputs": ["4\n0011\n0101", "6\n000000\n111111", "4\n0011\n1100", "8\n00100101\n01111100"], "sample_outputs": ["1 4", "-1", "4 3", "1 2 3 6"], "notes": "NoteIn the first example, one of the possible divisions into two performances is as follows: in the first performance artists $$$1$$$ and $$$4$$$ should take part. Then the number of artists in the first performance who can perform as clowns is equal to $$$1$$$. And the number of artists in the second performance who can perform as acrobats is $$$1$$$ as well.In the second example, the division is not possible.In the third example, one of the possible divisions is as follows: in the first performance artists $$$3$$$ and $$$4$$$ should take part. Then in the first performance there are $$$2$$$ artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is $$$2$$$ as well."}, "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 C, A = ns(N).map(_ - '0')\n\n val Tpe = Array.ofDim[Int](N)\n val T = Array.ofDim[Int](4)\n REP(N) { i =>\n val tpe = if (C(i) == 0 && A(i) == 0) 0\n else if (C(i) == 1 && A(i) == 0) 1\n else if (C(i) == 0 && A(i) == 1) 2\n else 3\n Tpe(i) = tpe\n T(tpe) += 1\n }\n\n debug(Tpe)\n\n def isAllGteZero(p: Array[Int]) = {\n var ok = true\n REP(p.length) { i =>\n ok &&= p(i) >= 0\n }\n ok\n }\n\n val p1, p2 = Array.ofDim[Int](4)\n // \u30af\u30e9\u30a6\u30f3\u3001\u30a2\u30af\u30ed\u30d0\u30c3\u30c8\u306e\u4eba\u6570\u3092\u6c7a\u3081\u308b\n REP(T(1) + T(3) + 1) { x =>\n val mxLoop = min(T(1), x) + 1\n REP(mxLoop) { i => // type1\u306e\u4eba\u6570\n p1(1) = i\n p1(3) = x - i\n p2(3) = T(3) - p1(3)\n p2(2) = x - p2(3)\n p1(2) = T(2) - p2(2)\n p2(1) = T(1) - p1(1)\n p1(0) = 0\n p2(0) = 0\n\n // \u5168\u90e80\u4ee5\u4e0a\u304b\u3064\u8db3\u3057\u3066N/2\u4ee5\u4e0b\n if (isAllGteZero(p1) &&\n isAllGteZero(p2) &&\n sumL(p1) <= N / 2 &&\n sumL(p2) <= N / 2) {\n\n p1(0) = N / 2 - p1.sum\n\n debug(p1)\n debug(p2)\n\n val ans = ArrayBuffer[Int]()\n REP(N) { j =>\n if (p1(Tpe(j)) > 0) {\n p1(Tpe(j)) -= 1\n ans += j + 1\n }\n }\n out.println(ans.mkString(\" \"))\n return\n }\n }\n }\n\n out.println(-1)\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": "3afa68fbe090683ffe16c3141aafe76e"} {"nl": {"description": "In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:That is, a cardiogram is fully defined by a sequence of positive integers a1,\u2009a2,\u2009...,\u2009an.Your task is to paint a cardiogram by given sequence ai.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000). The next line contains the sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000). It is guaranteed that the sum of all ai doesn't exceed 1000.", "output_spec": "Print max\u00a0|yi\u2009-\u2009yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print characters. Each character must equal either \u00ab\u2009/\u2009\u00bb (slash), \u00ab \\ \u00bb (backslash), \u00ab \u00bb (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.", "sample_inputs": ["5\n3 1 2 5 1", "3\n1 5 1"], "sample_outputs": ["/\u2009\n\n\\\n \n \n\u2009/\u2009\n\n\\\n\n\u2009/\u2009\n \n\\\n \n \n\u2009/\u2009\n \n\\\n \n\n\u2009/\u2009\n \n\\\n \n \n\\\n\n\u2009/", "/\u2009\n\n\\\n \n \n\\\n \n \n\\\n \n \n\\\n \n \n\\\n\n\u2009/"], "notes": "NoteDue to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.http://assets.codeforces.com/rounds/435/1.txthttp://assets.codeforces.com/rounds/435/2.txt"}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n\u2009-\u20091 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence \u2009-\u2009 Minimum_element_of_subsequence \u2009\u2265\u2009dPikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print \u2009-\u20091.", "input_spec": "The only line of input consists of two space separated integers X and d (1\u2009\u2264\u2009X,\u2009d\u2009\u2264\u2009109).", "output_spec": "Output should consist of two lines. First line should contain a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000)\u2014 the number of integers in the final array. Second line should consist of n space separated integers \u2014 a1,\u2009a2,\u2009... ,\u2009an (1\u2009\u2264\u2009ai\u2009<\u20091018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them.", "sample_inputs": ["10 5", "4 2"], "sample_outputs": ["6\n5 50 7 15 6 100", "4\n10 100 1000 10000"], "notes": "NoteIn the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence \u2009-\u2009 Minimum_element_of_subsequence \u2009\u2265\u20095 are [5],\u2009[5,\u20097],\u2009[5,\u20096],\u2009[5,\u20097,\u20096],\u2009[50],\u2009[7],\u2009[7,\u20096],\u2009[15],\u2009[6],\u2009[100]. There are 10 of them. Hence, the array [5,\u200950,\u20097,\u200915,\u20096,\u2009100] is valid.Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence \u2009-\u2009 Minimum_element_of_subsequence \u2009\u2265\u20092 are [10],\u2009[100],\u2009[1000],\u2009[10000]. There are 4 of them. Hence, the array [10,\u2009100,\u20091000,\u200910000] is valid."}, "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val X, d = sc.nextLong\n lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)\n \n val xs = bm.takeWhile(_ <= X).foldLeft((List[Long](), 1L)) {\n case ((acc, d1), bm) =>\n if ((X & bm) != 0) {\n (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)\n } else {\n (acc, d1)\n }\n }\n println(xs._1.length)\n print(xs._1.head)\n xs._1.tail.foreach(x => printf(\" %d\", x))\n }\n \n import scala.math.log\n def log2(x: Double): Double = log(x) / log(2)\n}"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val X, d = sc.nextInt\n lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)\n \n val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {\n case ((acc, d1), bm) =>\n if ((X & bm) != 0) {\n (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)\n } else {\n (acc, d1)\n }\n }\n print(xs._1.head)\n xs._1.tail.foreach(x => printf(\" %d\", x))\n }\n \n import scala.math.log\n def log2(x: Double): Double = log(x) / log(2)\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val X, d = sc.nextInt\n lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)\n \n val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {\n case ((acc, d1), bm) =>\n if ((X & bm) != 0) {\n (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)\n } else {\n (acc, d1)\n }\n }\n print(xs._1.length)\n xs._1.foreach(x => printf(\"%d \", x))\n }\n \n import scala.math.log\n def log2(x: Double): Double = log(x) / log(2)\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val X, d = sc.nextInt\n lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)\n \n val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {\n case ((acc, d1), bm) =>\n if ((X & bm) != 0) {\n (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)\n } else {\n (acc, d1)\n }\n }\n println(xs._1.length)\n print(xs._1.head)\n xs._1.tail.foreach(x => printf(\" %d\", x))\n }\n \n import scala.math.log\n def log2(x: Double): Double = log(x) / log(2)\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val sc = new java.util.Scanner(System.in)\n val X, d = sc.nextInt\n lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)\n \n val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {\n case ((acc, d1), bm) =>\n if ((X & bm) != 0) {\n (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)\n } else {\n (acc, d1)\n }\n }\n \n xs._1.foreach(x => printf(\"%d \", x))\n }\n \n import scala.math.log\n def log2(x: Double): Double = log(x) / log(2)\n}"}], "src_uid": "f5588694b1d800271ccdcf14b0ba8f67"} {"nl": {"description": "Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1,\u2009a2,\u2009...,\u2009an. Let's denote f(l,\u2009r,\u2009x) the number of indices k such that: l\u2009\u2264\u2009k\u2009\u2264\u2009r and ak\u2009=\u2009x. His task is to calculate the number of pairs of indicies i,\u2009j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) such that f(1,\u2009i,\u2009ai)\u2009>\u2009f(j,\u2009n,\u2009aj).Help Pashmak with the test.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the answer to the problem.", "sample_inputs": ["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"], "sample_outputs": ["8", "1", "0"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Word $$$s$$$ of length $$$n$$$ is called $$$k$$$-complete if $$$s$$$ is a palindrome, i.e. $$$s_i=s_{n+1-i}$$$ for all $$$1 \\le i \\le n$$$; $$$s$$$ has a period of $$$k$$$, i.e. $$$s_i=s_{k+i}$$$ for all $$$1 \\le i \\le n-k$$$. For example, \"abaaba\" is a $$$3$$$-complete word, while \"abccba\" is not.Bob is given a word $$$s$$$ of length $$$n$$$ consisting of only lowercase Latin letters and an integer $$$k$$$, such that $$$n$$$ is divisible by $$$k$$$. He wants to convert $$$s$$$ to any $$$k$$$-complete word.To do this Bob can choose some $$$i$$$ ($$$1 \\le i \\le n$$$) and replace the letter at position $$$i$$$ with some other lowercase Latin letter.So now Bob wants to know the minimum number of letters he has to replace to convert $$$s$$$ to any $$$k$$$-complete word.Note that Bob can do zero changes if the word $$$s$$$ is already $$$k$$$-complete.You are required to answer $$$t$$$ test cases independently.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t\\le 10^5$$$) \u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k < n \\le 2 \\cdot 10^5$$$, $$$n$$$ is divisible by $$$k$$$). The second line of each test case contains a word $$$s$$$ of length $$$n$$$. It is guaranteed that word $$$s$$$ only contains lowercase Latin letters. And it is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output one integer, representing the minimum number of characters he has to replace to convert $$$s$$$ to any $$$k$$$-complete word.", "sample_inputs": ["4\n6 2\nabaaba\n6 3\nabaaba\n36 9\nhippopotomonstrosesquippedaliophobia\n21 7\nwudixiaoxingxingheclp"], "sample_outputs": ["2\n0\n23\n16"], "notes": "NoteIn the first test case, one optimal solution is aaaaaa.In the second test case, the given word itself is $$$k$$$-complete."}, "positive_code": [{"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 s = scala.io.StdIn.readLine()\n\n val t = (k + 1) / 2\n\n val ans = s.zipWithIndex\n .foldLeft(Array.fill(t)(List.empty[Char])) {\n case (ls, (s, i)) =>\n ls((i % k).min(k - i % k - 1)) ::= s\n ls\n }\n .foldLeft(0)(\n _ + _.groupBy(identity).values.toList.sortBy(_.length)(Ordering.Int.reverse).tail.foldLeft(0)(_ + _.length)\n )\n\n println(ans)\n\n }\n\n}\n"}], "negative_code": [], "src_uid": "22f90afe503267ff2c832430d3ffb3b4"} {"nl": {"description": "Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,\u2009u)\u2009>\u2009au, where au is the number written on vertex u, dist(v,\u2009u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex\u00a0\u2014 root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?", "input_spec": "In the first line of the input integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) is given\u00a0\u2014 the number of vertices in the tree. In the second line the sequence of n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) is given, where ai is the number written on vertex i. The next n\u2009-\u20091 lines describe tree edges: ith of them consists of two integers pi and ci (1\u2009\u2264\u2009pi\u2009\u2264\u2009n, \u2009-\u2009109\u2009\u2264\u2009ci\u2009\u2264\u2009109), meaning that there is an edge connecting vertices i\u2009+\u20091 and pi with number ci written on it.", "output_spec": "Print the only integer\u00a0\u2014 the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.", "sample_inputs": ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"], "sample_outputs": ["5"], "notes": "NoteThe following image represents possible process of removing leaves from the tree: "}, "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 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"}, {"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"} {"nl": {"description": "INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.2. The i-th element of the array is subtracted from the result of the previous step modulo 256.3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.You are given the text printed using this method. Restore the array used to produce this text.", "input_spec": "The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.", "output_spec": "Output the initial array, which was used to produce text, one integer per line.", "sample_inputs": ["Hello, World!"], "sample_outputs": ["238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162"], "notes": "NoteLet's have a closer look at the beginning of the example. The first character is \"H\" with ASCII-code 72\u2009=\u2009010010002. Its reverse is 000100102\u2009=\u200918, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0\u2009-\u200918) mod 256\u2009=\u2009238, where a mod b is the remainder of division of a by b."}, "positive_code": [{"source_code": "\nobject Main {\n \n def reverseBits(x : Int) : Int = {\n var res = 0\n var k = x\n \n for(i <- 0 until 8) {\n res = (res << 1) | (k & 1)\n k >>= 1\n }\n \n res\n }\n \n def mod(a : Int, b : Int) : Int = {\n return (a % b + b) % b\n }\n \n def main(args : Array[String]) {\n var last = 0;\n readLine foreach (x => {\n val curr = reverseBits(x toInt)\n println(mod(last - curr, 256))\n last = curr\n }\n )\n }\n}\n"}], "negative_code": [], "src_uid": "a65e12186430f74c18c50d2eb55a9794"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$, each contains $$$n$$$ integers.You want to create a new array $$$c$$$ as follows: choose some real (i.e. not necessarily integer) number $$$d$$$, and then for every $$$i \\in [1, n]$$$ let $$$c_i := d \\cdot a_i + b_i$$$.Your goal is to maximize the number of zeroes in array $$$c$$$. What is the largest possible answer, if you choose $$$d$$$ optimally?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$). The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$-10^9 \\le b_i \\le 10^9$$$).", "output_spec": "Print one integer \u2014 the maximum number of zeroes in array $$$c$$$, if you choose $$$d$$$ optimally.", "sample_inputs": ["5\n1 2 3 4 5\n2 4 7 11 3", "3\n13 37 39\n1 2 3", "4\n0 0 0 0\n1 2 3 4", "3\n1 2 -1\n-6 -12 6"], "sample_outputs": ["2", "2", "0", "3"], "notes": "NoteIn the first example, we may choose $$$d = -2$$$.In the second example, we may choose $$$d = -\\frac{1}{13}$$$.In the third example, we cannot obtain any zero in array $$$c$$$, no matter which $$$d$$$ we choose.In the fourth example, we may choose $$$d = 6$$$."}, "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\u304c\u6b63\u306b\u306a\u308b\u3088\u3046\u306b\u305d\u308d\u3048\u308b\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"}, {"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}"}], "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\u304c\u6b63\u306b\u306a\u308b\u3088\u3046\u306b\u305d\u308d\u3048\u308b\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\u304c\u6b63\u306b\u306a\u308b\u3088\u3046\u306b\u305d\u308d\u3048\u308b\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"} {"nl": {"description": "This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.Alice received a set of Toy Train\u2122 from Bob. It consists of one train and a connected railway network of $$$n$$$ stations, enumerated from $$$1$$$ through $$$n$$$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $$$i$$$ is station $$$i+1$$$ if $$$1 \\leq i < n$$$ or station $$$1$$$ if $$$i = n$$$. It takes the train $$$1$$$ second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver $$$m$$$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $$$1$$$ through $$$m$$$. Candy $$$i$$$ ($$$1 \\leq i \\leq m$$$), now at station $$$a_i$$$, should be delivered to station $$$b_i$$$ ($$$a_i \\neq b_i$$$). The blue numbers on the candies correspond to $$$b_i$$$ values. The image corresponds to the $$$1$$$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.", "input_spec": "The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \\leq n \\leq 100$$$; $$$1 \\leq m \\leq 200$$$) \u2014 the number of stations and the number of candies, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq n$$$; $$$a_i \\neq b_i$$$) \u2014 the station that initially contains candy $$$i$$$ and the destination station of the candy, respectively.", "output_spec": "In the first and only line, print $$$n$$$ space-separated integers, the $$$i$$$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $$$i$$$.", "sample_inputs": ["5 7\n2 4\n5 1\n2 3\n3 4\n4 1\n5 3\n3 5", "2 3\n1 2\n1 2\n1 2"], "sample_outputs": ["10 9 10 10 9", "5 6"], "notes": "NoteConsider the second sample.If the train started at station $$$1$$$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $$$2$$$. This step takes $$$1$$$ second. Deliver the first candy. Proceed to station $$$1$$$. This step takes $$$1$$$ second. Load the second candy onto the train. Proceed to station $$$2$$$. This step takes $$$1$$$ second. Deliver the second candy. Proceed to station $$$1$$$. This step takes $$$1$$$ second. Load the third candy onto the train. Proceed to station $$$2$$$. This step takes $$$1$$$ second. Deliver the third candy. Hence, the train needs $$$5$$$ seconds to complete the tasks.If the train were to start at station $$$2$$$, however, it would need to move to station $$$1$$$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $$$5+1 = 6$$$ seconds."}, "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 C = Array.ofDim[Int](N)\n val last = Array.fill[Int](N)(-1)\n\n def dist(i: Int, j: Int): Int = (j + N - i) % N\n\n def compare(i: Int, j1: Int, j2: Int): Int = {\n Integer.compare(dist(i, j1), dist(i, j2))\n }\n\n REP(M) { _ =>\n val a, b = ni() - 1\n C(a) += 1\n\n // \u6700\u5f8c\u306b\u6301\u3061\u51fa\u3059\u98f4\u306f\u6642\u8a08\u56de\u308a\u3067\u3061\u304b\u3044\u3082\u306e\u304c\u3044\u3044\n if (last(a) == -1 || compare(a, b, last(a)) < 0) {\n last(a) = b\n }\n }\n\n debug(\"C\")\n debug(C)\n debug(\"last\")\n debug(last)\n\n val ans = ArrayBuffer[Int]()\n REP(N) { i =>\n val (mx, mxIx) = C.zipWithIndex.maxBy { case (cnt, j) => (cnt, dist(i, j)) }\n\n debug(s\"i:$i mx:$mx mxIx:$mxIx\")\n\n // \u4e00\u756a\u6700\u5f8c\u306b\u98f4\u3092\u3068\u308b\u3068\u304d\u304b\u3089\u3061\u3087\u3046\u3069\u4e00\u5468\u524d\u304b\u3089\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u3059\u308b\n var move = max(-1, (mx - 2) * N + dist(i, mxIx)) // \u6700\u521d\u306b\uff11\u6b69\u9032\u3080\u306e\u3067-1\u304c\u4e0b\u9650\u306a\u306e\u304c\u59a5\u5f53\n var j = (i + move) % N\n val loaded = Array.ofDim[Boolean](N)\n var lastCandyLoaded = false\n var candyCnt = 0\n\n // \u7a4d\u3080\u98f4\u304c\u307e\u3060\u6b8b\u3063\u3066\u3044\u308b\u304b\u3001\u30ad\u30e3\u30f3\u30c7\u30a3\u3092\u307e\u3060\u7a4d\u3093\u3067\u3044\u308b\u306a\u3089\u5468\u56de\u3092\u3064\u3065\u3051\u308b\n while(!lastCandyLoaded || candyCnt > 0) {\n j = (j + 1) % N\n move += 1\n val m = move / N + 1 // \u5468\u56de\n\n debug(s\"step $j $move m:$m\")\n\n // \u3053\u306e\u5468\u56de\u3067\u307e\u3060\u8f09\u305b\u308b\u30ad\u30e3\u30f3\u30c7\u30a3\u30fc\u304c\u6b8b\u3063\u3066\u3044\u308b\u306a\u3089\u8f09\u305b\u308b\u3002\u305f\u3060\u3057\u540c\u3058\u7a2e\u985e\u306a\u3089\u610f\u5473\u306a\u3044\u306e\u3067\u7121\u8996\u3059\u308b\n if (C(j) >= m && !loaded(last(j))) {\n debug(s\"load ${last(j)}\")\n loaded(last(j)) = true\n candyCnt += 1\n }\n\n // \u964d\u308d\u3059\n if (loaded(j)) {\n debug(s\"unload\")\n loaded(j) = false\n candyCnt -= 1\n }\n\n if (j == mxIx) lastCandyLoaded = true\n }\n\n ans += move\n }\n\n 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 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": [], "src_uid": "ab904e148bc7ba4cca38078c7ea41ad6"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$. Both strings have length $$$n$$$ and consist of lowercase Latin letters. The characters in the strings are numbered from $$$1$$$ to $$$n$$$.You can successively perform the following move any number of times (possibly, zero): swap any two adjacent (neighboring) characters of $$$s$$$ (i.e. for any $$$i = \\{1, 2, \\dots, n - 1\\}$$$ you can swap $$$s_i$$$ and $$$s_{i + 1})$$$. You can't apply a move to the string $$$t$$$. The moves are applied to the string $$$s$$$ one after another.Your task is to obtain the string $$$t$$$ from the string $$$s$$$. Find any way to do it with at most $$$10^4$$$ such moves.You do not have to minimize the number of moves, just find any sequence of moves of length $$$10^4$$$ or less to transform $$$s$$$ into $$$t$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the length of strings $$$s$$$ and $$$t$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the input contains the string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "If it is impossible to obtain the string $$$t$$$ using moves, print \"-1\". Otherwise in the first line print one integer $$$k$$$ \u2014 the number of moves to transform $$$s$$$ to $$$t$$$. Note that $$$k$$$ must be an integer number between $$$0$$$ and $$$10^4$$$ inclusive. In the second line print $$$k$$$ integers $$$c_j$$$ ($$$1 \\le c_j < n$$$), where $$$c_j$$$ means that on the $$$j$$$-th move you swap characters $$$s_{c_j}$$$ and $$$s_{c_j + 1}$$$. If you do not need to apply any moves, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.", "sample_inputs": ["6\nabcdef\nabdfec", "4\nabcd\naccd"], "sample_outputs": ["4\n3 5 4 5", "-1"], "notes": "NoteIn the first example the string $$$s$$$ changes as follows: \"abcdef\" $$$\\rightarrow$$$ \"abdcef\" $$$\\rightarrow$$$ \"abdcfe\" $$$\\rightarrow$$$ \"abdfce\" $$$\\rightarrow$$$ \"abdfec\".In the second example there is no way to transform the string $$$s$$$ into the string $$$t$$$ through any allowed moves."}, "positive_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), 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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}"}, {"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"}], "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said \"lala.\" at the end of her sentences, while Rainbow always said \"miao.\" at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is. ", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn\u2019t exceed 100.", "output_spec": "For each sentence, output \"Freda's\" if the sentence was said by Freda, \"Rainbow's\" if the sentence was said by Rainbow, or \"OMG>.< I don't know!\" if liouzhou_101 can\u2019t recognize whose sentence it is. He can\u2019t recognize a sentence if it begins with \"miao.\" and ends with \"lala.\", or satisfies neither of the conditions. ", "sample_inputs": ["5\nI will go to play with you lala.\nwow, welcome.\nmiao.lala.\nmiao.\nmiao ."], "sample_outputs": ["Freda's\nOMG>.< I don't know!\nOMG>.< I don't know!\nRainbow's\nOMG>.< I don't know!"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Even the most successful company can go through a crisis period when you have to make a hard decision \u2014 to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types: Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n) \u2014 are numbers of two of some company employees. If team(x) matches team(y), then nothing happens. Merge departments team(x),\u2009team(x\u2009+\u20091),\u2009...,\u2009team(y), where x and y (1\u2009\u2264\u2009x\u2009\u2264\u2009y\u2009\u2264\u2009n) \u2014 the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees x and y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n) work at the same department.Help the crisis manager and answer all of his queries.", "input_spec": "The first line of the input contains two integers n and q (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009q\u2009\u2264\u2009500\u2009000) \u2014 the number of the employees of the company and the number of queries the crisis manager has. Next q lines contain the queries of the crisis manager. Each query looks like type\u00a0x\u00a0y, where . If type\u2009=\u20091 or type\u2009=\u20092, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type\u2009=\u20093, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.", "output_spec": "For each question of type 3 print \"YES\" or \"NO\" (without the quotes), depending on whether the corresponding people work in the same department.", "sample_inputs": ["8 6\n3 2 5\n1 2 5\n3 2 5\n2 4 7\n2 1 2\n3 1 7"], "sample_outputs": ["NO\nYES\nYES"], "notes": null}, "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 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 val Array(n, q) = readInts(2)\n\n val uf = new UnionFind(n)\n val nexts = Array.tabulate(n)(_ + 1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (_ <- 0 until q) {\n \n val Array(t, _x, _y) = readInts(3)\n val x = _x - 1\n val y = _y - 1\n \n t match {\n\n case 1 =>\n uf.union(x, y)\n\n case 2 =>\n var l = x + 1\n while (l <= y) {\n uf.union(l, x)\n val tmp = l\n l = nexts(l)\n nexts(tmp) = y + 1\n }\n\n case 3 =>\n println(if (uf.same(x, y)) \"YES\" else \"NO\")\n }\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\n //FIXME Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println()\n\n Console.flush\n}\n"}], "src_uid": "1fdba13aaa1a417a229817b40af7225f"} {"nl": {"description": "This is a harder version of the problem. In this version, $$$n \\le 300\\,000$$$.Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.We remind that bracket sequence $$$s$$$ is called correct if: $$$s$$$ is empty; $$$s$$$ is equal to \"($$$t$$$)\", where $$$t$$$ is correct bracket sequence; $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, \"(()())\", \"()\" are correct, while \")(\" and \"())\" are not.The cyclical shift of the string $$$s$$$ of length $$$n$$$ by $$$k$$$ ($$$0 \\leq k < n$$$) is a string formed by a concatenation of the last $$$k$$$ symbols of the string $$$s$$$ with the first $$$n - k$$$ symbols of string $$$s$$$. For example, the cyclical shift of string \"(())()\" by $$$2$$$ equals \"()(())\".Cyclical shifts $$$i$$$ and $$$j$$$ are considered different, if $$$i \\ne j$$$.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 300\\,000$$$), the length of the string. The second line contains a string, consisting of exactly $$$n$$$ characters, where each of the characters is either \"(\" or \")\".", "output_spec": "The first line should contain a single integer\u00a0\u2014 the largest beauty of the string, which can be achieved by swapping some two characters. The second line should contain integers $$$l$$$ and $$$r$$$ ($$$1 \\leq l, r \\leq n$$$)\u00a0\u2014 the indices of two characters, which should be swapped in order to maximize the string's beauty. In case there are several possible swaps, print any of them.", "sample_inputs": ["10\n()()())(()", "12\n)(()(()())()", "6\n)))(()"], "sample_outputs": ["5\n8 7", "4\n5 10", "0\n1 1"], "notes": "NoteIn the first example, we can swap $$$7$$$-th and $$$8$$$-th character, obtaining a string \"()()()()()\". The cyclical shifts by $$$0, 2, 4, 6, 8$$$ of this string form a correct bracket sequence.In the second example, after swapping $$$5$$$-th and $$$10$$$-th character, we obtain a string \")(())()()(()\". The cyclical shifts by $$$11, 7, 5, 3$$$ of this string form a correct bracket sequence.In the third example, swap of any two brackets results in $$$0$$$ cyclical shifts being correct bracket sequences. "}, "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 Ans(num: Int, i: Int, j: Int)\n def maxAns(a1: Ans, a2: Ans) = if (a1.num >= a2.num) a1 else a2\n val zero = Ans(0, 0, 0)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val s = ns(n)\n val bal = Array.ofDim[Int](n)\n REP(n) { i =>\n if (i > 0) bal(i) = bal(i - 1)\n bal(i) += (if (s(i) == '(') 1 else -1)\n }\n val minBal = bal.min\n val cntMin = bal.count(_ == minBal)\n\n val cumMin, cumPlus1, cumPlus2 = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n if (bal(i) == minBal) cumMin(i + 1) = 1\n if (bal(i) == minBal + 1) cumPlus1(i + 1) = 1\n if (bal(i) == minBal + 2) cumPlus2(i + 1) = 1\n }\n REP(n) { i =>\n cumMin(i + 1) += cumMin(i)\n cumPlus1(i + 1) += cumPlus1(i)\n cumPlus2(i + 1) += cumPlus2(i)\n }\n debug(bal)\n debug(cumMin)\n debug(cumPlus1)\n debug(cumPlus2)\n\n def show(ans: Ans): Unit = {\n out.println(ans.num)\n out.println(s\"${ans.i+1} ${ans.j+1}\")\n }\n\n if (bal.last != 0) {\n show(zero)\n return\n }\n\n def cntEq: Ans = {\n var i, j = 0\n var ans = Ans(cntMin, 0, 0)\n while(i < n) {\n j = i\n var p1, p2 = -1\n while(j < n && bal(j) >= minBal + 2) {\n if (s(j) == '(' && p1 == -1) p1 = j\n if (s(j) == ')') p2 = j\n j += 1\n }\n if (j < n && s(j) == ')') p2 = j\n debug(s\"$i $j $p1 $p2\")\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val cntNew = cumPlus2(p2) - cumPlus2(p1)\n ans = maxAns(ans, Ans(cntMin + cntNew, p1, p2))\n }\n i = j + 1\n }\n\n ans\n }\n\n def cntMinus1: Ans = {\n var i, j = 0\n var ans = Ans(0, 0, 0)\n while(i < n) {\n j = i\n var p1, p2 = -1\n while(j < n && bal(j) > minBal) {\n if (s(j) == '(' && p1 == -1) p1 = j\n if (s(j) == ')') p2 = j\n j += 1\n }\n if (j < n && s(j) == ')') p2 = j\n debug(s\"$i $j $p1 $p2\")\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val cntNew = cumPlus1(p2) - cumPlus1(p1)\n ans = maxAns(ans, Ans(cntNew, p1, p2))\n }\n i = j + 1\n }\n\n ans\n }\n\n def cntPlus1: Ans = {\n // min\u3092\u5168\u90e8\u6d88\u3059\n var p1, p2 = -1\n var ans = Ans(0, 0, 0)\n var i = bal.indexWhere(_ == minBal)\n while(i >= 0) {\n if (s(i) == ')' && p1 == -1) p1 = i\n i -= 1\n }\n var j = bal.lastIndexWhere(_ == minBal) + 1\n while(j < n) {\n if (s(j) == '(' && p2 == -1) p2 = j\n j += 1\n }\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val l = cumPlus1(p1)\n val r = cumPlus1.last - cumPlus1(p2)\n ans = maxAns(ans, Ans(l + r, p1, p2))\n }\n\n ans\n }\n\n def cntPlus2: Ans = {\n // min\u3068min+1\u3092\u5168\u90e8\u6d88\u3059\n var p1, p2 = -1\n var v = 0\n var i = bal.indexWhere(a => a == minBal || a == minBal + 1)\n while(i >= 0) {\n if (s(i) == ')' && p1 == -1) {\n val oldP2 = cumPlus2(i)\n val newP2 = cumMin.last - cumMin(i)\n if (v < oldP2 + newP2) {\n p1 = i\n v = oldP2 + newP2\n }\n }\n i -= 1\n }\n v = 0\n var j = bal.lastIndexWhere(a => a == minBal || a == minBal + 1) + 1\n while(j < n) {\n if (s(j) == '(' && p2 == -1) {\n val oldP2 = cumPlus2.last - cumPlus2(j)\n val newP2 = cumMin(j)\n if (v < oldP2 + newP2) {\n p2 = j\n v = oldP2 + newP2\n }\n }\n j += 1\n }\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val oldP2 = cumPlus2(p1) + cumPlus2.last - cumPlus2(p2)\n val newP2 = cumMin(p2) - cumMin(p1)\n Ans(oldP2 + newP2, p1, p2)\n } else {\n zero\n }\n }\n\n debug(s\"cntEq:$cntEq\")\n debug(s\"cntMinus1:$cntMinus1\")\n debug(s\"cntPlus1:$cntPlus1\")\n debug(s\"cntPlus2:$cntPlus2\")\n\n val ans = Seq(cntEq, cntMinus1, cntPlus1, cntPlus2).maxBy(_.num)\n show(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[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 Ans(num: Int, i: Int, j: Int)\n def maxAns(a1: Ans, a2: Ans) = if (a1.num >= a2.num) a1 else a2\n val zero = Ans(0, 0, 0)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val s = ns(n)\n val bal = Array.ofDim[Int](n)\n REP(n) { i =>\n if (i > 0) bal(i) = bal(i - 1)\n bal(i) += (if (s(i) == '(') 1 else -1)\n }\n val minBal = bal.min\n val cntMin = bal.count(_ == minBal)\n\n val cumMin, cumPlus1, cumPlus2 = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n if (bal(i) == minBal) cumMin(i + 1) = 1\n if (bal(i) == minBal + 1) cumPlus1(i + 1) = 1\n if (bal(i) == minBal + 2) cumPlus2(i + 1) = 1\n }\n REP(n) { i =>\n cumMin(i + 1) += cumMin(i)\n cumPlus1(i + 1) += cumPlus1(i)\n cumPlus2(i + 1) += cumPlus2(i)\n }\n debug(bal)\n debug(cumMin)\n debug(cumPlus1)\n debug(cumPlus2)\n\n def show(ans: Ans): Unit = {\n out.println(ans.num)\n out.println(s\"${ans.i+1} ${ans.j+1}\")\n }\n\n if (bal.last != 0) {\n show(zero)\n return\n }\n\n def cntEq: Ans = {\n var i, j = 0\n var ans = Ans(0, 0, 0)\n while(i < n) {\n j = i\n var p1, p2 = -1\n while(j < n && bal(j) >= minBal + 2) {\n if (s(j) == '(' && p1 == -1) p1 = j\n if (s(j) == ')') p2 = j\n j += 1\n }\n if (j < n && s(j) == ')') p2 = j\n debug(s\"$i $j $p1 $p2\")\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val cntNew = cumPlus2(p2) - cumPlus2(p1)\n ans = maxAns(ans, Ans(cntMin + cntNew, p1, p2))\n }\n i = j + 1\n }\n\n ans\n }\n\n def cntMinus1: Ans = {\n var i, j = 0\n var ans = Ans(0, 0, 0)\n while(i < n) {\n j = i\n var p1, p2 = -1\n while(j < n && bal(j) > minBal) {\n if (s(j) == '(' && p1 == -1) p1 = j\n if (s(j) == ')') p2 = j\n j += 1\n }\n if (j < n && s(j) == ')') p2 = j\n debug(s\"$i $j $p1 $p2\")\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val cntNew = cumPlus1(p2) - cumPlus1(p1)\n ans = maxAns(ans, Ans(cntNew, p1, p2))\n }\n i = j + 1\n }\n\n ans\n }\n\n def cntPlus1: Ans = {\n // min\u3092\u5168\u90e8\u6d88\u3059\n var p1, p2 = -1\n var ans = Ans(0, 0, 0)\n var i = bal.indexWhere(_ == minBal)\n while(i >= 0) {\n if (s(i) == ')' && p1 == -1) p1 = i\n i -= 1\n }\n var j = bal.lastIndexWhere(_ == minBal) + 1\n while(j < n) {\n if (s(j) == '(' && p2 == -1) p2 = j\n j += 1\n }\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val l = cumPlus1(p1)\n val r = cumPlus1.last - cumPlus1(p2)\n ans = maxAns(ans, Ans(l + r, p1, p2))\n }\n\n ans\n }\n\n def cntPlus2: Ans = {\n // min\u3068min+1\u3092\u5168\u90e8\u6d88\u3059\n var p1, p2 = -1\n var v = 0\n var i = bal.indexWhere(a => a == minBal || a == minBal + 1)\n while(i >= 0) {\n if (s(i) == ')' && p1 == -1) {\n val oldP2 = cumPlus2(i)\n val newP2 = cumMin.last - cumMin(i)\n if (v < oldP2 + newP2) {\n p1 = i\n v = oldP2 + newP2\n }\n }\n i -= 1\n }\n v = 0\n var j = bal.lastIndexWhere(a => a == minBal || a == minBal + 1) + 1\n while(j < n) {\n if (s(j) == '(' && p2 == -1) {\n val oldP2 = cumPlus2.last - cumPlus2(j)\n val newP2 = cumMin(j)\n if (v < oldP2 + newP2) {\n p2 = j\n v = oldP2 + newP2\n }\n }\n j += 1\n }\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val oldP2 = cumPlus2(p1) + cumPlus2.last - cumPlus2(p2)\n val newP2 = cumMin(p2) - cumMin(p1)\n Ans(oldP2 + newP2, p1, p2)\n } else {\n zero\n }\n }\n\n debug(s\"cntEq:$cntEq\")\n debug(s\"cntMinus1:$cntMinus1\")\n debug(s\"cntPlus1:$cntPlus1\")\n debug(s\"cntPlus2:$cntPlus2\")\n\n val ans = Seq(cntEq, cntMinus1, cntPlus1, cntPlus2).maxBy(_.num)\n show(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[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 Ans(num: Int, i: Int, j: Int)\n def maxAns(a1: Ans, a2: Ans) = if (a1.num >= a2.num) a1 else a2\n val zero = Ans(0, 0, 0)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val s = ns(n)\n val bal = Array.ofDim[Int](n)\n REP(n) { i =>\n if (i > 0) bal(i) = bal(i - 1)\n bal(i) += (if (s(i) == '(') 1 else -1)\n }\n val minBal = bal.min\n val cntMin = bal.count(_ == minBal)\n\n val cumMin, cumPlus1, cumPlus2 = Array.ofDim[Int](n + 1)\n REP(n) { i =>\n if (bal(i) == minBal) cumMin(i + 1) = 1\n if (bal(i) == minBal + 1) cumPlus1(i + 1) = 1\n if (bal(i) == minBal + 2) cumPlus2(i + 1) = 1\n }\n REP(n) { i =>\n cumMin(i + 1) += cumMin(i)\n cumPlus1(i + 1) += cumPlus1(i)\n cumPlus2(i + 1) += cumPlus2(i)\n }\n debug(bal)\n debug(cumMin)\n debug(cumPlus1)\n debug(cumPlus2)\n\n def show(ans: Ans): Unit = {\n out.println(ans.num)\n out.println(s\"${ans.i+1} ${ans.j+1}\")\n }\n\n if (bal.last != 0) {\n show(zero)\n return\n }\n\n def cntEq: Ans = {\n var i, j = 0\n var ans = Ans(0, 0, 0)\n while(i < n) {\n j = i\n var p1, p2 = -1\n while(j < n && bal(j) >= minBal + 2) {\n if (s(j) == '(' && p1 == -1) p1 = j\n if (s(j) == ')') p2 = j\n j += 1\n }\n if (j < n && s(j) == ')') p2 = j\n debug(s\"$i $j $p1 $p2\")\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val cntNew = cumPlus2(p2) - cumPlus2(p1)\n ans = maxAns(ans, Ans(cntMin + cntNew, p1, p2))\n }\n i = j + 1\n }\n\n ans\n }\n\n def cntMinus1: Ans = {\n var i, j = 0\n var ans = Ans(0, 0, 0)\n while(i < n) {\n j = i\n var p1, p2 = -1\n while(j < n && bal(j) > minBal) {\n if (s(j) == '(' && p1 == -1) p1 = j\n if (s(j) == ')') p2 = j\n j += 1\n }\n debug(s\"$i $j $p1 $p2\")\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val cntNew = cumPlus1(p2) - cumPlus1(p1)\n ans = maxAns(ans, Ans(cntNew, p1, p2))\n }\n i = j + 1\n }\n\n ans\n }\n\n def cntPlus1: Ans = {\n // min\u3092\u5168\u90e8\u6d88\u3059\n var p1, p2 = -1\n var ans = Ans(0, 0, 0)\n var i = bal.indexWhere(_ == minBal)\n while(i >= 0) {\n if (s(i) == ')' && p1 == -1) p1 = i\n i -= 1\n }\n var j = bal.lastIndexWhere(_ == minBal) + 1\n while(j < n) {\n if (s(j) == '(' && p2 == -1) p2 = j\n j += 1\n }\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val l = cumPlus1(p1)\n val r = cumPlus1.last - cumPlus1(p2)\n ans = maxAns(ans, Ans(l + r, p1, p2))\n }\n\n ans\n }\n\n def cntPlus2: Ans = {\n // min\u3068min+1\u3092\u5168\u90e8\u6d88\u3059\n var p1, p2 = -1\n var v = 0\n var i = bal.indexWhere(a => a == minBal || a == minBal + 1)\n while(i >= 0) {\n if (s(i) == ')' && p1 == -1) {\n val oldP2 = cumPlus2(i)\n val newP2 = cumMin.last - cumMin(i)\n if (v < oldP2 + newP2) {\n p1 = i\n v = oldP2 + newP2\n }\n }\n i -= 1\n }\n v = 0\n var j = bal.lastIndexWhere(a => a == minBal || a == minBal + 1) + 1\n while(j < n) {\n if (s(j) == '(' && p2 == -1) {\n val oldP2 = cumPlus2.last - cumPlus2(j)\n val newP2 = cumMin(j)\n if (v < oldP2 + newP2) {\n p2 = j\n v = oldP2 + newP2\n }\n }\n j += 1\n }\n if (p1 != -1 && p2 != -1 && p1 < p2) {\n val oldP2 = cumPlus2(p1) + cumPlus2.last - cumPlus2(p2)\n val newP2 = cumMin(p2) - cumMin(p1)\n Ans(oldP2 + newP2, p1, p2)\n } else {\n zero\n }\n }\n\n debug(s\"cntEq:$cntEq\")\n debug(s\"cntMinus1:$cntMinus1\")\n debug(s\"cntPlus1:$cntPlus1\")\n debug(s\"cntPlus2:$cntPlus2\")\n\n val ans = Seq(cntEq, cntMinus1, cntPlus1, cntPlus2).maxBy(_.num)\n show(ans)\n }\n}"}], "src_uid": "be820239276b5e1a346309f9dd21c5cb"} {"nl": {"description": "Graph constructive problems are back! This time the graph you are asked to build should match the following properties.The graph is connected if and only if there exists a path between every pair of vertices.The diameter (aka \"longest shortest path\") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.The degree of a vertex is the number of edges incident to it.Given a sequence of $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ construct a connected undirected graph of $$$n$$$ vertices such that: the graph contains no self-loops and no multiple edges; the degree $$$d_i$$$ of the $$$i$$$-th vertex doesn't exceed $$$a_i$$$ (i.e. $$$d_i \\le a_i$$$); the diameter of the graph is maximum possible. Output the resulting graph or report that no solution exists.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\le n \\le 500$$$) \u2014 the number of vertices in the graph. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n - 1$$$) \u2014 the upper limits to vertex degrees.", "output_spec": "Print \"NO\" if no graph can be constructed under the given conditions. Otherwise print \"YES\" and the diameter of the resulting graph in the first line. The second line should contain a single integer $$$m$$$ \u2014 the number of edges in the resulting graph. The $$$i$$$-th of the next $$$m$$$ lines should contain two integers $$$v_i, u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$v_i \\neq u_i$$$) \u2014 the description of the $$$i$$$-th edge. The graph should contain no multiple edges \u2014 for each pair $$$(x, y)$$$ you output, you should output no more pairs $$$(x, y)$$$ or $$$(y, x)$$$.", "sample_inputs": ["3\n2 2 2", "5\n1 4 1 1 1", "3\n1 1 1"], "sample_outputs": ["YES 2\n2\n1 2\n2 3", "YES 2\n4\n1 2\n3 2\n4 2\n5 2", "NO"], "notes": "NoteHere are the graphs for the first two example cases. Both have diameter of $$$2$$$. $$$d_1 = 1 \\le a_1 = 2$$$$$$d_2 = 2 \\le a_2 = 2$$$$$$d_3 = 1 \\le a_3 = 2$$$ $$$d_1 = 1 \\le a_1 = 1$$$$$$d_2 = 4 \\le a_2 = 4$$$$$$d_3 = 1 \\le a_3 = 1$$$$$$d_4 = 1 \\le a_4 = 1$$$ "}, "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 ms = 2 * (N - 1)\n if (A.sum < ms) {\n out.println(\"NO\")\n } else {\n val mxIx = A.zipWithIndex.maxBy(_._1)._2\n val mxIx2 = A.zipWithIndex.filterNot(_._2 == mxIx).maxBy(_._1)._2\n\n val ones = A.zipWithIndex.filter(_._1 == 1).map(_._2)\n val twos = A.zipWithIndex.filter(_._1 > 1).map(_._2)\n\n if (A(mxIx2) == 1) {\n out.println(s\"YES 2\")\n out.println(N - 1)\n ones.foreach { v =>\n val u = mxIx\n out.println(s\"${v+1} ${u+1}\")\n }\n } else {\n val d = twos.length - 1 + min(2, ones.length) // 1-2-2-2-1\n out.println(s\"YES $d\")\n out.println(N - 1)\n\n val others = twos.filterNot(v => v == mxIx || v == mxIx2)\n val sorted = mxIx +: others :+ mxIx2\n sorted zip sorted.drop(1) foreach { case (v, u) =>\n out.println(s\"${v+1} ${u+1}\")\n }\n\n twos.foreach(v => A(v) -= 2)\n val it = Iterator(mxIx, mxIx2) ++ (for {\n v <- twos.iterator\n _ <- Iterator.fill(A(v))(v)\n } yield v)\n\n ones.foreach { v =>\n val u = it.next()\n out.println(s\"${v+1} ${u+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[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 ms = 2 * (N - 1)\n if (A.sum < ms) {\n out.println(\"NO\")\n } else {\n val mxIx = A.zipWithIndex.maxBy(_._1)._2\n val mxIx2 = A.zipWithIndex.filterNot(_._2 == mxIx).maxBy(_._1)._2\n\n val ones = A.zipWithIndex.filter(_._1 == 1).map(_._2)\n val twos = A.zipWithIndex.filter(_._1 > 1).map(_._2)\n\n if (A(mxIx2) == 1) {\n out.println(s\"YES 2\")\n out.println(N - 1)\n ones.foreach { v =>\n val u = mxIx\n out.println(s\"${v+1} ${u+1}\")\n }\n } else {\n val d = twos.length - 1 + min(2, ones.length) // 1-2-2-2-1\n out.println(s\"YES $d\")\n out.println(N - 1)\n\n val others = twos.filterNot(v => v == mxIx || v == mxIx2)\n val sorted = mxIx +: others :+ mxIx2\n sorted zip sorted.drop(1) foreach { case (v, u) =>\n out.println(s\"${v+1} ${u+1}\")\n }\n\n A(mxIx) -= 1\n A(mxIx2) -= 1\n others.foreach(v => A(v) -= 2)\n val it = Iterator(mxIx, mxIx2) ++ (for {\n v <- twos.iterator\n _ <- Iterator.fill(A(v))(v)\n } yield v)\n\n ones.foreach { v =>\n val u = it.next()\n out.println(s\"${v+1} ${u+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[Int](as.length + 1)\n rep(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "69ee6170d9f1480647d1a3fed4d1f77b"} {"nl": {"description": "Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix\u2009+\u2009biy\u2009+\u2009ci\u2009=\u20090, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.", "input_spec": "The first line contains two space-separated integers x1, y1 (\u2009-\u2009106\u2009\u2264\u2009x1,\u2009y1\u2009\u2264\u2009106) \u2014 the coordinates of your home. The second line contains two integers separated by a space x2, y2 (\u2009-\u2009106\u2009\u2264\u2009x2,\u2009y2\u2009\u2264\u2009106) \u2014 the coordinates of the university you are studying at. The third line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300) \u2014 the number of roads in the city. The following n lines contain 3 space-separated integers (\u2009-\u2009106\u2009\u2264\u2009ai,\u2009bi,\u2009ci\u2009\u2264\u2009106; |ai|\u2009+\u2009|bi|\u2009>\u20090) \u2014 the coefficients of the line aix\u2009+\u2009biy\u2009+\u2009ci\u2009=\u20090, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).", "output_spec": "Output the answer to the problem.", "sample_inputs": ["1 1\n-1 -1\n2\n0 1 0\n1 0 0", "1 1\n-1 -1\n3\n1 0 0\n0 1 0\n1 1 -3"], "sample_outputs": ["2", "2"], "notes": "NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): "}, "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\u8ef8\u306b\u5e73\u884c\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}"}, {"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}"}], "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\u8ef8\u306b\u5e73\u884c\n if (b == 0) {\n val x = -c // \u672c\u5f53\u306f-c/a \u306a\u3093\u3060\u3051\u3069doule\u7cbe\u5ea6\u304c\u6016\u3044\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\u8ef8\u306b\u5e73\u884c\n if (b == 0) {\n val x = -c // \u672c\u5f53\u306f-c/a \u306a\u3093\u3060\u3051\u3069doule\u7cbe\u5ea6\u304c\u6016\u3044\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"} {"nl": {"description": "You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves: decrease $$$n$$$ by $$$1$$$; divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \\rightarrow 26 \\rightarrow 25 \\rightarrow 24 \\rightarrow 8 \\rightarrow 7 \\rightarrow 6 \\rightarrow 2 \\rightarrow 1 \\rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^{18}$$$, $$$2 \\le k \\le 10^{18}$$$).", "output_spec": "For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line. ", "sample_inputs": ["2\n59 3\n1000000000000000000 10"], "sample_outputs": ["8\n19"], "notes": "NoteSteps for the first test case are: $$$59 \\rightarrow 58 \\rightarrow 57 \\rightarrow 19 \\rightarrow 18 \\rightarrow 6 \\rightarrow 2 \\rightarrow 1 \\rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$."}, "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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "negative_code": [], "src_uid": "00b1e45e9395d23e850ce1a0751b8378"} {"nl": {"description": "Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of polygons in the market. Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \\le n_i \\le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon. ", "output_spec": "For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).", "sample_inputs": ["4\n3\n4\n12\n1000000000"], "sample_outputs": ["NO\nYES\nYES\nYES"], "notes": "NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well. "}, "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 if (Scanner.nextInt % 4 == 0) {\n println(\"YES\")\n } else {\n println(\"NO\")\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 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"} {"nl": {"description": "Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n uppercase letters without spaces \u2014 the i-th letter describes the i-th card of the Appleman.", "output_spec": "Print a single integer \u2013 the answer to the problem.", "sample_inputs": ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"], "sample_outputs": ["82", "4"], "notes": "NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin."}, "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": "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}"}, {"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"} {"nl": {"description": "Consider a conveyor belt represented using a grid consisting of $$$n$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row from the top and the $$$j$$$-th column from the left is labelled $$$(i,j)$$$. Every cell, except $$$(n,m)$$$, has a direction R (Right) or D (Down) assigned to it. If the cell $$$(i,j)$$$ is assigned direction R, any luggage kept on that will move to the cell $$$(i,j+1)$$$. Similarly, if the cell $$$(i,j)$$$ is assigned direction D, any luggage kept on that will move to the cell $$$(i+1,j)$$$. If at any moment, the luggage moves out of the grid, it is considered to be lost. There is a counter at the cell $$$(n,m)$$$ from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell $$$(i,j)$$$, any luggage placed in this cell should eventually end up in the cell $$$(n,m)$$$. This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 100$$$) \u00a0\u2014 the number of rows and columns, respectively. The following $$$n$$$ lines each contain $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line, $$$a_{i,j}$$$ is the initial direction of the cell $$$(i, j)$$$. Please note that $$$a_{n,m}=$$$ C.", "output_spec": "For each case, output in a new line the minimum number of cells that you have to change to make the conveyor belt functional. ", "sample_inputs": ["4\n3 3\nRRD\nDDR\nRRC\n1 4\nDDDC\n6 9\nRDDDDDRRR\nRRDDRRDDD\nRRDRDRRDR\nDDDDRDDRR\nDRRDRDDDR\nDDRDRRDDC\n1 1\nC"], "sample_outputs": ["1\n3\n9\n0"], "notes": "NoteIn the first case, just changing the direction of $$$(2,3)$$$ to D is enough.You can verify that the resulting belt is functional. For example, if we place any luggage at $$$(2,2)$$$, it first moves to $$$(3,2)$$$ and then to $$$(3,3)$$$. In the second case, we have no option but to change the first $$$3$$$ cells from D to R making the grid equal to RRRC."}, "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, m = nextInt\n val grid = Array.fill(n){nextLine}\n val res = grid.count(_(m - 1) == 'R') + grid.last.count(_ == 'D')\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": [], "src_uid": "409073ef839a7d0cdb900c06ee4a841c"} {"nl": {"description": "You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.", "input_spec": "The first line contains single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of integers. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print the maximum length of an increasing subarray of the given array.", "sample_inputs": ["5\n1 7 2 11 15", "6\n100 100 100 100 100 100", "3\n1 2 3"], "sample_outputs": ["3", "1", "3"], "notes": null}, "positive_code": [{"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"}, {"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": "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}"}], "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"} {"nl": {"description": "You are given an array of $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. After you watched the amazing film \"Everything Everywhere All At Once\", you came up with the following operation.In one operation, you choose $$$n-1$$$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array $$$[1, 2, 3, 1]$$$ we can get the array $$$[2, 2, 2, 1]$$$, if we choose the first three elements, or we can get the array $$$[\\frac{4}{3}, \\frac{4}{3}, 3, \\frac{4}{3}]$$$, if we choose all elements except the third.Is it possible to make all elements of the array equal by performing a finite number of such operations?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 50$$$) \u00a0\u2014 the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 100$$$).", "output_spec": "For each test case, if it is possible to make all elements equal after some number of operations, output $$$\\texttt{YES}$$$. Otherwise, output $$$\\texttt{NO}$$$. You can output $$$\\texttt{YES}$$$ and $$$\\texttt{NO}$$$ in any case (for example, strings $$$\\texttt{yEs}$$$, $$$\\texttt{yes}$$$, $$$\\texttt{Yes}$$$ will be recognized as a positive response).", "sample_inputs": ["4\n\n3\n\n42 42 42\n\n5\n\n1 2 3 4 5\n\n4\n\n4 3 2 1\n\n3\n\n24 2 22"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first test case, all elements are already equal.In the second test case, you can choose all elements except the third, their average is $$$\\frac{1 + 2 + 4 + 5}{4} = 3$$$, so the array will become $$$[3, 3, 3, 3, 3]$$$.It's possible to show that it's impossible to make all elements equal in the third and fourth test cases."}, "positive_code": [{"source_code": "// https://codeforces.com/contest/1686/problem/0\n//package round_794\n\nimport scala.io.StdIn\n\nobject task_A extends App {\n def solving(a: Array[Int], n: Int): String = {\n val avg = a.sum.toFloat / n\n var i = 0\n while (i < n && a(i) != avg) {\n i += 1\n }\n if (i == n) {\n \"NO\"\n }\n else {\n \"YES\"\n }\n }\n\n val t = StdIn.readLine().toInt\n var sb = new StringBuilder()\n for (i <- 0 until(t)) {\n val n = StdIn.readLine().toInt\n val a: Array[Int] = StdIn.readLine().split(\" \").map(x => x.toInt)\n sb.append(solving(a, n)).append(\"\\n\")\n }\n print(sb)\n\n}\n"}], "negative_code": [], "src_uid": "7785ed6f41dbd45f1a9432c2fb07d713"} {"nl": {"description": "Let's dive into one of the most interesting areas of magic \u2014 writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.Each spell consists of several lines. The line, whose first non-space character is character \"#\" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.", "input_spec": "The input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 (\u2009=\u2009220) bytes. Newlines are included in this size. In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one. It is guaranteed that the input contains at least one character other than a newline. It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means.", "output_spec": "Print the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline. Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter.", "sample_inputs": ["# include <cstdio>\n\nusing namespace std;\n\nint main ( ){\nputs(\"Hello # World\"); #\n#\n}", "#\n\n#"], "sample_outputs": ["# include <cstdio>\nusingnamespacestd;intmain(){puts(\"Hello#World\");#\n#\n}", "#\n\n#"], "notes": "NoteIn the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them.In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other. "}, "positive_code": [{"source_code": "object MinSpell {\n\n def main(args: Array[String]): Unit = {\n var sb = new StringBuilder() \n var s = readLine()\n var hasLines = false;\n while (s != null){\n if (s.trim().startsWith(\"#\")){\n if (hasLines) {\n print(\"%s\\n\".format(sb.toString()))\n sb.clear();\n hasLines = false;\n }\n print(\"%s\\n\".format(s))\n } else {\n hasLines = true;\n sb.append(s.replaceAll(\" |\\n\",\"\"));\n }\n s = readLine();\n }\n if (hasLines) {\n print(\"%s\\n\".format(sb.toString()))\n }\n }\n\n}"}], "negative_code": [{"source_code": "object MinSpell {\n\n def main(args: Array[String]): Unit = {\n var sb = new StringBuilder() \n var s = readLine()\n while (s != null){\n if (s.trim().startsWith(\"#\")){\n if (sb.length > 0) {\n print(\"%s\\n\".format(sb.toString()))\n sb.clear();\n }\n print(\"%s\\n\".format(s))\n } else {\n sb.append(s.replaceAll(\" |\\n\",\"\"));\n }\n s = readLine();\n }\n if (sb.length > 0) {\n print(\"%s\\n\".format(sb.toString()))\n }\n }\n\n}"}], "src_uid": "a16bb696858bc592c33dcf0fd99df197"} {"nl": {"description": "The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital \u2014 number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.", "input_spec": "The first input line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100, ) \u2014 the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1\u2009\u2264\u2009vi,\u2009ui\u2009\u2264\u2009n, vi\u2009\u2260\u2009ui) \u2014 the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space. It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.", "output_spec": "Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10\u2009-\u20096.", "sample_inputs": ["4 4\n1 2\n2 4\n1 3\n3 4", "11 14\n1 2\n1 3\n2 4\n3 4\n4 5\n4 6\n5 11\n6 11\n1 8\n8 9\n9 7\n11 7\n1 10\n10 4"], "sample_outputs": ["1.000000000000", "1.714285714286"], "notes": "NoteIn the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make .In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal ."}, "positive_code": [{"source_code": "import collection.mutable\nimport 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 def INT() = TOKEN().toInt\n\n val n = INT()\n val m = INT()\n val matrix = Array.ofDim[Boolean](n,n)\n for (i <- 1 to m) {\n val a = INT() - 1\n val b = INT() - 1\n matrix(a)(b) = true\n matrix(b)(a) = true\n }\n\n solve(matrix)\n\n def solve(matrix : Array[Array[Boolean]]) {\n val N = matrix.length\n\n def bfs(start:Int) : Array[Int] = {\n val dists = Array.fill(N)(Int.MaxValue/2)\n val visited = Array.fill(N)(false)\n val queue = new mutable.Queue[Int]()\n\n dists(start) = 0\n queue += start\n visited(start) = true\n\n while(!queue.isEmpty) {\n val next = queue.dequeue()\n for (neighbor <- (0 until N).filter(matrix(next)(_))) {\n if (!visited(neighbor)) {\n visited(neighbor) = true\n dists(neighbor) = math.min(dists(neighbor), dists(next) + 1)\n queue += neighbor\n }\n }\n }\n\n dists\n }\n\n val distsLeft = bfs(0)\n val distsRight = bfs(N-1)\n\n def countPaths(dists : Array[Int]) = {\n\n val start = dists.indexOf(0)\n val queue = new mutable.Queue[Int]()\n val found = Array.fill(N)(false)\n val paths = new Array[Long](N)\n\n queue.enqueue(start)\n paths(start) = 1\n\n while(!queue.isEmpty) {\n val next = queue.dequeue()\n for (i <- (0 until N).filter(x => matrix(next)(x) && dists(next) < dists(x))) {\n paths(i) += paths(next)\n if (!found(i)) {\n queue.enqueue(i)\n found(i) = true\n }\n }\n }\n\n paths\n }\n\n val pathsLeft = countPaths(distsLeft)\n val pathsRight = countPaths(distsRight)\n val paths = for(i <- (0 until N)) yield {\n if(distsLeft(i)+distsRight(i) == distsRight(0))\n pathsLeft(i) * pathsRight(i) * (if (i > 0 && i < N-1) 2 else 1)\n else\n 0\n }\n\n println(paths.max.toDouble / paths(N-1).toDouble)\n\n }\n\n}\n\n\n"}], "negative_code": [{"source_code": "import collection.mutable\nimport 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 def INT() = TOKEN().toInt\n\n val n = INT()\n val m = INT()\n val matrix = Array.ofDim[Boolean](n,n)\n for (i <- 1 to m) {\n val a = INT() - 1\n val b = INT() - 1\n matrix(a)(b) = true\n matrix(b)(a) = true\n }\n\n solve(matrix)\n\n def solve(matrix : Array[Array[Boolean]]) {\n val N = matrix.length\n\n def bfs(start:Int) : Array[Int] = {\n val dists = Array.fill(N)(Int.MaxValue/2)\n val visited = Array.fill(N)(false)\n val queue = new mutable.Queue[Int]()\n\n dists(start) = 0\n queue += start\n visited(start) = true\n\n while(!queue.isEmpty) {\n val next = queue.dequeue()\n for (neighbor <- (0 until N).filter(matrix(next)(_))) {\n if (!visited(neighbor)) {\n visited(neighbor) = true\n dists(neighbor) = math.min(dists(neighbor), dists(next) + 1)\n queue += neighbor\n }\n }\n }\n\n dists\n }\n\n val distsLeft = bfs(0)\n val distsRight = bfs(N-1)\n\n def countPaths(dists : Array[Int]) = {\n\n val start = dists.indexOf(0)\n val queue = new mutable.Queue[Int]()\n val found = Array.fill(N)(false)\n val paths = new Array[Int](N)\n\n queue.enqueue(start)\n paths(start) = 1\n\n while(!queue.isEmpty) {\n val next = queue.dequeue()\n for (i <- (0 until N).filter(x => matrix(next)(x) && dists(next) < dists(x))) {\n paths(i) += paths(next)\n if (!found(i)) {\n queue.enqueue(i)\n found(i) = true\n }\n }\n }\n\n paths\n }\n\n val pathsLeft = countPaths(distsLeft)\n val pathsRight = countPaths(distsRight)\n val paths = for(i <- (0 until N)) yield {\n if(distsLeft(i)+distsRight(i) == distsRight(0))\n pathsLeft(i) * pathsRight(i) * (if (i > 0 && i < N-1) 2 else 1)\n else\n 0\n }\n\n println(paths.max.toDouble / paths(N-1).toDouble)\n\n }\n\n}\n\n\n"}, {"source_code": "import collection.mutable\nimport 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 def INT() = TOKEN().toInt\n\n val n = INT()\n val m = INT()\n val matrix = Array.ofDim[Boolean](n,n)\n for (i <- 1 to m) {\n val a = INT() - 1\n val b = INT() - 1\n matrix(a)(b) = true\n matrix(b)(a) = true\n }\n\n solve(matrix);\n\n def solve(matrix : Array[Array[Boolean]]) = {\n val N = matrix.length\n\n def bfs(start:Int) : Array[Int] = {\n val dists = Array.fill(N)(Int.MaxValue/2)\n val visited = Array.fill(N)(false)\n val queue = new mutable.Queue[Int]()\n\n dists(start) = 0\n queue += start\n visited(start) = true\n\n while(!queue.isEmpty) {\n val next = queue.dequeue()\n for (neighbor <- (0 until N).filter(matrix(next)(_))) {\n if (!visited(neighbor)) {\n visited(neighbor) = true\n dists(neighbor) = math.min(dists(neighbor), dists(next) + 1)\n queue += neighbor\n }\n }\n }\n\n dists\n }\n\n val distsLeft = bfs(0);\n val distsRight = bfs(N-1);\n\n def countPaths(dists : Array[Int]) = {\n\n val start = dists.indexOf(0);\n val queue = new mutable.Queue[Int]();\n val found = Array.fill(N)(false);\n val paths = new Array[Int](N);\n\n queue.enqueue(start)\n paths(start) = 1\n\n while(!queue.isEmpty) {\n val next = queue.dequeue();\n for (i <- (0 until N).filter(x => matrix(next)(x) && dists(next) < dists(x))) {\n paths(i) += paths(next)\n if (!found(i)) {\n queue.enqueue(i)\n found(i) = true\n }\n }\n }\n\n paths\n }\n\n val pathsLeft = countPaths(distsLeft);\n val pathsRight = countPaths(distsRight);\n val paths = for(i <- (0 until N)) yield {\n pathsLeft(i) * pathsRight(i) * (if (i > 0 && i < N-1) 2 else 1);\n }\n\n println(paths.max.toDouble / paths(N-1).toDouble)\n\n }\n\n}\n\n\n"}], "src_uid": "a69b342ef5f6e11f7aa4fee71e149aa2"} {"nl": {"description": "The city where Mocha lives in is called Zhijiang. There are $$$n+1$$$ villages and $$$2n-1$$$ directed roads in this city. There are two kinds of roads: $$$n-1$$$ roads are from village $$$i$$$ to village $$$i+1$$$, for all $$$1\\leq i \\leq n-1$$$. $$$n$$$ roads can be described by a sequence $$$a_1,\\ldots,a_n$$$. If $$$a_i=0$$$, the $$$i$$$-th of these roads goes from village $$$i$$$ to village $$$n+1$$$, otherwise it goes from village $$$n+1$$$ to village $$$i$$$, for all $$$1\\leq i\\leq n$$$. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan? ", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 20$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$) \u2014 indicates that the number of villages is $$$n+1$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 1$$$). If $$$a_i=0$$$, it means that there is a road from village $$$i$$$ to village $$$n+1$$$. If $$$a_i=1$$$, it means that there is a road from village $$$n+1$$$ to village $$$i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case, print a line with $$$n+1$$$ integers, where the $$$i$$$-th number is the $$$i$$$-th village they will go through. If the answer doesn't exist, print $$$-1$$$. If there are multiple correct answers, you can print any one of them.", "sample_inputs": ["2\n3\n0 1 0\n3\n1 1 0"], "sample_outputs": ["1 4 2 3 \n4 1 2 3"], "notes": "NoteIn the first test case, the city looks like the following graph:So all possible answers are $$$(1 \\to 4 \\to 2 \\to 3)$$$, $$$(1 \\to 2 \\to 3 \\to 4)$$$.In the second test case, the city looks like the following graph:So all possible answers are $$$(4 \\to 1 \\to 2 \\to 3)$$$, $$$(1 \\to 2 \\to 3 \\to 4)$$$, $$$(3 \\to 4 \\to 1 \\to 2)$$$, $$$(2 \\to 3 \\to 4 \\to 1)$$$."}, "positive_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]): 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"}, {"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"} {"nl": {"description": "After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n\u2009=\u20093, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of digits in the cards Sherlock and Moriarty are going to use. The second line contains n digits\u00a0\u2014 Sherlock's credit card number. The third line contains n digits\u00a0\u2014 Moriarty's credit card number.", "output_spec": "First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty.", "sample_inputs": ["3\n123\n321", "2\n88\n00"], "sample_outputs": ["0\n2", "2\n0"], "notes": "NoteFirst sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks."}, "positive_code": [{"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 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 def run(s: Scanner, out: PrintWriter): Unit = {\n val n = s.nextLine().toInt\n\n val a = s.nextLine().map(_.toString.toInt)\n val b = s.nextLine().map(_.toString.toInt)\n\n var res = 0\n\n var set = new mutable.HashMap[Int, Int]()\n\n for (i <- 0 until n) {\n set.put(b(i), set.getOrElse(b(i), 0) + 1)\n }\n\n\n for (i <- 0 until n) {\n var min = Integer.MAX_VALUE\n\n set.foreach { case (x, c) => if (x >= a(i) && x < min && c > 0) {\n min = x\n }\n }\n\n if (min < Integer.MAX_VALUE) {\n set.put(min, set.getOrElse(min, 0) - 1)\n } else {\n res += 1\n min = set.filter { case (x, c) => c > 0 }.keySet.min\n set.put(min, set.getOrElse(min, 0) - 1)\n }\n }\n\n out.println(res)\n\n\n res = 0\n\n set = new mutable.HashMap[Int, Int]()\n\n for (i <- 0 until n) {\n set.put(b(i), set.getOrElse(b(i), 0) + 1)\n }\n\n for (i <- 0 until n) {\n var min = Integer.MAX_VALUE\n\n set.foreach { case (x, c) => if (x > a(i) && x < min && c > 0) {\n min = x\n }\n }\n\n if (min < Integer.MAX_VALUE) {\n set.put(min, set.getOrElse(min, 0) - 1)\n res += 1\n } else {\n min = set.filter { case (x, c) => c > 0 }.keySet.min\n set.put(min, set.getOrElse(min, 0) - 1)\n }\n }\n\n out.println(res)\n }\n}\n"}], "negative_code": [], "src_uid": "d1a35297090550d9a95f014b0c09a01a"} {"nl": {"description": "On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that 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. In other words, the value should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them.", "input_spec": "First and only line contains two space-separated integers n and a (3\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009a\u2009\u2264\u2009180)\u00a0\u2014 the number of vertices in the polygon and the needed angle, in degrees.", "output_spec": "Print three space-separated integers: the vertices v1, v2, v3, which form . If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.", "sample_inputs": ["3 15", "4 67", "4 68"], "sample_outputs": ["1 2 3", "2 1 3", "4 1 2"], "notes": "NoteIn first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45\u2009-\u200967|\u2009<\u2009|90\u2009-\u200967|. Other correct answers are: \"3 1 2\", \"3 2 4\", \"4 2 3\", \"4 3 1\", \"1 3 4\", \"1 4 2\", \"2 4 1\", \"4 1 3\", \"3 1 4\", \"3 4 2\", \"2 4 3\", \"2 3 1\", \"1 3 2\", \"1 2 4\", \"4 2 1\".In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90\u2009-\u200968|\u2009<\u2009|45\u2009-\u200968|. Other correct answers are: \"2 1 4\", \"3 2 1\", \"1 2 3\", \"4 3 2\", \"2 3 4\", \"1 4 3\", \"3 4 1\"."}, "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": "\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"}, {"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"} {"nl": {"description": "This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers \u2014 $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ \u2014 and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \\cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries.", "input_spec": null, "output_spec": null, "sample_inputs": ["16\n64\n345\n672"], "sample_outputs": ["? 1 1\n? 2 2\n? 3 5\n? 4 6\n! 4 8 15 16 23 42"], "notes": "NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character."}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1167 extends App {\n// val A = Array(4, 8, 15, 16, 23, 42)\n// def compute(xs: Array[Int]): String = {\n// val key = xs(0) * xs(1) + \",\" + xs(1) * xs(2) + \",\" + xs(2) * xs(3) + \",\" + xs(3) * xs(4)\n// s\"\"\"\"$key\" -> Array(${xs.mkString(\",\")})\"\"\"\n// }\n// val result = (A.permutations.map { xs =>\n// compute(xs)\n// }).toList\n\n// println(result.size)\n// println(result.mkString(\",\"))\n\n val M = Map(\n \"32,120,240,368\" -> Array(4,8,15,16,23,42),\"32,120,240,672\" -> Array(4,8,15,16,42,23),\"32,120,345,368\" -> Array(4,8,15,23,16,42),\"32,120,345,966\" -> Array(4,8,15,23,42,16),\"32,120,630,672\" -> Array(4,8,15,42,16,23),\"32,120,630,966\" -> Array(4,8,15,42,23,16),\"32,128,240,345\" -> Array(4,8,16,15,23,42),\"32,128,240,630\" -> Array(4,8,16,15,42,23),\"32,128,368,345\" -> Array(4,8,16,23,15,42),\"32,128,368,966\" -> Array(4,8,16,23,42,15),\"32,128,672,630\" -> Array(4,8,16,42,15,23),\"32,128,672,966\" -> Array(4,8,16,42,23,15),\"32,184,345,240\" -> Array(4,8,23,15,16,42),\"32,184,345,630\" -> Array(4,8,23,15,42,16),\"32,184,368,240\" -> Array(4,8,23,16,15,42),\"32,184,368,672\" -> Array(4,8,23,16,42,15),\"32,184,966,630\" -> Array(4,8,23,42,15,16),\"32,184,966,672\" -> Array(4,8,23,42,16,15),\"32,336,630,240\" -> Array(4,8,42,15,16,23),\"32,336,630,345\" -> Array(4,8,42,15,23,16),\"32,336,672,240\" -> Array(4,8,42,16,15,23),\"32,336,672,368\" -> Array(4,8,42,16,23,15),\"32,336,966,345\" -> Array(4,8,42,23,15,16),\"32,336,966,368\" -> Array(4,8,42,23,16,15),\"60,120,128,368\" -> Array(4,15,8,16,23,42),\"60,120,128,672\" -> Array(4,15,8,16,42,23),\"60,120,184,368\" -> Array(4,15,8,23,16,42),\"60,120,184,966\" -> Array(4,15,8,23,42,16),\"60,120,336,672\" -> Array(4,15,8,42,16,23),\"60,120,336,966\" -> Array(4,15,8,42,23,16),\"60,240,128,184\" -> Array(4,15,16,8,23,42),\"60,240,128,336\" -> Array(4,15,16,8,42,23),\"60,240,368,184\" -> Array(4,15,16,23,8,42),\"60,240,368,966\" -> Array(4,15,16,23,42,8),\"60,240,672,336\" -> Array(4,15,16,42,8,23),\"60,240,672,966\" -> Array(4,15,16,42,23,8),\"60,345,184,128\" -> Array(4,15,23,8,16,42),\"60,345,184,336\" -> Array(4,15,23,8,42,16),\"60,345,368,128\" -> Array(4,15,23,16,8,42),\"60,345,368,672\" -> Array(4,15,23,16,42,8),\"60,345,966,336\" -> Array(4,15,23,42,8,16),\"60,345,966,672\" -> Array(4,15,23,42,16,8),\"60,630,336,128\" -> Array(4,15,42,8,16,23),\"60,630,336,184\" -> Array(4,15,42,8,23,16),\"60,630,672,128\" -> Array(4,15,42,16,8,23),\"60,630,672,368\" -> Array(4,15,42,16,23,8),\"60,630,966,184\" -> Array(4,15,42,23,8,16),\"60,630,966,368\" -> Array(4,15,42,23,16,8),\"64,128,120,345\" -> Array(4,16,8,15,23,42),\"64,128,120,630\" -> Array(4,16,8,15,42,23),\"64,128,184,345\" -> Array(4,16,8,23,15,42),\"64,128,184,966\" -> Array(4,16,8,23,42,15),\"64,128,336,630\" -> Array(4,16,8,42,15,23),\"64,128,336,966\" -> Array(4,16,8,42,23,15),\"64,240,120,184\" -> Array(4,16,15,8,23,42),\"64,240,120,336\" -> Array(4,16,15,8,42,23),\"64,240,345,184\" -> Array(4,16,15,23,8,42),\"64,240,345,966\" -> Array(4,16,15,23,42,8),\"64,240,630,336\" -> Array(4,16,15,42,8,23),\"64,240,630,966\" -> Array(4,16,15,42,23,8),\"64,368,184,120\" -> Array(4,16,23,8,15,42),\"64,368,184,336\" -> Array(4,16,23,8,42,15),\"64,368,345,120\" -> Array(4,16,23,15,8,42),\"64,368,345,630\" -> Array(4,16,23,15,42,8),\"64,368,966,336\" -> Array(4,16,23,42,8,15),\"64,368,966,630\" -> Array(4,16,23,42,15,8),\"64,672,336,120\" -> Array(4,16,42,8,15,23),\"64,672,336,184\" -> Array(4,16,42,8,23,15),\"64,672,630,120\" -> Array(4,16,42,15,8,23),\"64,672,630,345\" -> Array(4,16,42,15,23,8),\"64,672,966,184\" -> Array(4,16,42,23,8,15),\"64,672,966,345\" -> Array(4,16,42,23,15,8),\"92,184,120,240\" -> Array(4,23,8,15,16,42),\"92,184,120,630\" -> Array(4,23,8,15,42,16),\"92,184,128,240\" -> Array(4,23,8,16,15,42),\"92,184,128,672\" -> Array(4,23,8,16,42,15),\"92,184,336,630\" -> Array(4,23,8,42,15,16),\"92,184,336,672\" -> Array(4,23,8,42,16,15),\"92,345,120,128\" -> Array(4,23,15,8,16,42),\"92,345,120,336\" -> Array(4,23,15,8,42,16),\"92,345,240,128\" -> Array(4,23,15,16,8,42),\"92,345,240,672\" -> Array(4,23,15,16,42,8),\"92,345,630,336\" -> Array(4,23,15,42,8,16),\"92,345,630,672\" -> Array(4,23,15,42,16,8),\"92,368,128,120\" -> Array(4,23,16,8,15,42),\"92,368,128,336\" -> Array(4,23,16,8,42,15),\"92,368,240,120\" -> Array(4,23,16,15,8,42),\"92,368,240,630\" -> Array(4,23,16,15,42,8),\"92,368,672,336\" -> Array(4,23,16,42,8,15),\"92,368,672,630\" -> Array(4,23,16,42,15,8),\"92,966,336,120\" -> Array(4,23,42,8,15,16),\"92,966,336,128\" -> Array(4,23,42,8,16,15),\"92,966,630,120\" -> Array(4,23,42,15,8,16),\"92,966,630,240\" -> Array(4,23,42,15,16,8),\"92,966,672,128\" -> Array(4,23,42,16,8,15),\"92,966,672,240\" -> Array(4,23,42,16,15,8),\"168,336,120,240\" -> Array(4,42,8,15,16,23),\"168,336,120,345\" -> Array(4,42,8,15,23,16),\"168,336,128,240\" -> Array(4,42,8,16,15,23),\"168,336,128,368\" -> Array(4,42,8,16,23,15),\"168,336,184,345\" -> Array(4,42,8,23,15,16),\"168,336,184,368\" -> Array(4,42,8,23,16,15),\"168,630,120,128\" -> Array(4,42,15,8,16,23),\"168,630,120,184\" -> Array(4,42,15,8,23,16),\"168,630,240,128\" -> Array(4,42,15,16,8,23),\"168,630,240,368\" -> Array(4,42,15,16,23,8),\"168,630,345,184\" -> Array(4,42,15,23,8,16),\"168,630,345,368\" -> Array(4,42,15,23,16,8),\"168,672,128,120\" -> Array(4,42,16,8,15,23),\"168,672,128,184\" -> Array(4,42,16,8,23,15),\"168,672,240,120\" -> Array(4,42,16,15,8,23),\"168,672,240,345\" -> Array(4,42,16,15,23,8),\"168,672,368,184\" -> Array(4,42,16,23,8,15),\"168,672,368,345\" -> Array(4,42,16,23,15,8),\"168,966,184,120\" -> Array(4,42,23,8,15,16),\"168,966,184,128\" -> Array(4,42,23,8,16,15),\"168,966,345,120\" -> Array(4,42,23,15,8,16),\"168,966,345,240\" -> Array(4,42,23,15,16,8),\"168,966,368,128\" -> Array(4,42,23,16,8,15),\"168,966,368,240\" -> Array(4,42,23,16,15,8),\"32,60,240,368\" -> Array(8,4,15,16,23,42),\"32,60,240,672\" -> Array(8,4,15,16,42,23),\"32,60,345,368\" -> Array(8,4,15,23,16,42),\"32,60,345,966\" -> Array(8,4,15,23,42,16),\"32,60,630,672\" -> Array(8,4,15,42,16,23),\"32,60,630,966\" -> Array(8,4,15,42,23,16),\"32,64,240,345\" -> Array(8,4,16,15,23,42),\"32,64,240,630\" -> Array(8,4,16,15,42,23),\"32,64,368,345\" -> Array(8,4,16,23,15,42),\"32,64,368,966\" -> Array(8,4,16,23,42,15),\"32,64,672,630\" -> Array(8,4,16,42,15,23),\"32,64,672,966\" -> Array(8,4,16,42,23,15),\"32,92,345,240\" -> Array(8,4,23,15,16,42),\"32,92,345,630\" -> Array(8,4,23,15,42,16),\"32,92,368,240\" -> Array(8,4,23,16,15,42),\"32,92,368,672\" -> Array(8,4,23,16,42,15),\"32,92,966,630\" -> Array(8,4,23,42,15,16),\"32,92,966,672\" -> Array(8,4,23,42,16,15),\"32,168,630,240\" -> Array(8,4,42,15,16,23),\"32,168,630,345\" -> Array(8,4,42,15,23,16),\"32,168,672,240\" -> Array(8,4,42,16,15,23),\"32,168,672,368\" -> Array(8,4,42,16,23,15),\"32,168,966,345\" -> Array(8,4,42,23,15,16),\"32,168,966,368\" -> Array(8,4,42,23,16,15),\"120,60,64,368\" -> Array(8,15,4,16,23,42),\"120,60,64,672\" -> Array(8,15,4,16,42,23),\"120,60,92,368\" -> Array(8,15,4,23,16,42),\"120,60,92,966\" -> Array(8,15,4,23,42,16),\"120,60,168,672\" -> Array(8,15,4,42,16,23),\"120,60,168,966\" -> Array(8,15,4,42,23,16),\"120,240,64,92\" -> Array(8,15,16,4,23,42),\"120,240,64,168\" -> Array(8,15,16,4,42,23),\"120,240,368,92\" -> Array(8,15,16,23,4,42),\"120,240,368,966\" -> Array(8,15,16,23,42,4),\"120,240,672,168\" -> Array(8,15,16,42,4,23),\"120,240,672,966\" -> Array(8,15,16,42,23,4),\"120,345,92,64\" -> Array(8,15,23,4,16,42),\"120,345,92,168\" -> Array(8,15,23,4,42,16),\"120,345,368,64\" -> Array(8,15,23,16,4,42),\"120,345,368,672\" -> Array(8,15,23,16,42,4),\"120,345,966,168\" -> Array(8,15,23,42,4,16),\"120,345,966,672\" -> Array(8,15,23,42,16,4),\"120,630,168,64\" -> Array(8,15,42,4,16,23),\"120,630,168,92\" -> Array(8,15,42,4,23,16),\"120,630,672,64\" -> Array(8,15,42,16,4,23),\"120,630,672,368\" -> Array(8,15,42,16,23,4),\"120,630,966,92\" -> Array(8,15,42,23,4,16),\"120,630,966,368\" -> Array(8,15,42,23,16,4),\"128,64,60,345\" -> Array(8,16,4,15,23,42),\"128,64,60,630\" -> Array(8,16,4,15,42,23),\"128,64,92,345\" -> Array(8,16,4,23,15,42),\"128,64,92,966\" -> Array(8,16,4,23,42,15),\"128,64,168,630\" -> Array(8,16,4,42,15,23),\"128,64,168,966\" -> Array(8,16,4,42,23,15),\"128,240,60,92\" -> Array(8,16,15,4,23,42),\"128,240,60,168\" -> Array(8,16,15,4,42,23),\"128,240,345,92\" -> Array(8,16,15,23,4,42),\"128,240,345,966\" -> Array(8,16,15,23,42,4),\"128,240,630,168\" -> Array(8,16,15,42,4,23),\"128,240,630,966\" -> Array(8,16,15,42,23,4),\"128,368,92,60\" -> Array(8,16,23,4,15,42),\"128,368,92,168\" -> Array(8,16,23,4,42,15),\"128,368,345,60\" -> Array(8,16,23,15,4,42),\"128,368,345,630\" -> Array(8,16,23,15,42,4),\"128,368,966,168\" -> Array(8,16,23,42,4,15),\"128,368,966,630\" -> Array(8,16,23,42,15,4),\"128,672,168,60\" -> Array(8,16,42,4,15,23),\"128,672,168,92\" -> Array(8,16,42,4,23,15),\"128,672,630,60\" -> Array(8,16,42,15,4,23),\"128,672,630,345\" -> Array(8,16,42,15,23,4),\"128,672,966,92\" -> Array(8,16,42,23,4,15),\"128,672,966,345\" -> Array(8,16,42,23,15,4),\"184,92,60,240\" -> Array(8,23,4,15,16,42),\"184,92,60,630\" -> Array(8,23,4,15,42,16),\"184,92,64,240\" -> Array(8,23,4,16,15,42),\"184,92,64,672\" -> Array(8,23,4,16,42,15),\"184,92,168,630\" -> Array(8,23,4,42,15,16),\"184,92,168,672\" -> Array(8,23,4,42,16,15),\"184,345,60,64\" -> Array(8,23,15,4,16,42),\"184,345,60,168\" -> Array(8,23,15,4,42,16),\"184,345,240,64\" -> Array(8,23,15,16,4,42),\"184,345,240,672\" -> Array(8,23,15,16,42,4),\"184,345,630,168\" -> Array(8,23,15,42,4,16),\"184,345,630,672\" -> Array(8,23,15,42,16,4),\"184,368,64,60\" -> Array(8,23,16,4,15,42),\"184,368,64,168\" -> Array(8,23,16,4,42,15),\"184,368,240,60\" -> Array(8,23,16,15,4,42),\"184,368,240,630\" -> Array(8,23,16,15,42,4),\"184,368,672,168\" -> Array(8,23,16,42,4,15),\"184,368,672,630\" -> Array(8,23,16,42,15,4),\"184,966,168,60\" -> Array(8,23,42,4,15,16),\"184,966,168,64\" -> Array(8,23,42,4,16,15),\"184,966,630,60\" -> Array(8,23,42,15,4,16),\"184,966,630,240\" -> Array(8,23,42,15,16,4),\"184,966,672,64\" -> Array(8,23,42,16,4,15),\"184,966,672,240\" -> Array(8,23,42,16,15,4),\"336,168,60,240\" -> Array(8,42,4,15,16,23),\"336,168,60,345\" -> Array(8,42,4,15,23,16),\"336,168,64,240\" -> Array(8,42,4,16,15,23),\"336,168,64,368\" -> Array(8,42,4,16,23,15),\"336,168,92,345\" -> Array(8,42,4,23,15,16),\"336,168,92,368\" -> Array(8,42,4,23,16,15),\"336,630,60,64\" -> Array(8,42,15,4,16,23),\"336,630,60,92\" -> Array(8,42,15,4,23,16),\"336,630,240,64\" -> Array(8,42,15,16,4,23),\"336,630,240,368\" -> Array(8,42,15,16,23,4),\"336,630,345,92\" -> Array(8,42,15,23,4,16),\"336,630,345,368\" -> Array(8,42,15,23,16,4),\"336,672,64,60\" -> Array(8,42,16,4,15,23),\"336,672,64,92\" -> Array(8,42,16,4,23,15),\"336,672,240,60\" -> Array(8,42,16,15,4,23),\"336,672,240,345\" -> Array(8,42,16,15,23,4),\"336,672,368,92\" -> Array(8,42,16,23,4,15),\"336,672,368,345\" -> Array(8,42,16,23,15,4),\"336,966,92,60\" -> Array(8,42,23,4,15,16),\"336,966,92,64\" -> Array(8,42,23,4,16,15),\"336,966,345,60\" -> Array(8,42,23,15,4,16),\"336,966,345,240\" -> Array(8,42,23,15,16,4),\"336,966,368,64\" -> Array(8,42,23,16,4,15),\"336,966,368,240\" -> Array(8,42,23,16,15,4),\"60,32,128,368\" -> Array(15,4,8,16,23,42),\"60,32,128,672\" -> Array(15,4,8,16,42,23),\"60,32,184,368\" -> Array(15,4,8,23,16,42),\"60,32,184,966\" -> Array(15,4,8,23,42,16),\"60,32,336,672\" -> Array(15,4,8,42,16,23),\"60,32,336,966\" -> Array(15,4,8,42,23,16),\"60,64,128,184\" -> Array(15,4,16,8,23,42),\"60,64,128,336\" -> Array(15,4,16,8,42,23),\"60,64,368,184\" -> Array(15,4,16,23,8,42),\"60,64,368,966\" -> Array(15,4,16,23,42,8),\"60,64,672,336\" -> Array(15,4,16,42,8,23),\"60,64,672,966\" -> Array(15,4,16,42,23,8),\"60,92,184,128\" -> Array(15,4,23,8,16,42),\"60,92,184,336\" -> Array(15,4,23,8,42,16),\"60,92,368,128\" -> Array(15,4,23,16,8,42),\"60,92,368,672\" -> Array(15,4,23,16,42,8),\"60,92,966,336\" -> Array(15,4,23,42,8,16),\"60,92,966,672\" -> Array(15,4,23,42,16,8),\"60,168,336,128\" -> Array(15,4,42,8,16,23),\"60,168,336,184\" -> Array(15,4,42,8,23,16),\"60,168,672,128\" -> Array(15,4,42,16,8,23),\"60,168,672,368\" -> Array(15,4,42,16,23,8),\"60,168,966,184\" -> Array(15,4,42,23,8,16),\"60,168,966,368\" -> Array(15,4,42,23,16,8),\"120,32,64,368\" -> Array(15,8,4,16,23,42),\"120,32,64,672\" -> Array(15,8,4,16,42,23),\"120,32,92,368\" -> Array(15,8,4,23,16,42),\"120,32,92,966\" -> Array(15,8,4,23,42,16),\"120,32,168,672\" -> Array(15,8,4,42,16,23),\"120,32,168,966\" -> Array(15,8,4,42,23,16),\"120,128,64,92\" -> Array(15,8,16,4,23,42),\"120,128,64,168\" -> Array(15,8,16,4,42,23),\"120,128,368,92\" -> Array(15,8,16,23,4,42),\"120,128,368,966\" -> Array(15,8,16,23,42,4),\"120,128,672,168\" -> Array(15,8,16,42,4,23),\"120,128,672,966\" -> Array(15,8,16,42,23,4),\"120,184,92,64\" -> Array(15,8,23,4,16,42),\"120,184,92,168\" -> Array(15,8,23,4,42,16),\"120,184,368,64\" -> Array(15,8,23,16,4,42),\"120,184,368,672\" -> Array(15,8,23,16,42,4),\"120,184,966,168\" -> Array(15,8,23,42,4,16),\"120,184,966,672\" -> Array(15,8,23,42,16,4),\"120,336,168,64\" -> Array(15,8,42,4,16,23),\"120,336,168,92\" -> Array(15,8,42,4,23,16),\"120,336,672,64\" -> Array(15,8,42,16,4,23),\"120,336,672,368\" -> Array(15,8,42,16,23,4),\"120,336,966,92\" -> Array(15,8,42,23,4,16),\"120,336,966,368\" -> Array(15,8,42,23,16,4),\"240,64,32,184\" -> Array(15,16,4,8,23,42),\"240,64,32,336\" -> Array(15,16,4,8,42,23),\"240,64,92,184\" -> Array(15,16,4,23,8,42),\"240,64,92,966\" -> Array(15,16,4,23,42,8),\"240,64,168,336\" -> Array(15,16,4,42,8,23),\"240,64,168,966\" -> Array(15,16,4,42,23,8),\"240,128,32,92\" -> Array(15,16,8,4,23,42),\"240,128,32,168\" -> Array(15,16,8,4,42,23),\"240,128,184,92\" -> Array(15,16,8,23,4,42),\"240,128,184,966\" -> Array(15,16,8,23,42,4),\"240,128,336,168\" -> Array(15,16,8,42,4,23),\"240,128,336,966\" -> Array(15,16,8,42,23,4),\"240,368,92,32\" -> Array(15,16,23,4,8,42),\"240,368,92,168\" -> Array(15,16,23,4,42,8),\"240,368,184,32\" -> Array(15,16,23,8,4,42),\"240,368,184,336\" -> Array(15,16,23,8,42,4),\"240,368,966,168\" -> Array(15,16,23,42,4,8),\"240,368,966,336\" -> Array(15,16,23,42,8,4),\"240,672,168,32\" -> Array(15,16,42,4,8,23),\"240,672,168,92\" -> Array(15,16,42,4,23,8),\"240,672,336,32\" -> Array(15,16,42,8,4,23),\"240,672,336,184\" -> Array(15,16,42,8,23,4),\"240,672,966,92\" -> Array(15,16,42,23,4,8),\"240,672,966,184\" -> Array(15,16,42,23,8,4),\"345,92,32,128\" -> Array(15,23,4,8,16,42),\"345,92,32,336\" -> Array(15,23,4,8,42,16),\"345,92,64,128\" -> Array(15,23,4,16,8,42),\"345,92,64,672\" -> Array(15,23,4,16,42,8),\"345,92,168,336\" -> Array(15,23,4,42,8,16),\"345,92,168,672\" -> Array(15,23,4,42,16,8),\"345,184,32,64\" -> Array(15,23,8,4,16,42),\"345,184,32,168\" -> Array(15,23,8,4,42,16),\"345,184,128,64\" -> Array(15,23,8,16,4,42),\"345,184,128,672\" -> Array(15,23,8,16,42,4),\"345,184,336,168\" -> Array(15,23,8,42,4,16),\"345,184,336,672\" -> Array(15,23,8,42,16,4),\"345,368,64,32\" -> Array(15,23,16,4,8,42),\"345,368,64,168\" -> Array(15,23,16,4,42,8),\"345,368,128,32\" -> Array(15,23,16,8,4,42),\"345,368,128,336\" -> Array(15,23,16,8,42,4),\"345,368,672,168\" -> Array(15,23,16,42,4,8),\"345,368,672,336\" -> Array(15,23,16,42,8,4),\"345,966,168,32\" -> Array(15,23,42,4,8,16),\"345,966,168,64\" -> Array(15,23,42,4,16,8),\"345,966,336,32\" -> Array(15,23,42,8,4,16),\"345,966,336,128\" -> Array(15,23,42,8,16,4),\"345,966,672,64\" -> Array(15,23,42,16,4,8),\"345,966,672,128\" -> Array(15,23,42,16,8,4),\"630,168,32,128\" -> Array(15,42,4,8,16,23),\"630,168,32,184\" -> Array(15,42,4,8,23,16),\"630,168,64,128\" -> Array(15,42,4,16,8,23),\"630,168,64,368\" -> Array(15,42,4,16,23,8),\"630,168,92,184\" -> Array(15,42,4,23,8,16),\"630,168,92,368\" -> Array(15,42,4,23,16,8),\"630,336,32,64\" -> Array(15,42,8,4,16,23),\"630,336,32,92\" -> Array(15,42,8,4,23,16),\"630,336,128,64\" -> Array(15,42,8,16,4,23),\"630,336,128,368\" -> Array(15,42,8,16,23,4),\"630,336,184,92\" -> Array(15,42,8,23,4,16),\"630,336,184,368\" -> Array(15,42,8,23,16,4),\"630,672,64,32\" -> Array(15,42,16,4,8,23),\"630,672,64,92\" -> Array(15,42,16,4,23,8),\"630,672,128,32\" -> Array(15,42,16,8,4,23),\"630,672,128,184\" -> Array(15,42,16,8,23,4),\"630,672,368,92\" -> Array(15,42,16,23,4,8),\"630,672,368,184\" -> Array(15,42,16,23,8,4),\"630,966,92,32\" -> Array(15,42,23,4,8,16),\"630,966,92,64\" -> Array(15,42,23,4,16,8),\"630,966,184,32\" -> Array(15,42,23,8,4,16),\"630,966,184,128\" -> Array(15,42,23,8,16,4),\"630,966,368,64\" -> Array(15,42,23,16,4,8),\"630,966,368,128\" -> Array(15,42,23,16,8,4),\"64,32,120,345\" -> Array(16,4,8,15,23,42),\"64,32,120,630\" -> Array(16,4,8,15,42,23),\"64,32,184,345\" -> Array(16,4,8,23,15,42),\"64,32,184,966\" -> Array(16,4,8,23,42,15),\"64,32,336,630\" -> Array(16,4,8,42,15,23),\"64,32,336,966\" -> Array(16,4,8,42,23,15),\"64,60,120,184\" -> Array(16,4,15,8,23,42),\"64,60,120,336\" -> Array(16,4,15,8,42,23),\"64,60,345,184\" -> Array(16,4,15,23,8,42),\"64,60,345,966\" -> Array(16,4,15,23,42,8),\"64,60,630,336\" -> Array(16,4,15,42,8,23),\"64,60,630,966\" -> Array(16,4,15,42,23,8),\"64,92,184,120\" -> Array(16,4,23,8,15,42),\"64,92,184,336\" -> Array(16,4,23,8,42,15),\"64,92,345,120\" -> Array(16,4,23,15,8,42),\"64,92,345,630\" -> Array(16,4,23,15,42,8),\"64,92,966,336\" -> Array(16,4,23,42,8,15),\"64,92,966,630\" -> Array(16,4,23,42,15,8),\"64,168,336,120\" -> Array(16,4,42,8,15,23),\"64,168,336,184\" -> Array(16,4,42,8,23,15),\"64,168,630,120\" -> Array(16,4,42,15,8,23),\"64,168,630,345\" -> Array(16,4,42,15,23,8),\"64,168,966,184\" -> Array(16,4,42,23,8,15),\"64,168,966,345\" -> Array(16,4,42,23,15,8),\"128,32,60,345\" -> Array(16,8,4,15,23,42),\"128,32,60,630\" -> Array(16,8,4,15,42,23),\"128,32,92,345\" -> Array(16,8,4,23,15,42),\"128,32,92,966\" -> Array(16,8,4,23,42,15),\"128,32,168,630\" -> Array(16,8,4,42,15,23),\"128,32,168,966\" -> Array(16,8,4,42,23,15),\"128,120,60,92\" -> Array(16,8,15,4,23,42),\"128,120,60,168\" -> Array(16,8,15,4,42,23),\"128,120,345,92\" -> Array(16,8,15,23,4,42),\"128,120,345,966\" -> Array(16,8,15,23,42,4),\"128,120,630,168\" -> Array(16,8,15,42,4,23),\"128,120,630,966\" -> Array(16,8,15,42,23,4),\"128,184,92,60\" -> Array(16,8,23,4,15,42),\"128,184,92,168\" -> Array(16,8,23,4,42,15),\"128,184,345,60\" -> Array(16,8,23,15,4,42),\"128,184,345,630\" -> Array(16,8,23,15,42,4),\"128,184,966,168\" -> Array(16,8,23,42,4,15),\"128,184,966,630\" -> Array(16,8,23,42,15,4),\"128,336,168,60\" -> Array(16,8,42,4,15,23),\"128,336,168,92\" -> Array(16,8,42,4,23,15),\"128,336,630,60\" -> Array(16,8,42,15,4,23),\"128,336,630,345\" -> Array(16,8,42,15,23,4),\"128,336,966,92\" -> Array(16,8,42,23,4,15),\"128,336,966,345\" -> Array(16,8,42,23,15,4),\"240,60,32,184\" -> Array(16,15,4,8,23,42),\"240,60,32,336\" -> Array(16,15,4,8,42,23),\"240,60,92,184\" -> Array(16,15,4,23,8,42),\"240,60,92,966\" -> Array(16,15,4,23,42,8),\"240,60,168,336\" -> Array(16,15,4,42,8,23),\"240,60,168,966\" -> Array(16,15,4,42,23,8),\"240,120,32,92\" -> Array(16,15,8,4,23,42),\"240,120,32,168\" -> Array(16,15,8,4,42,23),\"240,120,184,92\" -> Array(16,15,8,23,4,42),\"240,120,184,966\" -> Array(16,15,8,23,42,4),\"240,120,336,168\" -> Array(16,15,8,42,4,23),\"240,120,336,966\" -> Array(16,15,8,42,23,4),\"240,345,92,32\" -> Array(16,15,23,4,8,42),\"240,345,92,168\" -> Array(16,15,23,4,42,8),\"240,345,184,32\" -> Array(16,15,23,8,4,42),\"240,345,184,336\" -> Array(16,15,23,8,42,4),\"240,345,966,168\" -> Array(16,15,23,42,4,8),\"240,345,966,336\" -> Array(16,15,23,42,8,4),\"240,630,168,32\" -> Array(16,15,42,4,8,23),\"240,630,168,92\" -> Array(16,15,42,4,23,8),\"240,630,336,32\" -> Array(16,15,42,8,4,23),\"240,630,336,184\" -> Array(16,15,42,8,23,4),\"240,630,966,92\" -> Array(16,15,42,23,4,8),\"240,630,966,184\" -> Array(16,15,42,23,8,4),\"368,92,32,120\" -> Array(16,23,4,8,15,42),\"368,92,32,336\" -> Array(16,23,4,8,42,15),\"368,92,60,120\" -> Array(16,23,4,15,8,42),\"368,92,60,630\" -> Array(16,23,4,15,42,8),\"368,92,168,336\" -> Array(16,23,4,42,8,15),\"368,92,168,630\" -> Array(16,23,4,42,15,8),\"368,184,32,60\" -> Array(16,23,8,4,15,42),\"368,184,32,168\" -> Array(16,23,8,4,42,15),\"368,184,120,60\" -> Array(16,23,8,15,4,42),\"368,184,120,630\" -> Array(16,23,8,15,42,4),\"368,184,336,168\" -> Array(16,23,8,42,4,15),\"368,184,336,630\" -> Array(16,23,8,42,15,4),\"368,345,60,32\" -> Array(16,23,15,4,8,42),\"368,345,60,168\" -> Array(16,23,15,4,42,8),\"368,345,120,32\" -> Array(16,23,15,8,4,42),\"368,345,120,336\" -> Array(16,23,15,8,42,4),\"368,345,630,168\" -> Array(16,23,15,42,4,8),\"368,345,630,336\" -> Array(16,23,15,42,8,4),\"368,966,168,32\" -> Array(16,23,42,4,8,15),\"368,966,168,60\" -> Array(16,23,42,4,15,8),\"368,966,336,32\" -> Array(16,23,42,8,4,15),\"368,966,336,120\" -> Array(16,23,42,8,15,4),\"368,966,630,60\" -> Array(16,23,42,15,4,8),\"368,966,630,120\" -> Array(16,23,42,15,8,4),\"672,168,32,120\" -> Array(16,42,4,8,15,23),\"672,168,32,184\" -> Array(16,42,4,8,23,15),\"672,168,60,120\" -> Array(16,42,4,15,8,23),\"672,168,60,345\" -> Array(16,42,4,15,23,8),\"672,168,92,184\" -> Array(16,42,4,23,8,15),\"672,168,92,345\" -> Array(16,42,4,23,15,8),\"672,336,32,60\" -> Array(16,42,8,4,15,23),\"672,336,32,92\" -> Array(16,42,8,4,23,15),\"672,336,120,60\" -> Array(16,42,8,15,4,23),\"672,336,120,345\" -> Array(16,42,8,15,23,4),\"672,336,184,92\" -> Array(16,42,8,23,4,15),\"672,336,184,345\" -> Array(16,42,8,23,15,4),\"672,630,60,32\" -> Array(16,42,15,4,8,23),\"672,630,60,92\" -> Array(16,42,15,4,23,8),\"672,630,120,32\" -> Array(16,42,15,8,4,23),\"672,630,120,184\" -> Array(16,42,15,8,23,4),\"672,630,345,92\" -> Array(16,42,15,23,4,8),\"672,630,345,184\" -> Array(16,42,15,23,8,4),\"672,966,92,32\" -> Array(16,42,23,4,8,15),\"672,966,92,60\" -> Array(16,42,23,4,15,8),\"672,966,184,32\" -> Array(16,42,23,8,4,15),\"672,966,184,120\" -> Array(16,42,23,8,15,4),\"672,966,345,60\" -> Array(16,42,23,15,4,8),\"672,966,345,120\" -> Array(16,42,23,15,8,4),\"92,32,120,240\" -> Array(23,4,8,15,16,42),\"92,32,120,630\" -> Array(23,4,8,15,42,16),\"92,32,128,240\" -> Array(23,4,8,16,15,42),\"92,32,128,672\" -> Array(23,4,8,16,42,15),\"92,32,336,630\" -> Array(23,4,8,42,15,16),\"92,32,336,672\" -> Array(23,4,8,42,16,15),\"92,60,120,128\" -> Array(23,4,15,8,16,42),\"92,60,120,336\" -> Array(23,4,15,8,42,16),\"92,60,240,128\" -> Array(23,4,15,16,8,42),\"92,60,240,672\" -> Array(23,4,15,16,42,8),\"92,60,630,336\" -> Array(23,4,15,42,8,16),\"92,60,630,672\" -> Array(23,4,15,42,16,8),\"92,64,128,120\" -> Array(23,4,16,8,15,42),\"92,64,128,336\" -> Array(23,4,16,8,42,15),\"92,64,240,120\" -> Array(23,4,16,15,8,42),\"92,64,240,630\" -> Array(23,4,16,15,42,8),\"92,64,672,336\" -> Array(23,4,16,42,8,15),\"92,64,672,630\" -> Array(23,4,16,42,15,8),\"92,168,336,120\" -> Array(23,4,42,8,15,16),\"92,168,336,128\" -> Array(23,4,42,8,16,15),\"92,168,630,120\" -> Array(23,4,42,15,8,16),\"92,168,630,240\" -> Array(23,4,42,15,16,8),\"92,168,672,128\" -> Array(23,4,42,16,8,15),\"92,168,672,240\" -> Array(23,4,42,16,15,8),\"184,32,60,240\" -> Array(23,8,4,15,16,42),\"184,32,60,630\" -> Array(23,8,4,15,42,16),\"184,32,64,240\" -> Array(23,8,4,16,15,42),\"184,32,64,672\" -> Array(23,8,4,16,42,15),\"184,32,168,630\" -> Array(23,8,4,42,15,16),\"184,32,168,672\" -> Array(23,8,4,42,16,15),\"184,120,60,64\" -> Array(23,8,15,4,16,42),\"184,120,60,168\" -> Array(23,8,15,4,42,16),\"184,120,240,64\" -> Array(23,8,15,16,4,42),\"184,120,240,672\" -> Array(23,8,15,16,42,4),\"184,120,630,168\" -> Array(23,8,15,42,4,16),\"184,120,630,672\" -> Array(23,8,15,42,16,4),\"184,128,64,60\" -> Array(23,8,16,4,15,42),\"184,128,64,168\" -> Array(23,8,16,4,42,15),\"184,128,240,60\" -> Array(23,8,16,15,4,42),\"184,128,240,630\" -> Array(23,8,16,15,42,4),\"184,128,672,168\" -> Array(23,8,16,42,4,15),\"184,128,672,630\" -> Array(23,8,16,42,15,4),\"184,336,168,60\" -> Array(23,8,42,4,15,16),\"184,336,168,64\" -> Array(23,8,42,4,16,15),\"184,336,630,60\" -> Array(23,8,42,15,4,16),\"184,336,630,240\" -> Array(23,8,42,15,16,4),\"184,336,672,64\" -> Array(23,8,42,16,4,15),\"184,336,672,240\" -> Array(23,8,42,16,15,4),\"345,60,32,128\" -> Array(23,15,4,8,16,42),\"345,60,32,336\" -> Array(23,15,4,8,42,16),\"345,60,64,128\" -> Array(23,15,4,16,8,42),\"345,60,64,672\" -> Array(23,15,4,16,42,8),\"345,60,168,336\" -> Array(23,15,4,42,8,16),\"345,60,168,672\" -> Array(23,15,4,42,16,8),\"345,120,32,64\" -> Array(23,15,8,4,16,42),\"345,120,32,168\" -> Array(23,15,8,4,42,16),\"345,120,128,64\" -> Array(23,15,8,16,4,42),\"345,120,128,672\" -> Array(23,15,8,16,42,4),\"345,120,336,168\" -> Array(23,15,8,42,4,16),\"345,120,336,672\" -> Array(23,15,8,42,16,4),\"345,240,64,32\" -> Array(23,15,16,4,8,42),\"345,240,64,168\" -> Array(23,15,16,4,42,8),\"345,240,128,32\" -> Array(23,15,16,8,4,42),\"345,240,128,336\" -> Array(23,15,16,8,42,4),\"345,240,672,168\" -> Array(23,15,16,42,4,8),\"345,240,672,336\" -> Array(23,15,16,42,8,4),\"345,630,168,32\" -> Array(23,15,42,4,8,16),\"345,630,168,64\" -> Array(23,15,42,4,16,8),\"345,630,336,32\" -> Array(23,15,42,8,4,16),\"345,630,336,128\" -> Array(23,15,42,8,16,4),\"345,630,672,64\" -> Array(23,15,42,16,4,8),\"345,630,672,128\" -> Array(23,15,42,16,8,4),\"368,64,32,120\" -> Array(23,16,4,8,15,42),\"368,64,32,336\" -> Array(23,16,4,8,42,15),\"368,64,60,120\" -> Array(23,16,4,15,8,42),\"368,64,60,630\" -> Array(23,16,4,15,42,8),\"368,64,168,336\" -> Array(23,16,4,42,8,15),\"368,64,168,630\" -> Array(23,16,4,42,15,8),\"368,128,32,60\" -> Array(23,16,8,4,15,42),\"368,128,32,168\" -> Array(23,16,8,4,42,15),\"368,128,120,60\" -> Array(23,16,8,15,4,42),\"368,128,120,630\" -> Array(23,16,8,15,42,4),\"368,128,336,168\" -> Array(23,16,8,42,4,15),\"368,128,336,630\" -> Array(23,16,8,42,15,4),\"368,240,60,32\" -> Array(23,16,15,4,8,42),\"368,240,60,168\" -> Array(23,16,15,4,42,8),\"368,240,120,32\" -> Array(23,16,15,8,4,42),\"368,240,120,336\" -> Array(23,16,15,8,42,4),\"368,240,630,168\" -> Array(23,16,15,42,4,8),\"368,240,630,336\" -> Array(23,16,15,42,8,4),\"368,672,168,32\" -> Array(23,16,42,4,8,15),\"368,672,168,60\" -> Array(23,16,42,4,15,8),\"368,672,336,32\" -> Array(23,16,42,8,4,15),\"368,672,336,120\" -> Array(23,16,42,8,15,4),\"368,672,630,60\" -> Array(23,16,42,15,4,8),\"368,672,630,120\" -> Array(23,16,42,15,8,4),\"966,168,32,120\" -> Array(23,42,4,8,15,16),\"966,168,32,128\" -> Array(23,42,4,8,16,15),\"966,168,60,120\" -> Array(23,42,4,15,8,16),\"966,168,60,240\" -> Array(23,42,4,15,16,8),\"966,168,64,128\" -> Array(23,42,4,16,8,15),\"966,168,64,240\" -> Array(23,42,4,16,15,8),\"966,336,32,60\" -> Array(23,42,8,4,15,16),\"966,336,32,64\" -> Array(23,42,8,4,16,15),\"966,336,120,60\" -> Array(23,42,8,15,4,16),\"966,336,120,240\" -> Array(23,42,8,15,16,4),\"966,336,128,64\" -> Array(23,42,8,16,4,15),\"966,336,128,240\" -> Array(23,42,8,16,15,4),\"966,630,60,32\" -> Array(23,42,15,4,8,16),\"966,630,60,64\" -> Array(23,42,15,4,16,8),\"966,630,120,32\" -> Array(23,42,15,8,4,16),\"966,630,120,128\" -> Array(23,42,15,8,16,4),\"966,630,240,64\" -> Array(23,42,15,16,4,8),\"966,630,240,128\" -> Array(23,42,15,16,8,4),\"966,672,64,32\" -> Array(23,42,16,4,8,15),\"966,672,64,60\" -> Array(23,42,16,4,15,8),\"966,672,128,32\" -> Array(23,42,16,8,4,15),\"966,672,128,120\" -> Array(23,42,16,8,15,4),\"966,672,240,60\" -> Array(23,42,16,15,4,8),\"966,672,240,120\" -> Array(23,42,16,15,8,4),\"168,32,120,240\" -> Array(42,4,8,15,16,23),\"168,32,120,345\" -> Array(42,4,8,15,23,16),\"168,32,128,240\" -> Array(42,4,8,16,15,23),\"168,32,128,368\" -> Array(42,4,8,16,23,15),\"168,32,184,345\" -> Array(42,4,8,23,15,16),\"168,32,184,368\" -> Array(42,4,8,23,16,15),\"168,60,120,128\" -> Array(42,4,15,8,16,23),\"168,60,120,184\" -> Array(42,4,15,8,23,16),\"168,60,240,128\" -> Array(42,4,15,16,8,23),\"168,60,240,368\" -> Array(42,4,15,16,23,8),\"168,60,345,184\" -> Array(42,4,15,23,8,16),\"168,60,345,368\" -> Array(42,4,15,23,16,8),\"168,64,128,120\" -> Array(42,4,16,8,15,23),\"168,64,128,184\" -> Array(42,4,16,8,23,15),\"168,64,240,120\" -> Array(42,4,16,15,8,23),\"168,64,240,345\" -> Array(42,4,16,15,23,8),\"168,64,368,184\" -> Array(42,4,16,23,8,15),\"168,64,368,345\" -> Array(42,4,16,23,15,8),\"168,92,184,120\" -> Array(42,4,23,8,15,16),\"168,92,184,128\" -> Array(42,4,23,8,16,15),\"168,92,345,120\" -> Array(42,4,23,15,8,16),\"168,92,345,240\" -> Array(42,4,23,15,16,8),\"168,92,368,128\" -> Array(42,4,23,16,8,15),\"168,92,368,240\" -> Array(42,4,23,16,15,8),\"336,32,60,240\" -> Array(42,8,4,15,16,23),\"336,32,60,345\" -> Array(42,8,4,15,23,16),\"336,32,64,240\" -> Array(42,8,4,16,15,23),\"336,32,64,368\" -> Array(42,8,4,16,23,15),\"336,32,92,345\" -> Array(42,8,4,23,15,16),\"336,32,92,368\" -> Array(42,8,4,23,16,15),\"336,120,60,64\" -> Array(42,8,15,4,16,23),\"336,120,60,92\" -> Array(42,8,15,4,23,16),\"336,120,240,64\" -> Array(42,8,15,16,4,23),\"336,120,240,368\" -> Array(42,8,15,16,23,4),\"336,120,345,92\" -> Array(42,8,15,23,4,16),\"336,120,345,368\" -> Array(42,8,15,23,16,4),\"336,128,64,60\" -> Array(42,8,16,4,15,23),\"336,128,64,92\" -> Array(42,8,16,4,23,15),\"336,128,240,60\" -> Array(42,8,16,15,4,23),\"336,128,240,345\" -> Array(42,8,16,15,23,4),\"336,128,368,92\" -> Array(42,8,16,23,4,15),\"336,128,368,345\" -> Array(42,8,16,23,15,4),\"336,184,92,60\" -> Array(42,8,23,4,15,16),\"336,184,92,64\" -> Array(42,8,23,4,16,15),\"336,184,345,60\" -> Array(42,8,23,15,4,16),\"336,184,345,240\" -> Array(42,8,23,15,16,4),\"336,184,368,64\" -> Array(42,8,23,16,4,15),\"336,184,368,240\" -> Array(42,8,23,16,15,4),\"630,60,32,128\" -> Array(42,15,4,8,16,23),\"630,60,32,184\" -> Array(42,15,4,8,23,16),\"630,60,64,128\" -> Array(42,15,4,16,8,23),\"630,60,64,368\" -> Array(42,15,4,16,23,8),\"630,60,92,184\" -> Array(42,15,4,23,8,16),\"630,60,92,368\" -> Array(42,15,4,23,16,8),\"630,120,32,64\" -> Array(42,15,8,4,16,23),\"630,120,32,92\" -> Array(42,15,8,4,23,16),\"630,120,128,64\" -> Array(42,15,8,16,4,23),\"630,120,128,368\" -> Array(42,15,8,16,23,4),\"630,120,184,92\" -> Array(42,15,8,23,4,16),\"630,120,184,368\" -> Array(42,15,8,23,16,4),\"630,240,64,32\" -> Array(42,15,16,4,8,23),\"630,240,64,92\" -> Array(42,15,16,4,23,8),\"630,240,128,32\" -> Array(42,15,16,8,4,23),\"630,240,128,184\" -> Array(42,15,16,8,23,4),\"630,240,368,92\" -> Array(42,15,16,23,4,8),\"630,240,368,184\" -> Array(42,15,16,23,8,4),\"630,345,92,32\" -> Array(42,15,23,4,8,16),\"630,345,92,64\" -> Array(42,15,23,4,16,8),\"630,345,184,32\" -> Array(42,15,23,8,4,16),\"630,345,184,128\" -> Array(42,15,23,8,16,4),\"630,345,368,64\" -> Array(42,15,23,16,4,8),\"630,345,368,128\" -> Array(42,15,23,16,8,4),\"672,64,32,120\" -> Array(42,16,4,8,15,23),\"672,64,32,184\" -> Array(42,16,4,8,23,15),\"672,64,60,120\" -> Array(42,16,4,15,8,23),\"672,64,60,345\" -> Array(42,16,4,15,23,8),\"672,64,92,184\" -> Array(42,16,4,23,8,15),\"672,64,92,345\" -> Array(42,16,4,23,15,8),\"672,128,32,60\" -> Array(42,16,8,4,15,23),\"672,128,32,92\" -> Array(42,16,8,4,23,15),\"672,128,120,60\" -> Array(42,16,8,15,4,23),\"672,128,120,345\" -> Array(42,16,8,15,23,4),\"672,128,184,92\" -> Array(42,16,8,23,4,15),\"672,128,184,345\" -> Array(42,16,8,23,15,4),\"672,240,60,32\" -> Array(42,16,15,4,8,23),\"672,240,60,92\" -> Array(42,16,15,4,23,8),\"672,240,120,32\" -> Array(42,16,15,8,4,23),\"672,240,120,184\" -> Array(42,16,15,8,23,4),\"672,240,345,92\" -> Array(42,16,15,23,4,8),\"672,240,345,184\" -> Array(42,16,15,23,8,4),\"672,368,92,32\" -> Array(42,16,23,4,8,15),\"672,368,92,60\" -> Array(42,16,23,4,15,8),\"672,368,184,32\" -> Array(42,16,23,8,4,15),\"672,368,184,120\" -> Array(42,16,23,8,15,4),\"672,368,345,60\" -> Array(42,16,23,15,4,8),\"672,368,345,120\" -> Array(42,16,23,15,8,4),\"966,92,32,120\" -> Array(42,23,4,8,15,16),\"966,92,32,128\" -> Array(42,23,4,8,16,15),\"966,92,60,120\" -> Array(42,23,4,15,8,16),\"966,92,60,240\" -> Array(42,23,4,15,16,8),\"966,92,64,128\" -> Array(42,23,4,16,8,15),\"966,92,64,240\" -> Array(42,23,4,16,15,8),\"966,184,32,60\" -> Array(42,23,8,4,15,16),\"966,184,32,64\" -> Array(42,23,8,4,16,15),\"966,184,120,60\" -> Array(42,23,8,15,4,16),\"966,184,120,240\" -> Array(42,23,8,15,16,4),\"966,184,128,64\" -> Array(42,23,8,16,4,15),\"966,184,128,240\" -> Array(42,23,8,16,15,4),\"966,345,60,32\" -> Array(42,23,15,4,8,16),\"966,345,60,64\" -> Array(42,23,15,4,16,8),\"966,345,120,32\" -> Array(42,23,15,8,4,16),\"966,345,120,128\" -> Array(42,23,15,8,16,4),\"966,345,240,64\" -> Array(42,23,15,16,4,8),\"966,345,240,128\" -> Array(42,23,15,16,8,4),\"966,368,64,32\" -> Array(42,23,16,4,8,15),\"966,368,64,60\" -> Array(42,23,16,4,15,8),\"966,368,128,32\" -> Array(42,23,16,8,4,15),\"966,368,128,120\" -> Array(42,23,16,8,15,4),\"966,368,240,60\" -> Array(42,23,16,15,4,8),\"966,368,240,120\" -> Array(42,23,16,15,8,4)\n\n )\n\n println(\"? 1 2\")\n val a = readInt()\n println(\"? 2 3\")\n val b = readInt()\n println(\"? 3 4\")\n val c = readInt()\n println(\"? 4 5\")\n val d = readInt()\n\n println(\"! \" + M(s\"$a,$b,$c,$d\").mkString(\" \"))\n /*\n? 1 2\n32\n? 2 3\n120\n? 3 4\n240\n? 4 5\n368\n */\n}\n"}], "negative_code": [], "src_uid": "c0f79d7ebcecc4eb7d07c372ba9be802"} {"nl": {"description": "You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that $$$a + b + c + d = n$$$, and $$$\\gcd(a, b) = \\operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $$$n$$$ ($$$4 \\le n \\le 10^9$$$)\u00a0\u2014 the sum of $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$.", "output_spec": "For each test case output $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ such that $$$a + b + c + d = n$$$ and $$$\\gcd(a, b) = \\operatorname{lcm}(c, d)$$$.", "sample_inputs": ["5\n4\n7\n8\n9\n10"], "sample_outputs": ["1 1 1 1\n2 2 2 1\n2 2 2 2\n2 4 2 1\n3 5 1 1"], "notes": "NoteIn the first test case $$$\\gcd(1, 1) = \\operatorname{lcm}(1, 1) = 1$$$, $$$1 + 1 + 1 + 1 = 4$$$.In the second test case $$$\\gcd(2, 2) = \\operatorname{lcm}(2, 1) = 2$$$, $$$2 + 2 + 2 + 1 = 7$$$.In the third test case $$$\\gcd(2, 2) = \\operatorname{lcm}(2, 2) = 2$$$, $$$2 + 2 + 2 + 2 = 8$$$.In the fourth test case $$$\\gcd(2, 4) = \\operatorname{lcm}(2, 1) = 2$$$, $$$2 + 4 + 2 + 1 = 9$$$.In the fifth test case $$$\\gcd(3, 5) = \\operatorname{lcm}(1, 1) = 1$$$, $$$3 + 5 + 1 + 1 = 10$$$. "}, "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(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"}, {"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"} {"nl": {"description": "Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.The park consists of n squares connected with (n\u2009-\u20091) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.Andryusha wants to use as little different colors as possible. Help him to choose the colors!", "input_spec": "The first line contains single integer n (3\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of squares in the park. Each of the next (n\u2009-\u20091) lines contains two integers x and y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n)\u00a0\u2014 the indices of two squares directly connected by a path. It is guaranteed that any square is reachable from any other using the paths.", "output_spec": "In the first line print single integer k\u00a0\u2014 the minimum number of colors Andryusha has to use. In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.", "sample_inputs": ["3\n2 3\n1 3", "5\n2 3\n5 3\n4 3\n1 3", "5\n2 1\n3 2\n4 3\n5 4"], "sample_outputs": ["3\n1 3 2", "5\n1 3 2 5 4", "3\n1 2 3 1 2"], "notes": "NoteIn the first sample the park consists of three squares: 1\u2009\u2192\u20093\u2009\u2192\u20092. Thus, the balloon colors have to be distinct. Illustration for the first sample. In the second example there are following triples of consequently connected squares: 1\u2009\u2192\u20093\u2009\u2192\u20092 1\u2009\u2192\u20093\u2009\u2192\u20094 1\u2009\u2192\u20093\u2009\u2192\u20095 2\u2009\u2192\u20093\u2009\u2192\u20094 2\u2009\u2192\u20093\u2009\u2192\u20095 4\u2009\u2192\u20093\u2009\u2192\u20095 We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. Illustration for the second sample. In the third example there are following triples: 1\u2009\u2192\u20092\u2009\u2192\u20093 2\u2009\u2192\u20093\u2009\u2192\u20094 3\u2009\u2192\u20094\u2009\u2192\u20095 We can see that one or two colors is not enough, but there is an answer that uses three colors only. Illustration for the third sample. "}, "positive_code": [{"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 val adj = Array.fill(n)(ArrayBuffer.empty[Int])\n\n (0 to n - 2).foreach { _ =>\n val Array(x, y) = readInts(2)\n adj(x - 1).append(y - 1)\n adj(y - 1).append(x - 1)\n }\n\n val q = mutable.Queue[Int]()\n val pre = Array.fill[Int](n)(0)\n val col = Array.fill[Int](n)(0)\n val visited = Array.fill(n)(false)\n\n var k = 0\n\n q.enqueue(0)\n pre(0) = 0\n col(0) = 1\n\n while (q.nonEmpty) {\n val cur = q.dequeue()\n visited(cur) = true\n k = Math.max(k, 1 + adj(cur).size)\n\n var cid = 1\n adj(cur).foreach { next =>\n if (!visited(next)) {\n while (pre(cur) == cid || col(cur) == cid) cid += 1\n col(next) = cid\n pre(next) = col(cur)\n cid += 1\n q.enqueue(next)\n }\n }\n }\n\n println(k)\n print(col(0))\n for (i <- 1 to n - 1) print(\" \" + col(i))\n println()\n\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "negative_code": [], "src_uid": "2aaa31d52d69ff3703f93177b25671a3"} {"nl": {"description": "This problem is interactive.We have hidden an array $$$a$$$ of $$$n$$$ pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of $$$k$$$ different elements of the array, it will return the position and value of the $$$m$$$-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember $$$k$$$, but don't remember $$$m$$$. Your task is to find $$$m$$$ using queries to this device. You can ask not more than $$$n$$$ queries.Note that the array $$$a$$$ and number $$$m$$$ are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array $$$a$$$. You just have to guess $$$m$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\\le k < n \\le 500$$$)\u00a0\u2014 the length of the array and the number of the elements in the query. It is guaranteed that number $$$m$$$ satisfies $$$1\\le m \\le k$$$, elements $$$a_1, a_2, \\dots, a_n$$$ of the array satisfy $$$0\\le a_i \\le 10^9$$$, and all of them are different.", "output_spec": null, "sample_inputs": ["4 3\n4 9\n4 9\n4 9\n1 2"], "sample_outputs": ["? 2 3 4\n? 1 3 4\n? 1 2 4\n? 1 2 3\n! 3"], "notes": "NoteIn the example, $$$n = 4$$$, $$$k = 3$$$, $$$m = 3$$$, $$$a = [2, 0, 1, 9]$$$."}, "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ids = Array.tabulate(k + 1)(_ + 1)\n val xs = Array.ofDim[Int](k + 1)\n for (i <- 0 until k + 1) {\n val ask = ids.filterNot(_ == i + 1)\n out.println(\"? \" + ask.mkString(\" \"))\n out.flush()\n val pos, x = nextInt\n xs(i) = x\n }\n\n val max = xs.max\n val res = xs.count(_ == max)\n\n out.println(s\"! $res\")\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 val n, k = nextInt\n val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)\n val xs = Array.ofDim[Int](k + 1)\n for (i <- 0 until k + 1) {\n val ask = ids.view(i, i + k)\n out.println(\"? \" + ask.mkString(\" \"))\n out.flush()\n val pos, x = nextInt\n xs(i) = x\n }\n\n val max = xs.max\n val res = xs.count(_ == max)\n\n out.println(s\"! $res\")\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 {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)\n val xs = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n val ask = ids.view(i, i + k)\n out.println(\"? \" + ask.mkString(\" \"))\n out.flush()\n val pos, x = nextInt\n xs(i) = x\n }\n\n val counts = xs.groupBy(identity).map {\n case (key, values) => key -> values.length\n }\n val max = counts.valuesIterator.max\n val countsWithMax = counts.valuesIterator.count(_ == max)\n val mode = xs.maxBy(counts)\n val x = xs.filter(x => counts(x) == mode).max\n val sorted = xs.sortBy(counts)\n val median = sorted(n / 2)\n val res = if (mode < median) xs.count(_ < mode) else k - xs.count(_ > mode)\n\n out.println(s\"! $res\")\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 {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)\n val xs = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n val ask = ids.view(i, i + k)\n out.println(\"? \" + ask.mkString(\" \"))\n out.flush()\n val pos, x = nextInt\n xs(i) = x\n }\n\n val counts = xs.groupBy(identity).map {\n case (key, values) => key -> values.length\n }\n val max = xs.maxBy(counts)\n val res = k - xs.count(_ > max)\n\n out.println(s\"! $res\")\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 {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)\n val xs = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n val ask = ids.view(i, i + k)\n out.println(\"? \" + ask.mkString(\" \"))\n out.flush()\n val pos, x = nextInt\n xs(i) = x\n }\n\n val max = xs.max\n val res = xs.count(_ == max)\n\n out.println(s\"! $res\")\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 {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n, k = nextInt\n val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)\n val xs = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n val ask = ids.view(i, i + k)\n out.println(\"? \" + ask.mkString(\" \"))\n out.flush()\n val pos, x = nextInt\n xs(i) = x\n }\n\n val counts = xs.groupBy(identity).map {\n case (key, values) => key -> values.length\n }\n val max = counts.valuesIterator.max\n val countsWithMax = counts.valuesIterator.count(_ == max)\n val mode = xs.maxBy(counts)\n val res = if (countsWithMax == 2) (k + 1) / 2 else k - xs.count(_ > mode)\n\n out.println(s\"! $res\")\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": "712bef1b0f737cb9c2b35a96498d50bc"} {"nl": {"description": "The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: Operation ++ increases the value of variable x by 1. Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters \"+\", \"-\", \"X\". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009150) \u2014 the number of statements in the programme. Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter \u00abX\u00bb). Thus, there are no empty statements. The operation and the variable can be written in any order.", "output_spec": "Print a single integer \u2014 the final value of x.", "sample_inputs": ["1\n++X", "2\nX++\n--X"], "sample_outputs": ["1", "0"], "notes": null}, "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": "\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}"}, {"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"} {"nl": {"description": "You have a card deck of $$$n$$$ cards, numbered from top to bottom, i.\u00a0e. the top card has index $$$1$$$ and bottom card\u00a0\u2014 index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should: find the highest card in the deck with color $$$t_j$$$, i.\u00a0e. the card with minimum index; print the position of the card you found; take the card and place it on top of the deck. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$; $$$1 \\le q \\le 3 \\cdot 10^5$$$)\u00a0\u2014 the number of cards in the deck and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 50$$$)\u00a0\u2014 the colors of cards. The third line contains $$$q$$$ integers $$$t_1, t_2, \\dots, t_q$$$ ($$$1 \\le t_j \\le 50$$$)\u00a0\u2014 the query colors. It's guaranteed that queries ask only colors that are present in the deck.", "output_spec": "Print $$$q$$$ integers\u00a0\u2014 the answers for each query.", "sample_inputs": ["7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"], "sample_outputs": ["5 2 3 1 5"], "notes": "NoteDescription of the sample: the deck is $$$[2, 1, 1, 4, \\underline{3}, 3, 1]$$$ and the first card with color $$$t_1 = 3$$$ has position $$$5$$$; the deck is $$$[3, \\underline{2}, 1, 1, 4, 3, 1]$$$ and the first card with color $$$t_2 = 2$$$ has position $$$2$$$; the deck is $$$[2, 3, \\underline{1}, 1, 4, 3, 1]$$$ and the first card with color $$$t_3 = 1$$$ has position $$$3$$$; the deck is $$$[\\underline{1}, 2, 3, 1, 4, 3, 1]$$$ and the first card with color $$$t_4 = 1$$$ has position $$$1$$$; the deck is $$$[1, 2, 3, 1, \\underline{4}, 3, 1]$$$ and the first card with color $$$t_5 = 4$$$ has position $$$5$$$. "}, "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 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"}, {"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"} {"nl": {"description": "Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last n days. Thus, he got a sequence of numbers t1,\u2009t2,\u2009...,\u2009tn, where the i-th number is the temperature on the i-th day.Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009-\u20091) such that t1\u2009<\u20090,\u2009t2\u2009<\u20090,\u2009...,\u2009tk\u2009<\u20090 and tk\u2009+\u20091\u2009>\u20090,\u2009tk\u2009+\u20092\u2009>\u20090,\u2009...,\u2009tn\u2009>\u20090. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset.You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of days for which Vasya has been measuring the temperature. The second line contains a sequence of n integers t1,\u2009t2,\u2009...,\u2009tn (|ti|\u2009\u2264\u2009109) \u2014 the sequence of temperature values. Numbers ti are separated by single spaces.", "output_spec": "Print a single integer \u2014 the answer to the given task.", "sample_inputs": ["4\n-1 1 -2 1", "5\n0 -1 1 2 -5"], "sample_outputs": ["1", "2"], "notes": "NoteNote to the first sample: there are two ways to change exactly one number so that the sequence met Vasya's condition. You can either replace the first number 1 by any negative number or replace the number -2 by any positive number."}, "positive_code": [{"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"}, {"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": "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}"}], "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"} {"nl": {"description": "An array is beautiful if both of the following two conditions meet: there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum; there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$)\u00a0\u2014 the number of test cases. Each test case consists of one line containing four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$ and $$$r_2$$$ ($$$1 \\le l_1 \\le r_1 \\le 50$$$; $$$1 \\le l_2 \\le r_2 \\le 50$$$).", "output_spec": "For each test case, print one integer\u00a0\u2014 the minimum possible number of elements in a beautiful array.", "sample_inputs": ["7\n\n3 5 4 6\n\n5 8 5 5\n\n3 3 10 12\n\n1 5 3 3\n\n1 1 2 2\n\n2 2 1 1\n\n6 6 6 6"], "sample_outputs": ["4\n5\n13\n3\n3\n3\n6"], "notes": "NoteOptimal arrays in the test cases of the example: $$$[1, 1, 1, 1]$$$, it has $$$4$$$ minimums and $$$4$$$ maximums; $$$[4, 4, 4, 4, 4]$$$, it has $$$5$$$ minimums and $$$5$$$ maximums; $$$[1, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2]$$$, it has $$$3$$$ minimums and $$$10$$$ maximums; $$$[8, 8, 8]$$$, it has $$$3$$$ minimums and $$$3$$$ maximums; $$$[4, 6, 6]$$$, it has $$$1$$$ minimum and $$$2$$$ maximums; $$$[3, 4, 3]$$$, it has $$$2$$$ minimums and $$$1$$$ maximum; $$$[5, 5, 5, 5, 5, 5]$$$, it has $$$6$$$ minimums and $$$6$$$ maximums. "}, "positive_code": [{"source_code": "/*\n Case 1: all same\n n A's are\n l1<=n<=r1\n l2<=n<=r2\n n=max(l1,l2)\n if(n>min(r1, r2))\n not ok\n Case 2: two distinct\n*/\n\nobject Main {\n def max(a: Int, b: Int): Int ={\n if(a>b)return a\n return b\n }\n def min(a: Int, b: Int): Int ={\n if(a>b)return b\n return a\n }\n def zoldyck(): Int = {\n val inp = scala.io.StdIn.readLine()\n val Array(l1,r1,l2,r2) = inp.split(\" \").map(_.toInt)\n var ans = l1 + l2\n if(max(l1, l2)<=min(r1, r2)){\n ans = min(ans, max(l1, l2))\n }\n return ans\n }\n def main(args: Array[String]): Unit = {\n var t = scala.io.StdIn.readInt()\n while(t>0){\n println(zoldyck())\n t = t - 1\n }\n }\n}"}], "negative_code": [], "src_uid": "c783eaf1bf7e4e7321406431030d5aab"} {"nl": {"description": "As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: \"Which one committed the crime?\". Suspect number i answered either \"The crime was committed by suspect number ai\", or \"Suspect number ai didn't commit the crime\". Also, the suspect could say so about himself (ai\u2009=\u2009i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either \"+ai\" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or \"-ai\" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1\u2009\u2264\u2009ai\u2009\u2264\u2009n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.", "output_spec": "Print n lines. Line number i should contain \"Truth\" if suspect number i has told the truth for sure. Print \"Lie\" if the suspect number i lied for sure and print \"Not defined\" if he could lie and could tell the truth, too, depending on who committed the crime.", "sample_inputs": ["1 1\n+1", "3 2\n-1\n-2\n-3", "4 1\n+2\n-3\n+4\n-1"], "sample_outputs": ["Truth", "Not defined\nNot defined\nNot defined", "Lie\nNot defined\nLie\nNot defined"], "notes": "NoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one."}, "positive_code": [{"source_code": "object D {\n def main(args: Array[String]): Unit = {\n val lines = scala.io.Source.stdin.getLines().toSeq\n val a = lines.head.split(\" \").map(_.toInt)\n val N = a(0)\n val M = a(1)\n val data = lines.tail.map(_.replace('+','0').toInt)\n\n val guilty = new Array[Int](N)\n val notguilty = new Array[Int](N)\n val maybeguilty = new Array[Boolean](N)\n\n var totalguilty = 0\n var totalnotguilty = 0\n\n data.foreach(n => n.signum match {\n case 1 => { guilty(n - 1) += 1; totalguilty += 1 }\n case -1 => { notguilty(-n - 1) += 1; totalnotguilty += 1 }\n })\n\n def maybeGuilty(n: Int) =\n (guilty(n) + (totalnotguilty - notguilty(n))) == M\n\n var maybeTotal = 0\n for (i <- 0 to N - 1) {\n if (maybeGuilty(i)) {\n maybeguilty(i) = true\n maybeTotal += 1\n }\n }\n\n data.foreach(n => n.signum match {\n case 1 => {\n if (!maybeGuilty(n - 1)) println(\"Lie\")\n else if (maybeTotal == 1) println(\"Truth\") else println(\"Not defined\")\n }\n case -1 => {\n if (!maybeGuilty(-n - 1)) println(\"Truth\")\n else if (maybeTotal == 1) println(\"Lie\") else println(\"Not defined\")\n }\n })\n }\n}"}], "negative_code": [{"source_code": "object D extends App {\n val (n,m)=(readLine.split(\" \").map(_.toInt)) match {case Array(a,b)=>(a,b)}\n val d=new Array[Int](n);val g=new Array[Int](n);val ng=new Array[Int](n);val G=new Array[Boolean](n)\n var tg=0;var tng=0\n (0 to n-1).foreach(z=>{val k=readLine.replace('+','0').toInt;if (k>0) {d(z)=k-1;g(k-1);tg+=1;} else {d(z)=k+1;ng(-k-1);tng+=1}})\n def mbg(n:Int)=(g(n)+(tng-ng(n)))==m\n var t=0;\n (0 to n-1).foreach(i=>{if (mbg(i)){G(i)=true;t+=1}})\n (0 to n-1).foreach(i=>{val q=d(i);if (q>0) {if (!G(q)) println(\"Lie\") else if (t==1) println(\"Truth\") else println (\"Not defined\")} else {if(!G(-q)) if(t==1) println (\"Truth\") else println (\"Not defined\")}})\n}"}], "src_uid": "c761bb69cf1b5a3dbe38d9f5c46e9007"} {"nl": {"description": "To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,\u2009a3,\u2009...,\u2009ap\u2009-\u20091 such that all pairs of people ai and ai\u2009+\u20091 (1\u2009\u2264\u2009i\u2009<\u2009p) are friends. Help the Beaver find the maximum number of acquaintances he can invite.", "input_spec": "The first line of input contains an integer n \u2014 the number of the Beaver's acquaintances. The second line contains an integer k \u2014 the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,\u2009vi \u2014 indices of people who form the i-th pair of friends. The next line contains an integer m \u2014 the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2\u2009\u2264\u2009n\u2009\u2264\u200914 The input limitations for getting 100 points are: 2\u2009\u2264\u2009n\u2009\u2264\u20092000 ", "output_spec": "Output a single number \u2014 the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.", "sample_inputs": ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"], "sample_outputs": ["3"], "notes": "NoteLet's have a look at the example. Two groups of people can be invited: {1,\u20092,\u20093} and {4,\u20095}, thus the answer will be the size of the largest of these groups. Group {6,\u20097,\u20098,\u20099} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,\u20092,\u20093,\u20094,\u20095} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected)."}, "positive_code": [{"source_code": "object PartyC2 extends App {\n import scala.collection.mutable.ListBuffer\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 nodes = (0 until n).map(i => new Node(i)).toArray\n\n def addRelations(adder: Node => Node => Unit)(cant: Int): Unit = {\n (1 to cant).foreach{ _ =>\n val a = nodes(in.nextInt()-1)\n val b = nodes(in.nextInt()-1)\n adder(a)(b)\n adder(b)(a)\n }\n }\n def addFriends(cant: Int): Unit = addRelations(_.addFriend)(cant)\n def addDislikes(cant: Int): Unit = addRelations(_.addDislike)(cant)\n\n addFriends(in.nextInt())\n addDislikes(in.nextInt())\n\n def dfs(node: Node,groupID: Int): Unit = {\n node.groupID = Some(groupID)\n\n node.friends.foreach{f =>\n if(!f.visited)\n dfs(f,groupID)\n }\n }\n\n nodes.zipWithIndex.foreach{\n case (node,indx) => {\n if(!node.visited)\n dfs(node,indx)\n }\n }\n\n val counts: Array[Option[Int]] = Array.fill(n)(Option(0))\n nodes.foreach{ node =>\n node.groupID.map{ group =>\n counts(group).map{ currentCount =>\n if(node.friends.forall(friend => friend.groupID.contains(group)) &&\n node.dislikes.forall(dislike => !dislike.groupID.contains(group))){\n counts(group) = Some(currentCount+1)\n }else{\n counts(group) = None\n }\n }\n }\n }\n\n val maxValidCount: Int = {\n val validCounts = counts.flatten\n if(validCounts.isEmpty)\n 0\n else\n validCounts.max\n }\n out.println(maxValidCount)\n\n\n\n }\n\n class Node(id: Int){\n var groupID: Option[Int] = None\n var friends = ListBuffer.empty[Node]\n var dislikes = ListBuffer.empty[Node]\n def addFriend(f: Node): Unit = friends.append(f)\n def addDislike(d: Node): Unit = dislikes.append(d)\n def visited: Boolean = groupID.nonEmpty\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": "e1ebaf64b129edb8089f9e2f89a0e1e1"} {"nl": {"description": "Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109\u2009+\u20097.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000)\u00a0\u2014 the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.", "output_spec": "Print the number of ways to correctly split the given sequence modulo 109\u2009+\u20097.", "sample_inputs": ["6\n123434", "8\n20152016"], "sample_outputs": ["8", "4"], "notes": "NoteIn the first sample there are 8 ways to split the sequence: \"123434\" = \"123434\" (maybe the given sequence is just one big number) \"123434\" = \"1\" + \"23434\" \"123434\" = \"12\" + \"3434\" \"123434\" = \"123\" + \"434\" \"123434\" = \"1\" + \"23\" + \"434\" \"123434\" = \"1\" + \"2\" + \"3434\" \"123434\" = \"1\" + \"2\" + \"3\" + \"434\" \"123434\" = \"1\" + \"2\" + \"3\" + \"4\" + \"34\" Note that we don't count a split \"123434\" = \"12\" + \"34\" + \"34\" because numbers have to be strictly increasing.In the second sample there are 4 ways: \"20152016\" = \"20152016\" \"20152016\" = \"20\" + \"152016\" \"20152016\" = \"201\" + \"52016\" \"20152016\" = \"2015\" + \"2016\" "}, "positive_code": [{"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 mod = (1e9 + 7).toInt\n val len = readLine().toInt\n val digits = readLine()\n\n val dp = Array.fill(len+1, len+1)(0)\n val b = Array.fill(len+1, len+1)(len)\n val s = Array.fill(len+1, len+1)(0)\n\n for (i <- 0 to len-1) {\n dp(i)(0) = 1\n }\n\n s(0)(1) = 1\n\n\n for (i <- 1 to len/2) {\n for (j <- len-1 to i by(-1)) {\n if (digits(j-i) != digits(j)) b(j-i)(j) = 0\n else {\n if (j + 1 < len) b(j-i)(j) = 1 + b(j-i+1)(j+1)\n }\n }\n }\n\n for (i <- 1 to len-1) {\n for (j <- i to 1 by(-1)) {\n if (digits(j) != '0') {\n dp(i)(j) = s(j-1)(Math.min(i-j, j))\n if (2*j-i-1 >= 0 && digits(2*j-i-1) != '0') {\n val offset = b(2*j-i-1)(j)\n if (offset < i - j + 1 && digits(2*j-i-1+offset) < digits(j+offset)) {\n dp(i)(j) = (dp(i)(j) + dp(j-1)(2*j-i-1)) % mod\n }\n }\n }\n s(i)(i-j+1) = (s(i)(i-j) + dp(i)(j)) % mod\n }\n s(i)(i+1) = (s(i)(i) + dp(i)(0)) % mod\n }\n\n var res = 0\n for (i <- 0 to len-1) {\n val v = dp(len-1)(i)\n if (v != -1) res = (res + v) % mod\n }\n\n\n// for (i <- 0 to len-1) {\n// for (j <- 0 to len-1) {\n// print(dp(i)(j)+\" \")\n// }\n// print(\"\\n\")\n// }\n//\n// for (i <- 0 to len-1) {\n// for (j <- 1 to len) {\n// print(s(i)(j)+\" \")\n// }\n// print(\"\\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}"}], "negative_code": [{"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 mod = (1e9 + 7).toInt\n val len = readLine().toInt\n val digits = readLine()\n\n val dp = Array.fill(len+1, len+1)(-1)\n val b = Array.fill(len+1, len+1)(len)\n\n for (i <- 0 to len) dp(i)(i) = 1\n\n for (i <- 1 to len/2) {\n for (j <- len-1 to i by(-1)) {\n if (digits(j-i) != digits(j)) b(j-i)(j) = 0\n else {\n if (j + 1 < len) b(j-i)(j) = 1 + b(j-i+1)(j+1)\n }\n }\n }\n\n def solve(start: Int, n: Int): Int = {\n if (dp(start)(n) == -1) {\n var count = 0\n for (i <- 1 to n) {\n if (start - n - i >= 0 && digits(start-n-i) != '0' && digits(start-n) != '0' && (i < n || (b(start-n-i)(start-n) <= n && digits(start-n-i+b(start-n-i)(start-n)) < digits(start-n+b(start-n-i)(start-n))))) {\n val v = solve(start - n, i)\n if (v != -1) count = (count + v) % mod\n }\n }\n dp(start)(n) = count\n // println(start+\" \"+n+\" \"+count)\n }\n dp(start)(n)\n }\n\n var res = 0\n if (len != 5000) {\n for (i <- 1 to len) {\n val v = solve(len, i)\n if (v != -1) res = (res + v) % mod\n }\n }\n\n\n // for (i <- 0 to len) {\n // for (j <- 0 to len) {\n // print(dp(i)(j)+\" \")\n // }\n // print(\"\\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}"}], "src_uid": "1fe6daf718b88cabb2e956e81add3719"} {"nl": {"description": "You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.", "input_spec": "The first line contains three space-separated integers n (1\u2009\u2264\u2009n\u2009\u2264\u2009103), k1 and k2 (0\u2009\u2264\u2009k1\u2009+\u2009k2\u2009\u2264\u2009103, k1 and k2 are non-negative) \u2014 size of arrays and number of operations to perform on A and B respectively. Second line contains n space separated integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009106\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 array A. Third line contains n space separated integers b1,\u2009b2,\u2009...,\u2009bn (\u2009-\u2009106\u2009\u2264\u2009bi\u2009\u2264\u2009106)\u2014 array B.", "output_spec": "Output a single integer \u2014 the minimum possible value of after doing exactly k1 operations on array A and exactly k2 operations on array B.", "sample_inputs": ["2 0 0\n1 2\n2 3", "2 1 0\n1 2\n2 2", "2 5 7\n3 4\n14 4"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E\u2009=\u2009(1\u2009-\u20092)2\u2009+\u2009(2\u2009-\u20093)2\u2009=\u20092. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A\u2009=\u2009[2,\u20092]. The error is now E\u2009=\u2009(2\u2009-\u20092)2\u2009+\u2009(2\u2009-\u20092)2\u2009=\u20090. This is the minimum possible error obtainable.In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A\u2009=\u2009[8,\u20094] and B\u2009=\u2009[8,\u20094]. The error is now E\u2009=\u2009(8\u2009-\u20098)2\u2009+\u2009(4\u2009-\u20094)2\u2009=\u20090, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B\u2009=\u2009[8,\u20095] and E\u2009=\u2009(8\u2009-\u20098)2\u2009+\u2009(4\u2009-\u20095)2\u2009=\u20091."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movement\u00a0\u2014 it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.", "input_spec": "The first line contains the positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of particles. The second line contains n symbols \"L\" and \"R\". If the i-th symbol equals \"L\", then the i-th particle will move to the left, otherwise the i-th symbol equals \"R\" and the i-th particle will move to the right. The third line contains the sequence of pairwise distinct even integers x1,\u2009x2,\u2009...,\u2009xn (0\u2009\u2264\u2009xi\u2009\u2264\u2009109)\u00a0\u2014 the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order. ", "output_spec": "In the first line print the only integer\u00a0\u2014 the first moment (in microseconds) when two particles are at the same point and there will be an explosion. Print the only integer -1, if the collision of particles doesn't happen. ", "sample_inputs": ["4\nRLRL\n2 4 6 10", "3\nLLR\n40 50 60"], "sample_outputs": ["1", "-1"], "notes": "NoteIn the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\\underset{1 \\leq i \\leq n}{\\max} (a_i \\oplus X)$$$ is minimum possible, where $$$\\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\\underset{1 \\leq i \\leq n}{\\max} (a_i \\oplus X)$$$.", "input_spec": "The first line contains integer $$$n$$$ ($$$1\\le n \\le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2^{30}-1$$$).", "output_spec": "Print one integer \u2014 the minimum possible value of $$$\\underset{1 \\leq i \\leq n}{\\max} (a_i \\oplus X)$$$.", "sample_inputs": ["3\n1 2 3", "2\n1 5"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt).toList\n findMin(a, 30) match {\n case Some(i) => println(i)\n case None => println(0)\n }\n }\n\n def findMin(a: List[Int], b: Int): Option[Int] = {\n if (a.isEmpty) None else\n if (b == -1) Some(0) else\n {\n val (a1, a0) = a.partition((x) => ((x & (1 << b)) != 0))\n val a1p = a1.map((x) => x ^ (1 << b))\n //println(a1p, a0)\n (findMin(a1p, b - 1), findMin(a0, b - 1)) match {\n case (None, None) => None\n case (Some(i), None) => Some(i)\n case (None, Some(j)) => Some(j)\n case (Some(i), Some(j)) => if (i < j) Some(i ^ (1 << b)) else Some(j ^ (1 << b))\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "d17d2fcfb088bf51e9c1f3fce4133a94"} {"nl": {"description": "After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the total likes to the published photoes. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091\u2009000\u2009000), where ai is the identifier of the photo which got the i-th like.", "output_spec": "Print the identifier of the photo which won the elections.", "sample_inputs": ["5\n1 3 2 2 1", "9\n100 200 300 200 100 300 300 100 200"], "sample_outputs": ["2", "300"], "notes": "NoteIn the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got: more likes than the photo with id 3; as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier. "}, "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 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"}, {"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": "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"}, {"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"}], "negative_code": [], "src_uid": "e4a2354159fc4cab7088e016cf17ae6c"} {"nl": {"description": "Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally: If it is the first move, he chooses any element and deletes it; If it is the second or any next move: if the last deleted element was odd, Polycarp chooses any even element and deletes it; if the last deleted element was even, Polycarp chooses any odd element and deletes it. If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2000$$$) \u2014 the number of elements of $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer \u2014 the minimum possible sum of non-deleted elements of the array after end of the game.", "sample_inputs": ["5\n1 5 7 8 2", "6\n5 1 2 4 6 3", "2\n1000000 1000000"], "sample_outputs": ["0", "0", "1000000"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1,\u2009a2,\u2009...,\u2009a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1\u00a0or\u00a0a2,\u2009a3\u00a0or\u00a0a4,\u2009...,\u2009a2n\u2009-\u20091\u00a0or\u00a0a2n, consisting of 2n\u2009-\u20091 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a\u2009=\u2009(1,\u20092,\u20093,\u20094). Then let's write down all the transformations (1,\u20092,\u20093,\u20094) \u2009\u2192\u2009 (1\u00a0or\u00a02\u2009=\u20093,\u20093\u00a0or\u00a04\u2009=\u20097) \u2009\u2192\u2009 (3\u00a0xor\u00a07\u2009=\u20094). The result is v\u2009=\u20094.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p,\u2009b. Query p,\u2009b means that you need to perform the assignment ap\u2009=\u2009b. After each query, you need to print the new value v for the new sequence a.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200917,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009105). The next line contains 2n integers a1,\u2009a2,\u2009...,\u2009a2n (0\u2009\u2264\u2009ai\u2009<\u2009230). Each of the next m lines contains queries. The i-th line contains integers pi,\u2009bi (1\u2009\u2264\u2009pi\u2009\u2264\u20092n,\u20090\u2009\u2264\u2009bi\u2009<\u2009230) \u2014 the i-th query.", "output_spec": "Print m integers \u2014 the i-th integer denotes value v for sequence a after the i-th query.", "sample_inputs": ["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"], "sample_outputs": ["1\n3\n3\n3"], "notes": "NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation"}, "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 //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"}, {"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"} {"nl": {"description": "A card pyramid of height $$$1$$$ is constructed by resting two cards against each other. For $$$h>1$$$, a card pyramid of height $$$h$$$ is constructed by placing a card pyramid of height $$$h-1$$$ onto a base. A base consists of $$$h$$$ pyramids of height $$$1$$$, and $$$h-1$$$ cards on top. For example, card pyramids of heights $$$1$$$, $$$2$$$, and $$$3$$$ look as follows: You start with $$$n$$$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?", "input_spec": "Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 10^9$$$)\u00a0\u2014 the number of cards. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^9$$$.", "output_spec": "For each test case output a single integer\u00a0\u2014 the number of pyramids you will have constructed in the end.", "sample_inputs": ["5\n3\n14\n15\n24\n1"], "sample_outputs": ["1\n2\n1\n3\n0"], "notes": "NoteIn the first test, you construct a pyramid of height $$$1$$$ with $$$2$$$ cards. There is $$$1$$$ card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height $$$2$$$, with no cards remaining.In the third test, you build one pyramid of height $$$3$$$, with no cards remaining.In the fourth test, you build one pyramid of height $$$3$$$ with $$$9$$$ cards remaining. Then you build a pyramid of height $$$2$$$ with $$$2$$$ cards remaining. Then you build a final pyramid of height $$$1$$$ with no cards remaining.In the fifth test, one card is not enough to build any pyramids."}, "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": "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}"}, {"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"} {"nl": {"description": "You are given a string $$$s$$$ consisting of lowercase Latin letters \"a\", \"b\" and \"c\" and question marks \"?\".Let the number of question marks in the string $$$s$$$ be $$$k$$$. Let's replace each question mark with one of the letters \"a\", \"b\" and \"c\". Here we can obtain all $$$3^{k}$$$ possible strings consisting only of letters \"a\", \"b\" and \"c\". For example, if $$$s = $$$\"ac?b?c\" then we can obtain the following strings: $$$[$$$\"acabac\", \"acabbc\", \"acabcc\", \"acbbac\", \"acbbbc\", \"acbbcc\", \"accbac\", \"accbbc\", \"accbcc\"$$$]$$$.Your task is to count the total number of subsequences \"abc\" in all resulting strings. Since the answer can be very large, print it modulo $$$10^{9} + 7$$$.A subsequence of the string $$$t$$$ is such a sequence that can be derived from the string $$$t$$$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string \"baacbc\" contains two subsequences \"abc\" \u2014 a subsequence consisting of letters at positions $$$(2, 5, 6)$$$ and a subsequence consisting of letters at positions $$$(3, 5, 6)$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ $$$(3 \\le n \\le 200\\,000)$$$ \u2014 the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters \"a\", \"b\" and \"c\" and question marks\"?\".", "output_spec": "Print the total number of subsequences \"abc\" in all strings you can obtain if you replace all question marks with letters \"a\", \"b\" and \"c\", modulo $$$10^{9} + 7$$$.", "sample_inputs": ["6\nac?b?c", "7\n???????", "9\ncccbbbaaa", "5\na???c"], "sample_outputs": ["24", "2835", "0", "46"], "notes": "NoteIn the first example, we can obtain $$$9$$$ strings: \"acabac\" \u2014 there are $$$2$$$ subsequences \"abc\", \"acabbc\" \u2014 there are $$$4$$$ subsequences \"abc\", \"acabcc\" \u2014 there are $$$4$$$ subsequences \"abc\", \"acbbac\" \u2014 there are $$$2$$$ subsequences \"abc\", \"acbbbc\" \u2014 there are $$$3$$$ subsequences \"abc\", \"acbbcc\" \u2014 there are $$$4$$$ subsequences \"abc\", \"accbac\" \u2014 there is $$$1$$$ subsequence \"abc\", \"accbbc\" \u2014 there are $$$2$$$ subsequences \"abc\", \"accbcc\" \u2014 there are $$$2$$$ subsequences \"abc\". So, there are $$$2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24$$$ subsequences \"abc\" in total."}, "positive_code": [{"source_code": "//package codeforces.contests._1426\n\nobject NumberOfSubsequences {\n val MOD: Long = 1000000007\n\n def main(args: Array[String]): Unit = {\n\n val n = io.StdIn.readInt()\n val s = io.StdIn.readLine\n\n var count: Long = 1\n\n val dp: Array[Array[Long]] = Array.ofDim[Long](n, 3)\n\n\n s(n - 1) match {\n case 'c' =>\n dp(n - 1)(2) = 1\n case '?' =>\n dp(n - 1)(2) = 1\n count = 3\n case _ =>\n }\n\n\n for (i <- n - 2 to 0 by -1) {\n\n dp(i)(0) = dp(i + 1)(0)\n dp(i)(1) = dp(i + 1)(1)\n dp(i)(2) = dp(i + 1)(2)\n\n s(i) match {\n case 'a' => dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD\n case 'b' => dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD\n case 'c' => dp(i)(2) = (dp(i)(2) + count) % MOD\n case '?' =>\n dp(i)(0) = (dp(i)(0) * 3) % MOD\n dp(i)(1) = (dp(i)(1) * 3) % MOD\n dp(i)(2) = (dp(i)(2) * 3) % MOD\n\n dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD\n dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD\n dp(i)(2) = (dp(i)(2) + count) % MOD\n\n count = (count * 3) % MOD\n }\n\n }\n\n println(dp(0)(0))\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1426\n\nobject NumberOfSubsequences {\n val MOD: Long = (1e9 + 7).toLong\n\n def main(args: Array[String]): Unit = {\n\n val n = io.StdIn.readInt()\n val s = io.StdIn.readLine\n\n var count = 1\n\n val dp: Array[Array[Long]] = Array.ofDim[Long](n, 3)\n\n\n s(n - 1) match {\n case 'c' =>\n dp(n - 1)(2) = 1\n case '?' =>\n dp(n - 1)(2) = 1\n count = 3\n case _ =>\n }\n\n\n for (i <- n - 2 to 0 by -1) {\n\n dp(i)(0) = dp(i + 1)(0)\n dp(i)(1) = dp(i + 1)(1)\n dp(i)(2) = dp(i + 1)(2)\n\n s(i) match {\n case 'a' => dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD\n case 'b' => dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD\n case 'c' => dp(i)(2) = (dp(i)(2) + count) % MOD\n case '?' =>\n dp(i)(0) = (dp(i)(0) * 3) % MOD\n dp(i)(1) = (dp(i)(1) * 3) % MOD\n dp(i)(2) = (dp(i)(2) * 3) % MOD\n\n dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD\n dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD\n dp(i)(2) = (dp(i)(2) + count) % MOD\n\n count *= 3\n }\n\n }\n\n println(dp(0)(0))\n }\n}\n"}, {"source_code": "//package codeforces.contests._1426\n\nobject NumberOfSubsequences {\n val MOD: Long = 1000000007\n\n def main(args: Array[String]): Unit = {\n\n val n = io.StdIn.readInt()\n val s = io.StdIn.readLine\n\n var count: Long = 1\n\n val dp: Array[Array[Long]] = Array.ofDim[Long](n, 3)\n\n\n s(n - 1) match {\n case 'c' =>\n dp(n - 1)(2) = 1\n case '?' =>\n dp(n - 1)(2) = 1\n count = 3\n case _ =>\n }\n\n\n for (i <- n - 2 to 0 by -1) {\n\n dp(i)(0) = dp(i + 1)(0)\n dp(i)(1) = dp(i + 1)(1)\n dp(i)(2) = dp(i + 1)(2)\n\n s(i) match {\n case 'a' => dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD\n case 'b' => dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD\n case 'c' => dp(i)(2) = (dp(i)(2) + count) % MOD\n case '?' =>\n dp(i)(0) = (dp(i)(0) * 3) % MOD\n dp(i)(1) = (dp(i)(1) * 3) % MOD\n dp(i)(2) = (dp(i)(2) * 3) % MOD\n\n dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD\n dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD\n dp(i)(2) = (dp(i)(2) + count) % MOD\n\n count *= 3\n }\n\n }\n\n println(dp(0)(0))\n }\n}\n"}], "src_uid": "45d8827bfee3afeeed79741a2c3b0a0f"} {"nl": {"description": "Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.The way to split up game pieces is split into several steps: First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once. Alice will get all the pieces marked A and Bob will get all the pieces marked B. The strength of a player is then the sum of strengths of the pieces in the group.Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of game pieces. The second line contains n integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009109) \u2014 the strength of the i-th piece. The third line contains n characters A or B \u2014 the assignment of teams after the first step (after Alice's step).", "output_spec": "Print the only integer a \u2014 the maximum strength Bob can achieve.", "sample_inputs": ["5\n1 2 3 4 5\nABABA", "5\n1 2 3 4 5\nAAAAA", "1\n1\nB"], "sample_outputs": ["11", "15", "1"], "notes": "NoteIn the first sample Bob should flip the suffix of length one.In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.In the third sample Bob should do nothing."}, "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 p = in.next().split(' ').map(_.toLong)\n val str = in.next()\n val zipped = str.zip(p)\n val current = zipped.filter(_._1 == 'B').map(_._2).sum\n\n val prefix = zipped.foldLeft((current, current)) {\n case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))\n case ((sum, max), ('B', score)) => (sum - score, max)\n }\n\n val suffix = zipped.reverse.foldLeft((current, current)) {\n case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))\n case ((sum, max), ('B', score)) => (sum - score, max)\n }\n\n println(Math.max(suffix._2, prefix._2))\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 p = in.next().split(' ').map(_.toInt)\n val str = in.next()\n val zipped = str.zip(p)\n val current = zipped.filter(_._1 == 'B').map(_._2).sum\n\n val prefix = zipped.foldLeft((current, current)) {\n case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))\n case ((sum, max), ('B', score)) => (sum - score, max)\n }\n\n val suffix = zipped.reverse.foldLeft((current, current)) {\n case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))\n case ((sum, max), ('B', score)) => (sum - score, max)\n }\n\n println(Math.max(suffix._2, prefix._2))\n}\n"}], "src_uid": "d1926feaeec151f4a2f186a46a863d90"} {"nl": {"description": "Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. The park can be represented as a rectangular n\u2009\u00d7\u2009m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.Om Nom isn't yet sure where to start his walk from but he definitely wants: to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.", "input_spec": "The first line contains three integers n,\u2009m,\u2009k (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092000;\u00a00\u2009\u2264\u2009k\u2009\u2264\u2009m(n\u2009-\u20091)). Each of the next n lines contains m characters \u2014 the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals \".\", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: \"L\" (meaning that this cell has a spider at time 0, moving left), \"R\" (a spider moving right), \"U\" (a spider moving up), \"D\" (a spider moving down). It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders.", "output_spec": "Print m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right.", "sample_inputs": ["3 3 4\n...\nR.L\nR.U", "2 2 2\n..\nRL", "2 2 2\n..\nLR", "3 4 8\n....\nRRLL\nUUUU", "2 2 2\n..\nUU"], "sample_outputs": ["0 2 2", "1 1", "0 0", "1 3 3 1", "0 0"], "notes": "NoteConsider the first sample. The notes below show how the spider arrangement changes on the field over time:... ... ..U ...R.L -> .*U -> L.R -> ...R.U .R. ..R ...Character \"*\" represents a cell that contains two spiders at the same time. If Om Nom starts from the first cell of the first row, he won't see any spiders. If he starts from the second cell, he will see two spiders at time 1. If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2. "}, "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 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}"}, {"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"} {"nl": {"description": "A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition \u2014 when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom. You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.", "input_spec": "The only line of the input contains four integer numbers d,\u2009h,\u2009v,\u2009e (1\u2009\u2264\u2009d,\u2009h,\u2009v,\u2009e\u2009\u2264\u2009104), where: d \u2014 the diameter of your cylindrical cup, h \u2014 the initial level of water in the cup, v \u2014 the speed of drinking process from the cup in milliliters per second, e \u2014 the growth of water because of rain if you do not drink from the cup. ", "output_spec": "If it is impossible to make the cup empty, print \"NO\" (without quotes). Otherwise print \"YES\" (without quotes) in the first line. In the second line print a real number \u2014 time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009-\u20094. It is guaranteed that if the answer exists, it doesn't exceed 104.", "sample_inputs": ["1 2 3 100", "1 1 1 1"], "sample_outputs": ["NO", "YES\n3.659792366325"], "notes": "NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in seconds."}, "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": "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"}, {"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"} {"nl": {"description": "You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \\le x \\le r$$$.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 500$$$) \u2014 the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^9$$$, $$$1 \\le d_i \\le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.", "output_spec": "For each query print one integer: the answer to this query.", "sample_inputs": ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"], "sample_outputs": ["6\n4\n1\n3\n10"], "notes": null}, "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 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}"}, {"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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 1\\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \\le a, b \\le 10^{9}$$$)\u00a0\u2014 the current volume and Bob's desired volume, respectively.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.", "sample_inputs": ["3\n4 0\n5 14\n3 9"], "sample_outputs": ["2\n3\n2"], "notes": "NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$. "}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\\frac{n}{2}$$$ opening brackets '(' and $$$\\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is: \"()\" is regular bracket sequence; if $$$s$$$ is regular bracket sequence then \"(\" + $$$s$$$ + \")\" is regular bracket sequence; if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, \"()()\", \"(())()\", \"(())\" and \"()\" are regular bracket sequences, but \")(\", \"()(\" and \")))\" are not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \\le n \\le 50$$$) \u2014 the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\\frac{n}{2}$$$ opening and $$$\\frac{n}{2}$$$ closing brackets.", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.", "sample_inputs": ["4\n2\n)(\n4\n()()\n8\n())()()(\n10\n)))((((())"], "sample_outputs": ["1\n0\n1\n3"], "notes": "NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain \"((()))(())\"."}, "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": "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"}, {"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"} {"nl": {"description": "A well-known art union called \"Kalevich is Alive!\" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules: Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j\u2009+\u20091)-th painter (if j\u2009<\u2009n); each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.", "input_spec": "The first line of the input contains integers m,\u2009n (1\u2009\u2264\u2009m\u2009\u2264\u200950000,\u20091\u2009\u2264\u2009n\u2009\u2264\u20095), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1,\u2009ti2,\u2009...,\u2009tin (1\u2009\u2264\u2009tij\u2009\u2264\u20091000), where tij is the time the j-th painter needs to work on the i-th picture.", "output_spec": "Print the sequence of m integers r1,\u2009r2,\u2009...,\u2009rm, where ri is the moment when the n-th painter stopped working on the i-th picture.", "sample_inputs": ["5 1\n1\n2\n3\n4\n5", "4 2\n2 5\n3 1\n5 3\n10 1"], "sample_outputs": ["1 3 6 10 15", "7 8 13 21"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500)\u00a0\u2014 the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n)\u00a0\u2014 the color of the i-th gemstone in a line.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of seconds needed to destroy the entire line.", "sample_inputs": ["3\n1 2 1", "3\n1 2 3", "7\n1 4 4 2 3 2 1"], "sample_outputs": ["1", "3", "2"], "notes": "NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1."}, "positive_code": [{"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ListBuffer\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 c = (for(i<-0 until n ) yield nextInt).toArray\n val ans=Array.ofDim[Int](n,n)\n for(sep<-0 until n){\n for(l<-0 until n-sep){\n val r=l+sep\n ans(l)(r)=n+1\n if(c(l)==c(r)){\n if(r-1>l+1){\n ans(l)(r)=ans(l+1)(r-1)\n }else{\n ans(l)(r)=0\n }\n }\n\n for(c<-l until r){\n\n ans(l)(r)=Math.min(ans(l)(r),1+ans(l)(c)+ans(c+1)(r))\n }\n\n \n }\n }\n \n out.println(ans(0)(n-1)+1)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "object B{\n //import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ListBuffer\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 c = (for(i<-0 until n ) yield nextInt).toArray\n val ans=Array.ofDim[Int](n,n)\n for(sep<-0 until n){\n for(l<-0 until n-sep){\n val r=l+sep\n if(c(l)==c(r)){\n if(r-1>l+1){\n ans(l)(r)=ans(l+1)(r-1)\n }else{\n ans(l)(r)=0\n }\n }else{\n ans(l)(r)=n+1\n for(c<-l until r){\n \n ans(l)(r)=Math.min(ans(l)(r),1+ans(l)(c)+ans(c+1)(r))\n }\n \n }\n }\n }\n \n out.println(ans(0)(n-1)+1)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "f942ed9c5e707d12be42d3ab55f39441"} {"nl": {"description": "Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\\{1, 2, 2, 3\\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.", "input_spec": "The first line of input contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$)\u00a0\u2014 the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \\le b_i \\le 10^6$$$), describing the list of the player B.", "output_spec": "Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.", "sample_inputs": ["2\n1 4\n5 1", "3\n100 100 100\n100 100 100", "2\n2 1\n5 6"], "sample_outputs": ["0", "0", "-3"], "notes": "NoteIn the first example, the game could have gone as follows: A removes $$$5$$$ from B's list. B removes $$$4$$$ from A's list. A takes his $$$1$$$. B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing: A removes $$$5$$$ from B's list. B removes $$$4$$$ from A's list. A removes $$$1$$$ from B's list. B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$."}, "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 = ni()\n val A, B = na(N)\n radixSort(A)\n radixSort(B)\n\n val stack = Array.fill[mutable.Stack[Int]](2)(mutable.Stack())\n rep(N) { i =>\n stack(0).push(A(i))\n stack(1).push(B(i))\n }\n\n var i = 0\n val S = Array.ofDim[Long](2)\n while(stack(0).nonEmpty || stack(1).nonEmpty) {\n val me = i & 1\n val you = me ^ 1\n if (stack(me).nonEmpty && stack(you).nonEmpty) {\n if (stack(me).top < stack(you).top) {\n stack(you).pop\n } else {\n S(me) += stack(me).pop\n }\n\n } else if (stack(me).nonEmpty) {\n S(me) += stack(me).pop\n } else {\n stack(you).pop\n }\n \n i += 1\n }\n\n// var i = 0\n// var a, b = N - 1\n// var Sa, Sb = 0L\n// while(a > 0 || b > 0) {\n// if (i % 2 == 0) {\n// if (a > 0 && b > 0) {\n// if (A(a) < B(b)) {\n// b -= 1\n// } else {\n// Sa += A(a)\n// a -= 1\n// }\n// } else {\n// if (A(a) > B(b)) {\n// a -= 1\n// } else {\n// Sb += B(b)\n// b -= 1\n// }\n// }\n// }\n// i += 1\n// }\n\n out.println(S(0) - S(1))\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}"}], "negative_code": [], "src_uid": "d740f4ee1b18eeb74dfb253125c52762"} {"nl": {"description": "There are $$$n$$$ left boots and $$$n$$$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $$$l$$$ and $$$r$$$, both of length $$$n$$$. The character $$$l_i$$$ stands for the color of the $$$i$$$-th left boot and the character $$$r_i$$$ stands for the color of the $$$i$$$-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.", "input_spec": "The first line contains $$$n$$$ ($$$1 \\le n \\le 150000$$$), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string $$$l$$$ of length $$$n$$$. It contains only lowercase Latin letters or question marks. The $$$i$$$-th character stands for the color of the $$$i$$$-th left boot. The third line contains the string $$$r$$$ of length $$$n$$$. It contains only lowercase Latin letters or question marks. The $$$i$$$-th character stands for the color of the $$$i$$$-th right boot.", "output_spec": "Print $$$k$$$ \u2014 the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following $$$k$$$ lines should contain pairs $$$a_j, b_j$$$ ($$$1 \\le a_j, b_j \\le n$$$). The $$$j$$$-th of these lines should contain the index $$$a_j$$$ of the left boot in the $$$j$$$-th pair and index $$$b_j$$$ of the right boot in the $$$j$$$-th pair. All the numbers $$$a_j$$$ should be distinct (unique), all the numbers $$$b_j$$$ should be distinct (unique). If there are many optimal answers, print any of them.", "sample_inputs": ["10\ncodeforces\ndodivthree", "7\nabaca?b\nzabbbcc", "9\nbambarbia\nhellocode", "10\ncode??????\n??????test"], "sample_outputs": ["5\n7 8\n4 9\n2 2\n9 10\n3 1", "5\n6 5\n2 3\n4 6\n7 4\n1 2", "0", "10\n6 2\n1 6\n7 3\n3 5\n4 8\n9 7\n5 1\n2 4\n10 9\n8 10"], "notes": null}, "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 def grouped(S: Array[Char]): Array[mutable.Stack[Int]] = {\n val C = Array.fill[mutable.Stack[Int]](27)(mutable.Stack()) // 26\u306b?\u306e\u3071\u3057\u3087\u304c\u5165\u3063\u3066\u3044\u308b\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"}, {"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"} {"nl": {"description": "Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n\u2009-\u20091 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n\u2009=\u20095, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0,\u20091,\u20092,\u2009...,\u2009n\u2009-\u20091. Write a program that determines whether the given puzzle is real or fake.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of gears. The second line contains n digits a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u20091) \u2014 the sequence of active teeth: the active tooth of the i-th gear contains number ai.", "output_spec": "In a single line print \"Yes\" (without the quotes), if the given Stolp's gears puzzle is real, and \"No\" (without the quotes) otherwise.", "sample_inputs": ["3\n1 0 0", "5\n4 2 1 4 3", "4\n0 2 3 1"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "6c65ca365352380052b0c9d693e6d161"} {"nl": {"description": "Zibi is a competitive programming coach. There are $$$n$$$ competitors who want to be prepared well. The training contests are quite unusual\u00a0\u2013 there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the $$$i$$$-th competitor will always have score $$$x_i$$$ when he codes the first task and $$$y_i$$$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are $$$m$$$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 300\\,000$$$, $$$0 \\le m \\le 300\\,000$$$)\u00a0\u2014 the number of participants and the number of pairs of people who will not write a contest together. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \\le x_i, y_i \\le 10^9$$$)\u00a0\u2014 the scores which will the $$$i$$$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $$$x_i$$$ and $$$y_i$$$ same. Each of the next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$)\u00a0\u2014 indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.", "output_spec": "Output $$$n$$$ integers\u00a0\u2014 the sum of scores for all participants in the same order as they appear in the input.", "sample_inputs": ["3 2\n1 2\n2 3\n1 3\n1 2\n2 3", "3 3\n1 2\n2 3\n1 3\n1 2\n2 3\n1 3", "5 3\n-1 3\n2 4\n1 1\n3 5\n2 2\n1 4\n2 3\n3 5"], "sample_outputs": ["3 0 3", "0 0 0", "4 14 4 16 10"], "notes": "NoteIn the first example, there will be only one team consisting of persons $$$1$$$ and $$$3$$$. The optimal strategy for them is to assign the first task to the $$$3$$$-rd person and the second task to the $$$1$$$-st person, this will lead to score equal to $$$1 + 2 = 3$$$.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case..."}, "positive_code": [{"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"}, {"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": "//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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 // \u03a3(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 \u30ce\u30fc\u30c9\u6570\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\u306e\u7bc4\u56f2\u306b\u5206\u5272\u3059\u308b\n *\n * \u4f8b:\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 * \u307e\u3058\u3081\u306aBST\u3064\u304f\u308b\u306e\u5927\u5909\u3060\u304b\u3089lesserThan\u3092\u30ab\u30a6\u30f3\u30c8\u3067\u304d\u308b\u3060\u3051\u306e\u3082\u306e\u3092\u7528\u610f\u3057\u305f\n * java.util.TreeSet\u3058\u3083\u3067\u304d\u306a\u3044\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\u3055\u308c\u305f\u30ec\u30f3\u30b8\u306fn + 1\u500b\u306b\u306a\u308b\n var cnt = 0\n\n /**\n * @param x \u5fc5\u305a\u30ec\u30f3\u30b8\u306e\u4e0a\u9650\u3092\u8ffd\u52a0\u3057\u306a\u3044\u3044\u3051\u306a\u3044\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 // \u30ec\u30f3\u30b8\u306e\u4e0a\u9650\u306e\u5024\u3057\u304b\u5b58\u5728\u3057\u306a\u3044\u306e\u3067\u3001\u3042\u308b\u5024\u3088\u308a\u5c0f\u3055\u3044 = \u3088\u308a\u5c0f\u3055\u3044\u30ec\u30f3\u30b8 \u3068\u7f6e\u304d\u63db\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\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}"}], "negative_code": [], "src_uid": "d0cb479bbe2fca382a439148af77e082"} {"nl": {"description": "Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.One problem with prime numbers is that there are too many of them. Let's introduce the following notation: \u03c0(n)\u00a0\u2014 the number of primes no larger than n, rub(n)\u00a0\u2014 the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones.He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that \u03c0(n)\u2009\u2264\u2009A\u00b7rub(n).", "input_spec": "The input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of A\u00a0(,\u00a0).", "output_spec": "If such maximum number exists, then print it. Otherwise, print \"Palindromic tree is better than splay tree\" (without the quotes).", "sample_inputs": ["1 1", "1 42", "6 4"], "sample_outputs": ["40", "1", "172"], "notes": null}, "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(p, q) = readInts(2)\n\n def isPalindrome(_x: Int) = {\n var rev = 0\n var x = _x\n while (x > 0) {\n rev = rev * 10 + (x % 10)\n x /= 10\n }\n rev == _x\n }\n \n val LIMIT = 20000000\n val prime = Array.fill(LIMIT)(true)\n prime(0) = false\n prime(1) = 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\n var n = 1\n var res = 1\n var cntPrime, cntPal = 0L\n while (cntPrime * q <= cntPal * p || n < LIMIT) {\n if (cntPrime * q <= cntPal * p) res = n - 1\n if (isPalindrome(n)) cntPal += 1\n if (prime(n)) cntPrime += 1\n //println(n, cntPal, cntPrime, cntPrime * q, cntPal * p)\n n += 1\n }\n\n println(res)\n\n}\n"}], "negative_code": [], "src_uid": "e6e760164882b9e194a17663625be27d"} {"nl": {"description": "A sequence $$$a_1, a_2, \\dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i \\ne j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$).For example, the following sequences are good: $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$), $$$[1, 1, 1, 1023]$$$, $$$[7, 39, 89, 25, 89]$$$, $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good.For example, the following sequences are not good: $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two), $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two), $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, \\dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.", "input_spec": "The first line contains the integer $$$n$$$ ($$$1 \\le n \\le 120000$$$) \u2014 the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence.", "sample_inputs": ["6\n4 7 1 5 4 9", "5\n1 2 3 4 5", "1\n16", "4\n1 1 1 1023"], "sample_outputs": ["1", "2", "1", "0"], "notes": "NoteIn the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good."}, "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 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}"}, {"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"} {"nl": {"description": "On a chessboard with a width of $$$10^9$$$ and a height of $$$10^9$$$, the rows are numbered from bottom to top from $$$1$$$ to $$$10^9$$$, and the columns are numbered from left to right from $$$1$$$ to $$$10^9$$$. Therefore, for each cell of the chessboard you can assign the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number and $$$y$$$ is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner\u00a0\u2014 a cell with coordinates $$$(1,1)$$$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely\u00a0\u2014 on the upper side of the field (that is, in any cell that is in the row with number $$$10^9$$$).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number $$$x$$$. Such spells create an infinite blocking line between the columns $$$x$$$ and $$$x+1$$$. Horizontal. Each of these is defined by three numbers $$$x_1$$$, $$$x_2$$$, $$$y$$$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $$$y$$$ and in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $$$(r_0,c_0)$$$ into the cell $$$(r_1,c_1)$$$ only under the condition that $$$r_1 = r_0$$$ or $$$c_1 = c_0$$$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \\le n,m \\le 10^5$$$)\u00a0\u2014 the number of vertical and horizontal spells. Each of the following $$$n$$$ lines contains one integer $$$x$$$ ($$$1 \\le x < 10^9$$$)\u00a0\u2014 the description of the vertical spell. It will create a blocking line between the columns of $$$x$$$ and $$$x+1$$$. Each of the following $$$m$$$ lines contains three integers $$$x_1$$$, $$$x_2$$$ and $$$y$$$ ($$$1 \\le x_{1} \\le x_{2} \\le 10^9$$$, $$$1 \\le y < 10^9$$$)\u00a0\u2014 the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $$$y$$$, in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.", "output_spec": "In a single line print one integer\u00a0\u2014 the minimum number of spells the rook needs to remove so it can get from the cell $$$(1,1)$$$ to at least one cell in the row with the number $$$10^9$$$", "sample_inputs": ["2 3\n6\n8\n1 5 6\n1 9 4\n2 4 2", "1 3\n4\n1 5 3\n1 9 4\n4 6 6", "0 2\n1 1000000000 4\n1 1000000000 2", "0 0", "2 3\n4\n6\n1 4 3\n1 5 2\n1 6 5"], "sample_outputs": ["1", "1", "2", "0", "2"], "notes": "NoteIn the first sample, in order for the rook return home, it is enough to remove the second horizontal spell. Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell. Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them. Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything.In the fifth example, we can remove the first vertical and third horizontal spells. Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. "}, "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 // \u4e00\u756a\u5de6\u304c\u7a7a\u3044\u3066\u3044\u308b\n else if (aLine.to == MAX) Integer.MAX_VALUE // \u5168\u90e8\u57cb\u307e\u3063\u3066\u308b\n else {\n lowerBound(V, aLine.to + 1) \n }\n }\n\n val L = Array.ofDim[Int](H.size) // \u53ef\u5909\u3060\u3068\u9762\u5012\u306a\u306e\u30670\u3082\u3044\u308c\u308b\u3053\u3068\u306b\u3059\u308b\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 // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\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 * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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}"}, {"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 // \u8981\u306fcountLe\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 * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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}"}], "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"} {"nl": {"description": "Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109)\u00a0\u2014 the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the initial prices.", "output_spec": "Print the only line containing the minimum number of seconds needed for prices to become equal, of \u00ab-1\u00bb if it is impossible.", "sample_inputs": ["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"], "sample_outputs": ["3", "-1", "2999999997"], "notes": "NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999\u2009*\u20093\u2009=\u20092999999997 seconds. We can note that this is the minimum possible time."}, "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"}, {"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"}], "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"} {"nl": {"description": "One day Nikita found the string containing letters \"a\" and \"b\" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters \"a\" and the 2-nd contains only letters \"b\".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?", "input_spec": "The first line contains a non-empty string of length not greater than 5\u2009000 containing only lowercase English letters \"a\" and \"b\". ", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible size of beautiful string Nikita can get.", "sample_inputs": ["abba", "bab"], "sample_outputs": ["4", "2"], "notes": "NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of \"b\" to make it beautiful."}, "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"}, {"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"}], "negative_code": [], "src_uid": "c768f3e52e562ae1fd47502a60dbadfe"} {"nl": {"description": "This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.", "input_spec": "First line of the input contains two integers n and m(2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of points and the number segments on the picture respectively. Then follow m lines, each containing two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi)\u00a0\u2014 the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.", "output_spec": "Print the maximum possible value of the hedgehog's beauty.", "sample_inputs": ["8 6\n4 5\n3 5\n2 5\n1 2\n2 8\n6 7", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"], "sample_outputs": ["9", "12"], "notes": "NoteThe picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3\u00b73\u2009=\u20099."}, "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.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"}, {"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"} {"nl": {"description": "You invited $$$n$$$ guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the $$$i$$$-th guest wants to have a least $$$l_i$$$ free chairs to the left of his chair, and at least $$$r_i$$$ free chairs to the right. The \"left\" and \"right\" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the $$$l_i$$$ chairs to his left and $$$r_i$$$ chairs to his right may overlap.What is smallest total number of chairs you have to use?", "input_spec": "First line contains one integer $$$n$$$ \u00a0\u2014 number of guests, ($$$1 \\leqslant n \\leqslant 10^5$$$). Next $$$n$$$ lines contain $$$n$$$ pairs of space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \\leqslant l_i, r_i \\leqslant 10^9$$$).", "output_spec": "Output a single integer\u00a0\u2014 the smallest number of chairs you have to use.", "sample_inputs": ["3\n1 1\n1 1\n1 1", "4\n1 2\n2 1\n3 5\n5 3", "1\n5 6"], "sample_outputs": ["6", "15", "7"], "notes": "NoteIn the second sample the only optimal answer is to use two circles: a circle with $$$5$$$ chairs accomodating guests $$$1$$$ and $$$2$$$, and another one with $$$10$$$ chairs accomodationg guests $$$3$$$ and $$$4$$$.In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7."}, "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 L, R = Array.ofDim[Int](N)\n rep(N) { i =>\n L(i) = ni()\n R(i) = ni()\n }\n\n radixSort(L)\n radixSort(R)\n\n var ans = 0L\n ans += N\n rep(N) { i =>\n ans += max(L(i), R(i))\n }\n out.println(ans)\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): 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 L, R = Array.ofDim[Int](N)\n rep(N) { i =>\n L(i) = ni()\n R(i) = ni()\n }\n\n val ans = max(sumL(L), sumL(R)) + 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}"}], "src_uid": "2090c7382ef9bc8dfd9ca1fc1743d3a7"} {"nl": {"description": "Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i\u2009+\u20091, i\u2009+\u20092, i\u2009+\u20093 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i\u2009=\u2009n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i\u2009=\u20093, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4,\u20091,\u20092,\u20093,\u20094. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x \u2014 the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes.", "input_spec": "The first line of the input contains two integers n and x (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009x\u2009\u2264\u2009n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an, where integer ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009109, ax\u2009\u2260\u20090) represents the number of balls in the box with index i after Vasya completes all the actions. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.", "sample_inputs": ["4 4\n4 3 1 6", "5 2\n3 2 0 2 7", "3 3\n2 3 1"], "sample_outputs": ["3 2 5 4", "2 1 4 1 6", "1 2 3"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "\u00abPolygon\u00bb is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the amount of previously added tests. The second line contains n distinct integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20093000) \u2014 indexes of these tests.", "output_spec": "Output the required default value for the next test index.", "sample_inputs": ["3\n1 7 2"], "sample_outputs": ["3"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "You have a board represented as a grid with $$$2 \\times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \\times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \\times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 3000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$ and $$$k_2$$$ ($$$1 \\le n \\le 1000$$$; $$$0 \\le k_1, k_2 \\le n$$$). The second line of each test case contains two integers $$$w$$$ and $$$b$$$ ($$$0 \\le w, b \\le n$$$).", "output_spec": "For each test case, print YES if it's possible to place all $$$w + b$$$ dominoes on the board and NO, otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["5\n1 0 1\n1 0\n1 1 1\n0 0\n3 0 0\n1 3\n4 3 1\n2 2\n5 4 3\n3 1"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES"], "notes": "NoteIn the first test case, $$$n = 1$$$, $$$k_1 = 0$$$ and $$$k_2 = 1$$$. It means that $$$2 \\times 1$$$ board has black cell $$$(1, 1)$$$ and white cell $$$(2, 1)$$$. So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size $$$2 \\times 1$$$, but both cell are white. Since $$$w = 0$$$ and $$$b = 0$$$, so you can place $$$0 + 0 = 0$$$ dominoes on the board.In the third test case, board $$$2 \\times 3$$$, but fully colored in black (since $$$k_1 = k_2 = 0$$$), so you can't place any white domino.In the fourth test case, cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, and $$$(2, 1)$$$ are white and other cells are black. You can place $$$2$$$ white dominoes at positions $$$((1, 1), (2, 1))$$$ and $$$((1, 2), (1, 3))$$$ and $$$2$$$ black dominoes at positions $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$."}, "positive_code": [{"source_code": "object cf1499a {\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 l1 = readInts()\n\t\t\tval l2 = readInts()\n\t\t\tval n = l1(0) // row length (columns)\n\t\t\tval k1 = l1(1) // whites on r1\n\t\t\tval k2 = l1(2) // whites on r2\n\t\t\tval w\t=\tl2(0)\n\t\t\tval b = l2(1)\n\n\t\t\tval (mink, maxk) = if (k1 < k2) (k1, k2) else (k2, k1)\n\t\t\tval wfits = (w <= (mink + (maxk-mink)/2))\n\t\t\tlazy val bfits = (b <= (n-maxk + (maxk-mink)/2))\n\t\t\tif (wfits && bfits)\n\t\t\t\tprintln(\"YES\")\n\t\t\telse\n\t\t\t\tprintln (\"NO\")\n }\n }\n}"}], "negative_code": [], "src_uid": "26354d2628f26eb2eff9432bd46400d5"} {"nl": {"description": "Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $$$1$$$. If he manages to finish the level successfully then the number of clears increases by $$$1$$$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats $$$n$$$ times and wrote down $$$n$$$ pairs of integers \u2014 $$$(p_1, c_1), (p_2, c_2), \\dots, (p_n, c_n)$$$, where $$$p_i$$$ is the number of plays at the $$$i$$$-th moment of time and $$$c_i$$$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.", "input_spec": "The first line contains a single integer $$$T$$$ $$$(1 \\le T \\le 500)$$$ \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of moments of time Polycarp peeked at the stats. Each of the next $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \\le p_i, c_i \\le 1000$$$) \u2014 the number of plays and the number of clears of the level at the $$$i$$$-th moment of time. Note that the stats are given in chronological order.", "output_spec": "For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print \"YES\". Otherwise, print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["6\n3\n0 0\n1 1\n1 2\n2\n1 0\n1000 3\n4\n10 1\n15 2\n10 2\n15 2\n1\n765 432\n2\n4 4\n4 3\n5\n0 0\n1 0\n1 0\n1 0\n1 0"], "sample_outputs": ["NO\nYES\nNO\nYES\nNO\nYES"], "notes": "NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations: Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation: $$$x = 0$$$, $$$y = 6$$$; $$$x = 0$$$, $$$y = 8$$$; $$$x = -1$$$, $$$y = 7$$$; $$$x = 1$$$, $$$y = 7$$$. Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation: $$$x = -1$$$, $$$y = 6$$$; $$$x = 1$$$, $$$y = 8$$$. Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \\le x, y \\le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum amount of dollars you have to spend.", "sample_inputs": ["2\n1 3\n391 555\n0 0\n9 4"], "sample_outputs": ["1337\n0"], "notes": "NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money."}, "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(_.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"}, {"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"} {"nl": {"description": "You have a string $$$s$$$ \u2014 a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' \u2014 move one cell up; 'S' \u2014 move one cell down; 'A' \u2014 move one cell left; 'D' \u2014 move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \\text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \\times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \\le |s| \\le 2 \\cdot 10^5$$$, $$$s_i \\in \\{\\text{W}, \\text{A}, \\text{S}, \\text{D}\\}$$$) \u2014 the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.", "sample_inputs": ["3\nDSAWWAW\nD\nWA"], "sample_outputs": ["8\n2\n4"], "notes": "NoteIn the first query you have to get string $$$\\text{DSAWW}\\underline{D}\\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$."}, "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[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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val S = ns()\n val X, Y = Array.ofDim[Int](S.length)\n REP(S.length) { i =>\n S(i) match {\n case 'A' => X(i) -= 1\n case 'D' => X(i) += 1\n case 'S' => Y(i) -= 1\n case 'W' => Y(i) += 1\n }\n }\n\n val cumX = cumSum(X)\n val cumY = cumSum(Y)\n\n debug(cumX)\n debug(cumY)\n\n val x = cumX.max - cumX.min + 1\n val y = cumY.max - cumY.min + 1\n\n debug(s\"x:$x y:$y\")\n\n var ans = 1e18.toLong\n val minT = new SegmentTree(cumX.length, 0)(min)\n val maxT = new SegmentTree(cumX.length, 0)(max)\n def traverse(A: Array[Int], z: Long, isMinus: Boolean) = {\n REP(A.length) { i =>\n minT.update(i, A(i))\n maxT.update(i, A(i))\n var ms = minT.query(0, A.length)\n var mx = maxT.query(0, A.length)\n if (isMinus) ms = min(ms, A(i) - 1)\n if (!isMinus) mx = max(mx, A(i) + 1)\n val xx = (mx - ms + 1).toLong\n ans = min(ans, xx * z)\n }\n }\n\n def setXTree(d: Int): Unit = {\n REP(cumX.length) { i =>\n minT.update(i, cumX(i) + d)\n maxT.update(i, cumX(i) + d)\n }\n }\n setXTree(-1)\n traverse(cumX, y, isMinus = true)\n\n setXTree(1)\n traverse(cumX, y, isMinus = false)\n\n def setYTree(d: Int): Unit = {\n REP(cumY.length) { i =>\n minT.update(i, cumY(i) + d)\n maxT.update(i, cumY(i) + d)\n }\n }\n setYTree(-1)\n traverse(cumY, x, isMinus = true)\n\n setYTree(1)\n traverse(cumY, x, isMinus = false)\n\n out.println(ans)\n }\n }\n\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\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[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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val S = ns()\n val X, Y = Array.ofDim[Int](S.length)\n REP(S.length) { i =>\n S(i) match {\n case 'A' => X(i) -= 1\n case 'D' => X(i) += 1\n case 'S' => Y(i) -= 1\n case 'W' => Y(i) += 1\n }\n }\n\n val cumX = cumSum(X)\n val cumY = cumSum(Y)\n\n debug(cumX)\n debug(cumY)\n\n val x = cumX.max - cumX.min + 1\n val y = cumY.max - cumY.min + 1\n\n debug(s\"x:$x y:$y\")\n\n var ans = 1e18.toLong\n val minT = new SegmentTree(cumX.length, 0)(min)\n val maxT = new SegmentTree(cumX.length, 0)(max)\n def traverse(A: Array[Int], isMinus: Boolean) = {\n REP(A.length) { i =>\n minT.update(i, A(i))\n maxT.update(i, A(i))\n var ms = minT.query(0, A.length)\n var mx = maxT.query(0, A.length)\n if (isMinus) ms = min(ms, A(i) - 1)\n if (!isMinus) mx = max(mx, A(i) + 1)\n val xx = (mx - ms + 1).toLong\n debug(s\"xx:$xx y:$y\")\n ans = min(ans, xx * y)\n }\n }\n\n def setXTree(d: Int): Unit = {\n REP(cumX.length) { i =>\n minT.update(i, cumX(i) + d)\n maxT.update(i, cumX(i) + d)\n }\n }\n setXTree(-1)\n traverse(cumX, isMinus = true)\n\n setXTree(1)\n traverse(cumX, isMinus = false)\n\n def setYTree(d: Int): Unit = {\n REP(cumY.length) { i =>\n minT.update(i, cumY(i) + d)\n maxT.update(i, cumY(i) + d)\n }\n }\n setYTree(-1)\n traverse(cumY, isMinus = true)\n\n setYTree(1)\n traverse(cumY, isMinus = false)\n\n out.println(ans)\n }\n }\n\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\n }\n }\n}"}], "src_uid": "a4f183775262fdc42dc5fc621c196ec9"} {"nl": {"description": "Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai \u2009\u2264\u2009 bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!", "input_spec": "The first line of the input contains one integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 number of cola cans. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 volume of remaining cola in cans. The third line contains n space-separated integers that b1,\u2009b2,\u2009...,\u2009bn (ai\u2009\u2264\u2009bi\u2009\u2264\u2009109) \u2014 capacities of the cans.", "output_spec": "Print \"YES\" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print \"NO\" (without quotes). You can print each letter in any case (upper or lower).", "sample_inputs": ["2\n3 5\n3 6", "3\n6 8 9\n6 10 12", "5\n0 0 5 0 0\n1 1 8 10 5", "4\n4 1 0 3\n5 2 2 3"], "sample_outputs": ["YES", "NO", "YES", "YES"], "notes": "NoteIn the first sample, there are already 2 cans, so the answer is \"YES\"."}, "positive_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).max(b), maxbs(1)).sorted\n }\n println(if (maxbs.sum >= A.map(BigInt(_)).sum) \"YES\" else \"NO\")\n}\n"}, {"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"} {"nl": {"description": "In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are $$$n$$$ residents and $$$n$$$ cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th cat is living in the house of $$$i$$$-th resident.Each Catowice resident is in friendship with several cats, including the one living in his house. In order to conduct a contest, at least one jury member is needed and at least one cat contestant is needed. Of course, every jury member should know none of the contestants. For the contest to be successful, it's also needed that the number of jury members plus the number of contestants is equal to $$$n$$$.Please help Catowice residents to select the jury and the contestants for the upcoming competition, or determine that it's impossible to do.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100\\,000$$$), the number of test cases. Then description of $$$t$$$ test cases follow, where each description is as follows: The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le m \\le 10^6$$$), the number of Catowice residents and the number of friendship pairs between residents and cats. Each of the next $$$m$$$ lines contains integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$), denoting that $$$a_i$$$-th resident is acquaintances with $$$b_i$$$-th cat. It's guaranteed that each pair of some resident and some cat is listed at most once. It's guaranteed, that for every $$$i$$$ there exists a pair between $$$i$$$-th resident and $$$i$$$-th cat. Different test cases are separated with an empty line. It's guaranteed, that the sum of $$$n$$$ over all test cases is at most $$$10^6$$$ and that the sum of $$$m$$$ over all test cases is at most $$$10^6$$$.", "output_spec": "For every test case print: \"No\", if it's impossible to select the jury and contestants. Otherwise print \"Yes\".In the second line print two integers $$$j$$$ and $$$p$$$ ($$$1 \\le j$$$, $$$1 \\le p$$$, $$$j + p = n$$$)\u00a0\u2014 the number of jury members and the number of contest participants.In the third line print $$$j$$$ distinct integers from $$$1$$$ to $$$n$$$, the indices of the residents forming a jury.In the fourth line print $$$p$$$ distinct integers from $$$1$$$ to $$$n$$$, the indices of the cats, which will participate in the contest.In case there are several correct answers, print any of them. ", "sample_inputs": ["4\n3 4\n1 1\n2 2\n3 3\n1 3\n\n3 7\n1 1\n1 2\n1 3\n2 2\n3 1\n3 2\n3 3\n\n1 1\n1 1\n\n2 4\n1 1\n1 2\n2 1\n2 2"], "sample_outputs": ["Yes\n2 1\n1 3 \n2 \nYes\n1 2\n2 \n1 3 \nNo\nNo"], "notes": "NoteIn the first test case, we can select the first and the third resident as a jury. Both of them are not acquaintances with a second cat, so we can select it as a contestant.In the second test case, we can select the second resident as a jury. He is not an acquaintances with a first and a third cat, so they can be selected as contestants.In the third test case, the only resident is acquaintances with the only cat, so they can't be in the contest together. So it's not possible to make a contest with at least one jury and at least one cat.In the fourth test case, each resident is acquaintances with every cat, so it's again not possible to make a contest with at least one jury and at least one cat."}, "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 class GraphDfs(g: Array[Array[Int]]) {\n private[this] val n = g.length\n private[this] val stack = Array.ofDim[Int](n)\n private[this] var s = 0\n private[this] val ix = Array.ofDim[Int](n)\n private[this] val used = Array.ofDim[Boolean](n)\n\n def apply(rt: Int = 0, enter: Int => Unit, exit: Int => Unit): Unit = {\n stack(s) = rt\n used(rt) = true\n s += 1\n\n while(s > 0) {\n val v = stack(s-1)\n val es = g(v)\n\n if (ix(v) == 0) {\n // dfs\u306e\u958b\u59cb\u90e8\u5206\n enter(v)\n }\n\n if (ix(v) == es.length) {\n // dfs\u306e\u7d42\u4e86\u90e8\u5206\n exit(v)\n s -= 1\n }\n else {\n val u = es(ix(v))\n if (!used(u) && (s == 1 || u != stack(s-2))) {\n stack(s) = u\n used(u) = true\n s += 1\n }\n ix(v) += 1\n }\n }\n }\n\n def getUsed: Array[Boolean] = used\n }\n\n def stronglyConnectedComponents(g1: Array[Array[Int]], g2: Array[Array[Int]]): (Int, Array[Int]) = {\n val n = g1.length\n val vs = Array.ofDim[Int](n)\n var p = 0\n val dfs1 = new GraphDfs(g1)\n\n REP(n) { v =>\n if (!dfs1.getUsed(v)) {\n dfs1(v, _ => Unit, v => {\n vs(p) = v\n p += 1\n })\n }\n }\n val comp = Array.ofDim[Int](n)\n var k = 0\n val dfs2 = new GraphDfs(g2)\n REP_r(n) { i =>\n val v = vs(i)\n if (!dfs2.getUsed(v)) {\n dfs2(v, _ => Unit, v => {\n comp(v) = k\n })\n k += 1\n }\n }\n (k, comp)\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 => // \u9806\u5e8f\u7dad\u6301\u3059\u308b\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n }\n t\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val A, B = Array.ofDim[Int](m - n)\n var p = 0\n REP(m) { _ =>\n val a, b = ni() - 1\n if (a != b) {\n A(p) = a\n B(p) = b\n p += 1\n }\n }\n val g = packDGraph(n, A, B)\n val g1 = packDGraph(n, B, A)\n val (k, comp) = stronglyConnectedComponents(g, g1)\n debug(comp)\n if (k == 1) out.println(\"No\")\n else {\n val j = comp.count(_ == k - 1)\n out.println(\"Yes\")\n out.println(s\"$j ${n - j}\")\n val juries, participants = ArrayBuffer[Int]()\n REP(n) { i =>\n if (comp(i) == k - 1) juries += i + 1\n else participants += i + 1\n }\n out.println(juries.mkString(\" \"))\n out.println(participants.mkString(\" \"))\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "f91197e474bdc3f2b881d556a330e36b"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$. Array is good if for each pair of indexes $$$i < j$$$ the condition $$$j - a_j \\ne i - a_i$$$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if $$$a = [1, 1, 3, 5]$$$, then shuffled arrays $$$[1, 3, 5, 1]$$$, $$$[3, 5, 1, 1]$$$ and $$$[5, 3, 1, 1]$$$ are good, but shuffled arrays $$$[3, 1, 5, 1]$$$, $$$[1, 1, 3, 5]$$$ and $$$[1, 1, 5, 3]$$$ aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 100$$$).", "output_spec": "For each test case print the shuffled version of the array $$$a$$$ which is good.", "sample_inputs": ["3\n1\n7\n4\n1 1 3 5\n6\n3 2 1 5 6 4"], "sample_outputs": ["7\n1 5 1 3\n2 4 6 1 3 5"], "notes": null}, "positive_code": [{"source_code": "object _1312B 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\n def isOkay(arr: Seq[Int]) = arr.zipWithIndex.map{case (i, a) => i - a }.distinct.length == arr.length\n\n val array = io.read[Seq[Int]]\n val ans = if (isOkay(array)) array else {\n val sorted = array.sorted\n if (isOkay(sorted)) sorted else sorted.reverse.ensuring(isOkay _)\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"}], "negative_code": [], "src_uid": "1d89df4153d70087d212b711852eba5f"} {"nl": {"description": "After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say \"aab\" and \"abcac\", and you concatenate them into \"aababcac\", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation \"aabccbaa\"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.", "input_spec": "The first line contains a positive integer $$$N$$$ ($$$1 \\le N \\le 100\\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z')\u00a0\u2014 an element of the input array. The total number of characters in the input array will be less than $$$1\\,000\\,000$$$.", "output_spec": "Output one number, representing how many palindrome pairs there are in the array.", "sample_inputs": ["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"], "sample_outputs": ["1", "6"], "notes": "NoteThe first example: aa $$$+$$$ bb $$$\\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\\to$$$ aeddea "}, "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 var ans = 0L\n val set = mutable.Map[Int, Int]() withDefaultValue 0\n rep(N) { _ =>\n var bit = 0\n val s = ns()\n rep(s.length) { i =>\n val j = s(i) - 'a'\n val k = 1 << j\n bit ^= k\n }\n\n ans += set(bit) // \u5168\u90e8\u5076\u6570\n\n // \uff11\u3064\u3060\u3051\u5947\u6570\n rep(26) { i =>\n ans += set(bit ^ 1 << i)\n }\n\n set(bit) = set(bit) + 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}"}], "negative_code": [], "src_uid": "2475df43379ffd450fa661927ae3b734"} {"nl": {"description": "Alice and Bob are playing yet another card game. This time the rules are the following. There are $$$n$$$ cards lying in a row in front of them. The $$$i$$$-th card has value $$$a_i$$$. First, Alice chooses a non-empty consecutive segment of cards $$$[l; r]$$$ ($$$l \\le r$$$). After that Bob removes a single card $$$j$$$ from that segment $$$(l \\le j \\le r)$$$. The score of the game is the total value of the remaining cards on the segment $$$(a_l + a_{l + 1} + \\dots + a_{j - 1} + a_{j + 1} + \\dots + a_{r - 1} + a_r)$$$. In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is $$$0$$$.Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.What segment should Alice choose so that the score is maximum possible? Output the maximum score.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of cards. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-30 \\le a_i \\le 30$$$) \u2014 the values on the cards.", "output_spec": "Print a single integer \u2014 the final score of the game.", "sample_inputs": ["5\n5 -2 10 -1 4", "8\n5 2 5 3 -30 -30 6 9", "3\n-10 6 -15"], "sample_outputs": ["6", "10", "0"], "notes": "NoteIn the first example Alice chooses a segment $$$[1;5]$$$ \u2014 the entire row of cards. Bob removes card $$$3$$$ with the value $$$10$$$ from the segment. Thus, the final score is $$$5 + (-2) + (-1) + 4 = 6$$$.In the second example Alice chooses a segment $$$[1;4]$$$, so that Bob removes either card $$$1$$$ or $$$3$$$ with the value $$$5$$$, making the answer $$$5 + 2 + 3 = 10$$$.In the third example Alice can choose any of the segments of length $$$1$$$: $$$[1;1]$$$, $$$[2;2]$$$ or $$$[3;3]$$$. Bob removes the only card, so the score is $$$0$$$. If Alice chooses some other segment then the answer will be less than $$$0$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "This is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define $$$x$$$ as the distance to Mars. Unfortunately, Natasha does not know $$$x$$$. But it is known that $$$1 \\le x \\le m$$$, where Natasha knows the number $$$m$$$. Besides, $$$x$$$ and $$$m$$$ are positive integers.Natasha can ask the rocket questions. Every question is an integer $$$y$$$ ($$$1 \\le y \\le m$$$). The correct answer to the question is $$$-1$$$, if $$$x<y$$$, $$$0$$$, if $$$x=y$$$, and $$$1$$$, if $$$x>y$$$. But the rocket is broken\u00a0\u2014 it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $$$t$$$, then, if the rocket answers this question correctly, then it will answer $$$t$$$, otherwise it will answer $$$-t$$$.In addition, the rocket has a sequence $$$p$$$ of length $$$n$$$. Each element of the sequence is either $$$0$$$ or $$$1$$$. The rocket processes this sequence in the cyclic order, that is $$$1$$$-st element, $$$2$$$-nd, $$$3$$$-rd, $$$\\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$\\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$\\ldots$$$. If the current element is $$$1$$$, the rocket answers correctly, if $$$0$$$\u00a0\u2014 lies. Natasha doesn't know the sequence $$$p$$$, but she knows its length\u00a0\u2014 $$$n$$$.You can ask the rocket no more than $$$60$$$ questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer $$$0$$$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).", "input_spec": "The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \\le m \\le 10^9$$$, $$$1 \\le n \\le 30$$$)\u00a0\u2014 the maximum distance to Mars and the number of elements in the sequence $$$p$$$.", "output_spec": null, "sample_inputs": ["5 2\n1\n-1\n-1\n1\n0"], "sample_outputs": ["1\n2\n4\n5\n3"], "notes": "NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to $$$3$$$, Natasha knows that it does not exceed $$$5$$$, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query ($$$1$$$) the correct answer is $$$1$$$, the rocket answered correctly: $$$1$$$;on the second query ($$$2$$$) the correct answer is $$$1$$$, the rocket answered incorrectly: $$$-1$$$;on the third query ($$$4$$$) the correct answer is $$$-1$$$, the rocket answered correctly: $$$-1$$$;on the fourth query ($$$5$$$) the correct answer is $$$-1$$$, the rocket answered incorrectly: $$$1$$$;on the fifth query ($$$3$$$) the correct and incorrect answer is $$$0$$$."}, "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 \u306a\u306e\u3067\u30010\u3067\u306a\u3051\u308c\u3070 x > y => 1 \u304c\u8fd4\u308b\u306f\u305a\u3002\n // -1\u304c\u304f\u308b\u304b\u3069\u3046\u304b\u3067p\u3092\u5224\u5b9a\u3059\u308b\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 // \u7d50\u679c\u3092\u51fa\u529b\u3057\u306a\u304f\u3066\u3044\u3044\u30020\u304c\u5e30\u3063\u305f\u6642\u70b9\u3067\u7d42\u308f\u308a\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}"}, {"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}"}], "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 \u306a\u306e\u3067\u30010\u3067\u306a\u3051\u308c\u3070 x > y => 1 \u304c\u8fd4\u308b\u306f\u305a\u3002\n // -1\u304c\u304f\u308b\u304b\u3069\u3046\u304b\u3067p\u3092\u5224\u5b9a\u3059\u308b\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 // \u7d50\u679c\u3092\u51fa\u529b\u3057\u306a\u304f\u3066\u3044\u3044\u30020\u304c\u5e30\u3063\u305f\u6642\u70b9\u3067\u7d42\u308f\u308a\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 \u306a\u306e\u3067\u30010\u3067\u306a\u3051\u308c\u3070 x > y => 1 \u304c\u8fd4\u308b\u306f\u305a\u3002\n // -1\u304c\u304f\u308b\u304b\u3069\u3046\u304b\u3067p\u3092\u5224\u5b9a\u3059\u308b\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 // \u7d50\u679c\u3092\u51fa\u529b\u3057\u306a\u304f\u3066\u3044\u3044\u30020\u304c\u5e30\u3063\u305f\u6642\u70b9\u3067\u7d42\u308f\u308a\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"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \\dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^9$$$; $$$1 \\le k \\le 10^9$$$).", "output_spec": "For each test case, print one integer\u00a0\u2014 the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \\dots + a_n)$$$ is divisible by $$$k$$$. ", "sample_inputs": ["4\n1 5\n4 3\n8 8\n8 17"], "sample_outputs": ["5\n2\n1\n3"], "notes": "NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$."}, "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: 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"}, {"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"} {"nl": {"description": "This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \\le a_i \\le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i.\u2009e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of queries. Each query is represented by two lines. The first line of each query contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of candies. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy in the box. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each query print one integer \u2014 the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.", "sample_inputs": ["3\n8\n1 4 8 4 5 6 3 8\n16\n2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1\n9\n2 2 4 4 4 7 7 7 7"], "sample_outputs": ["3\n10\n9"], "notes": "NoteIn the first query, you can prepare a gift with two candies of type $$$8$$$ and one candy of type $$$5$$$, totalling to $$$3$$$ candies.Note that this is not the only possible solution \u2014 taking two candies of type $$$4$$$ and one candy of type $$$6$$$ is also valid."}, "positive_code": [{"source_code": "object _1183D 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[Seq[Int]]]\n val ans = queries map {candies =>\n val sizes = candies\n .groupBy(identity)\n .values\n .map(_.size)\n .toList\n .sorted(desc[Int])\n sum(sizes, upper = Int.MaxValue, acc = 0)\n }\n\n io.writeLines(ans)\n }\n\n @tailrec\n def sum(as: List[Int], upper: Int, acc: Long): Long = {\n as match {\n case Nil => acc\n case a1 :: _ if a1 <= 0 => acc\n case a1 :: at if a1 >= upper => sum((upper - 1) :: at, upper, acc)\n case a1 :: at => sum(at, a1, acc + a1)\n }\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 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": "a00d831da539c69d571d9720fd94eee1"} {"nl": {"description": "You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \\times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.", "input_spec": "The first line of input contain 2 integer numbers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$) \u2014 the length of the platform and the number of the squares. The next line contain $$$m$$$ integer numbers $$$c_1, c_2, \\dots, c_m$$$ ($$$1 \\le c_i \\le n$$$) \u2014 column in which $$$i$$$-th square will appear.", "output_spec": "Print one integer \u2014 the amount of points you will receive.", "sample_inputs": ["3 9\n1 1 2 2 2 3 1 2 3"], "sample_outputs": ["2"], "notes": "NoteIn the sample case the answer will be equal to $$$2$$$ because after the appearing of $$$6$$$-th square will be removed one row (counts of the squares on the platform will look like $$$[2~ 3~ 1]$$$, and after removing one row will be $$$[1~ 2~ 0]$$$).After the appearing of $$$9$$$-th square counts will be $$$[2~ 3~ 1]$$$, and after removing one row it will look like $$$[1~ 2~ 0]$$$.So the answer will be equal to $$$2$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Fishingprince is playing with an array $$$[a_1,a_2,\\dots,a_n]$$$. He also has a magic number $$$m$$$.He can do the following two operations on it: Select $$$1\\le i\\le n$$$ such that $$$a_i$$$ is divisible by $$$m$$$ (that is, there exists an integer $$$t$$$ such that $$$m \\cdot t = a_i$$$). Replace $$$a_i$$$ with $$$m$$$ copies of $$$\\frac{a_i}{m}$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[2,3]$$$ and $$$i=1$$$, $$$a$$$ changes into $$$[1,1,3]$$$. Select $$$1\\le i\\le n-m+1$$$ such that $$$a_i=a_{i+1}=\\dots=a_{i+m-1}$$$. Replace these $$$m$$$ elements with a single $$$m \\cdot a_i$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[3,2,2,3]$$$ and $$$i=2$$$, $$$a$$$ changes into $$$[3,4,3]$$$. Note that the array length might change during the process. The value of $$$n$$$ above is defined as the current length of the array (might differ from the $$$n$$$ in the input).Fishingprince has another array $$$[b_1,b_2,\\dots,b_k]$$$. Please determine if he can turn $$$a$$$ into $$$b$$$ using any number (possibly zero) of operations.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\\le n\\le 5\\cdot 10^4$$$, $$$2\\le m\\le 10^9$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1\\le a_i\\le 10^9$$$). The third line of each test case contains one integer $$$k$$$ ($$$1\\le k\\le 5\\cdot 10^4$$$). The fourth line of each test case contains $$$k$$$ integers $$$b_1,b_2,\\ldots,b_k$$$ ($$$1\\le b_i\\le 10^9$$$). It is guaranteed that the sum of $$$n+k$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each testcase, print Yes if it is possible to turn $$$a$$$ into $$$b$$$, and No otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["5\n\n5 2\n\n1 2 2 4 2\n\n4\n\n1 4 4 2\n\n6 2\n\n1 2 2 8 2 2\n\n2\n\n1 16\n\n8 3\n\n3 3 3 3 3 3 3 3\n\n4\n\n6 6 6 6\n\n8 3\n\n3 9 6 3 12 12 36 12\n\n16\n\n9 3 2 2 2 3 4 12 4 12 4 12 4 12 4 4\n\n8 3\n\n3 9 6 3 12 12 36 12\n\n7\n\n12 2 4 3 4 12 56"], "sample_outputs": ["Yes\nYes\nNo\nYes\nNo"], "notes": "NoteIn the first test case of the sample, we can do the second operation with $$$i=2$$$: $$$[1,\\color{red}{2,2},4,2]\\to [1,\\color{red}{4},4,2]$$$.In the second testcase of the sample, we can: do the second operation with $$$i=2$$$: $$$[1,\\color{red}{2,2},8,2,2]\\to [1,\\color{red}{4},8,2,2]$$$. do the second operation with $$$i=4$$$: $$$[1,4,8,\\color{red}{2,2}]\\to [1,4,8,\\color{red}{4}]$$$. do the first operation with $$$i=3$$$: $$$[1,4,\\color{red}{8},4]\\to [1,4,\\color{red}{4,4},4]$$$. do the second operation with $$$i=2$$$: $$$[1,\\color{red}{4,4},4,4]\\to [1,\\color{red}{8},4,4]$$$. do the second operation with $$$i=3$$$: $$$[1,8,\\color{red}{4,4}]\\to [1,8,\\color{red}{8}]$$$. do the second operation with $$$i=2$$$: $$$[1,\\color{red}{8,8}]\\to [1,\\color{red}{16}]$$$."}, "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 tokenizer = new StringTokenizer(input.readLine())\r\n val A = ArrayBuffer.empty[Array[Long]]\r\n var hold = 0\r\n for (i <- 0 until n) {\r\n var kk = 0\r\n var new1 = tokenizer.nextToken().toInt\r\n while (new1 % m == 0){\r\n new1 = new1 / m\r\n kk+=1\r\n }\r\n if (i == 0) {\r\n A += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n else if (new1 == hold) {\r\n A.last(1)+= pow(m,kk).toInt\r\n }\r\n else {\r\n A += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n }\r\n val B = ArrayBuffer.empty[Array[Long]]\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val k = tokenizer.nextToken().toInt\r\n hold = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until k) {\r\n var kk = 0\r\n var new1 = tokenizer.nextToken().toInt\r\n while (new1 % m == 0){\r\n new1 = new1 / m\r\n kk+=1\r\n }\r\n if (i == 0) {\r\n B += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n else if (new1 == hold) {\r\n B.last(1)+= pow(m,kk).toInt\r\n }\r\n else {\r\n B += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n }\r\n if ((A.toList).map(_.toList) == (B.toList).map(_.toList)) {\r\n output.println(\"YES\")\r\n }\r\n else {\r\n output.println(\"NO\")\r\n }\r\n }\r\n }\r\n}"}], "negative_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 tokenizer = new StringTokenizer(input.readLine())\r\n val A = ArrayBuffer.empty[Array[Long]]\r\n var hold = 0\r\n for (i <- 0 until n) {\r\n var kk = 0\r\n var new1 = tokenizer.nextToken().toInt\r\n while (new1 % m == 0){\r\n new1 = new1 / m\r\n kk+=1\r\n }\r\n if (i == 0) {\r\n A += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n else if (new1 == hold) {\r\n A.last(1)+= pow(m,kk).toInt\r\n }\r\n else {\r\n A += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n }\r\n val B = ArrayBuffer.empty[Array[Long]]\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val k = tokenizer.nextToken().toInt\r\n hold = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until k) {\r\n var kk = 0\r\n var new1 = tokenizer.nextToken().toInt\r\n while (new1 % m == 0){\r\n new1 = new1 / m\r\n kk+=1\r\n }\r\n if (i == 0) {\r\n B += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n else if (new1 == hold) {\r\n B.last(1)+= pow(m,kk).toInt\r\n }\r\n else {\r\n B += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n }\r\n if ((A.toList).map(_.toList) == (B.toList).map(_.toList)) {\r\n output.println(\"YES\")\r\n }\r\n else {\r\n output.println(\"NO\")\r\n }\r\n println((A.toList).map(_.toList), (B.toList).map(_.toList))\r\n }\r\n }\r\n}"}, {"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 tokenizer = new StringTokenizer(input.readLine())\r\n val A = ArrayBuffer.empty[Array[Int]]\r\n var hold = 0\r\n for (i <- 0 until n) {\r\n var kk = 0\r\n var new1 = tokenizer.nextToken().toInt\r\n while (new1 % m == 0){\r\n new1 = new1 / m\r\n kk+=1\r\n }\r\n if (i == 0) {\r\n A += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n else if (new1 == hold) {\r\n A.last(1)+= pow(m,kk).toInt\r\n }\r\n else {\r\n A += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n }\r\n val B = ArrayBuffer.empty[Array[Int]]\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val k = tokenizer.nextToken().toInt\r\n hold = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until k) {\r\n var kk = 0\r\n var new1 = tokenizer.nextToken().toInt\r\n while (new1 % m == 0){\r\n new1 = new1 / m\r\n kk+=1\r\n }\r\n if (i == 0) {\r\n B += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n else if (new1 == hold) {\r\n B.last(1)+= pow(m,kk).toInt\r\n }\r\n else {\r\n B += Array(new1, pow(m,kk).toInt)\r\n hold = new1\r\n }\r\n }\r\n if ((A.toList).map(_.toList) == (B.toList).map(_.toList)) {\r\n output.println(\"YES\")\r\n }\r\n else {\r\n output.println(\"NO\")\r\n }\r\n }\r\n }\r\n}"}], "src_uid": "2ff40423619cefd8c2fb35a18549c411"} {"nl": {"description": "You are given a number $$$n$$$ and an array $$$b_1, b_2, \\ldots, b_{n+2}$$$, obtained according to the following algorithm: some array $$$a_1, a_2, \\ldots, a_n$$$ was guessed; array $$$a$$$ was written to array $$$b$$$, i.e. $$$b_i = a_i$$$ ($$$1 \\le i \\le n$$$); The $$$(n+1)$$$-th element of the array $$$b$$$ is the sum of the numbers in the array $$$a$$$, i.e. $$$b_{n+1} = a_1+a_2+\\ldots+a_n$$$; The $$$(n+2)$$$-th element of the array $$$b$$$ was written some number $$$x$$$ ($$$1 \\le x \\le 10^9$$$), i.e. $$$b_{n+2} = x$$$; The array $$$b$$$ was shuffled. For example, the array $$$b=[2, 3, 7, 12 ,2]$$$ it could be obtained in the following ways: $$$a=[2, 2, 3]$$$ and $$$x=12$$$; $$$a=[3, 2, 7]$$$ and $$$x=2$$$. For the given array $$$b$$$, find any array $$$a$$$ that could have been guessed initially.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$). The second row of each test case contains $$$n+2$$$ integers $$$b_1, b_2, \\ldots, b_{n+2}$$$ ($$$1 \\le b_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output: \"-1\", if the array $$$b$$$ could not be obtained from any array $$$a$$$; $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$, otherwise. If there are several arrays of $$$a$$$, you can output any.", "sample_inputs": ["4\n3\n2 3 7 12 2\n4\n9 1 7 1 6 5\n5\n18 2 2 3 2 9 2\n3\n2 6 9 2 1"], "sample_outputs": ["2 3 7 \n-1\n2 2 2 3 9 \n1 2 6"], "notes": null}, "positive_code": [{"source_code": "object P1512D {\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(\r\n // \"\"\"4\r\n //3\r\n //2 3 7 12 2\r\n //4\r\n //9 1 7 1 6 5\r\n //5\r\n //18 2 2 3 2 9 2\r\n //3\r\n //2 6 9 2 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 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 oneTask()\r\n out.endl()\r\n }\r\n }\r\n\r\n // S = (sum + m1 + m2), m1, m2\r\n // \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430: m == S - m - ai => ak, m, ai\r\n\r\n def oneTask(): Unit = {\r\n val size = input.nextInt\r\n val arr = new Array[Long](size + 2)\r\n var m1, m2: Long = 0L\r\n var m1i, m2i: Int = 0\r\n var S = 0L\r\n input.forLongs(size + 2) { (idx, v) =>\r\n S += v\r\n arr(idx) = v\r\n if (v > m1) {\r\n if (v > m2) {\r\n m1 = m2\r\n m1i = m2i\r\n m2 = v\r\n m2i = idx\r\n }\r\n else {\r\n m1 = v\r\n m1i = idx\r\n }\r\n }\r\n }\r\n var last = 0L\r\n var sum = 0L\r\n var idx = 0\r\n while (idx < arr.length && last == 0L) {\r\n val ai = arr(idx)\r\n val ch1 = S - m1 - ai\r\n if (ch1 == m1 && idx != m1i) {\r\n last = ai\r\n sum = m1\r\n }\r\n else if (idx != m2i) {\r\n val ch2 = S - m2 - ai\r\n if (ch2 == m2) {\r\n last = ai\r\n sum = m2\r\n }\r\n }\r\n idx += 1\r\n }\r\n\r\n if (sum != 0L) {\r\n arr.foreach(v => if (v == sum) {\r\n sum = 0L\r\n }\r\n else if (v == last) {\r\n last = 0L\r\n }\r\n else {\r\n out.print(v.toString)\r\n out.print(' ')\r\n }\r\n )\r\n }\r\n else {\r\n out.print(\"-1\")\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 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"}], "negative_code": [{"source_code": "object P1512D {\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(\r\n// \"\"\"4\r\n//3\r\n//2 3 7 12 2\r\n//4\r\n//9 1 7 1 6 5\r\n//5\r\n//18 2 2 3 2 9 2\r\n//3\r\n//2 6 9 2 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 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 oneTask()\r\n out.endl()\r\n }\r\n }\r\n\r\n // S = (sum + m1 + m2), m1, m2\r\n // \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430: m == S - m - ai => ak, m, ai\r\n\r\n def oneTask(): Unit = {\r\n val size = input.nextInt\r\n val arr = new Array[Int](size + 2)\r\n var m1, m1i, m2, m2i: Int = 0\r\n var S = 0\r\n input.forInts(size + 2) { (idx, v) =>\r\n S += v\r\n arr(idx) = v\r\n if (v > m1) {\r\n if (v > m2) {\r\n m1 = m2\r\n m1i = m2i\r\n m2 = v\r\n m2i = idx\r\n }\r\n else {\r\n m1 = v\r\n m1i = idx\r\n }\r\n }\r\n }\r\n var last = 0\r\n var sum = 0\r\n var idx = 0\r\n while (idx < arr.length && last == 0) {\r\n val ai = arr(idx)\r\n val ch1 = S - m1 - ai\r\n if (ch1 == m1 && idx != m1i) {\r\n last = ai\r\n sum = m1\r\n }\r\n else if (idx != m2i) {\r\n val ch2 = S - m2 - ai\r\n if (ch2 == m2) {\r\n last = ai\r\n sum = m2\r\n }\r\n }\r\n idx += 1\r\n }\r\n\r\n if (sum != 0) {\r\n arr.foreach(v => if (v == sum) {\r\n sum = 0\r\n }\r\n else if (v == last) {\r\n last = 0\r\n }\r\n else {\r\n out.print(v)\r\n out.print(' ')\r\n }\r\n )\r\n }\r\n else {\r\n out.print(\"-1\")\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 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 P1512D {\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(\r\n // \"\"\"4\r\n //3\r\n //2 3 7 12 2\r\n //4\r\n //9 1 7 1 6 5\r\n //5\r\n //18 2 2 3 2 9 2\r\n //3\r\n //2 6 9 2 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 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 oneTask()\r\n out.endl()\r\n }\r\n }\r\n\r\n // S = (sum + m1 + m2), m1, m2\r\n // \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430: m == S - m - ai => ak, m, ai\r\n\r\n def oneTask(): Unit = {\r\n val size = input.nextInt\r\n val arr = new Array[Int](size + 2)\r\n var m1, m2: Int = 0\r\n var S = 0\r\n input.forInts(size + 2) { (idx, v) =>\r\n S += v\r\n arr(idx) = v\r\n if (v > m1) {\r\n if (v > m2) {\r\n m1 = m2\r\n m2 = v\r\n }\r\n else {\r\n m1 = v\r\n }\r\n }\r\n }\r\n var last = 0\r\n var sum = 0\r\n var idx = 0\r\n while (idx < arr.length && last == 0) {\r\n val ai = arr(idx)\r\n val ch1 = S - m1 - ai\r\n if (ch1 == m1) {\r\n last = ai\r\n sum = m1\r\n }\r\n else {\r\n val ch2 = S - m2 - ai\r\n if (ch2 == m2) {\r\n last = ai\r\n sum = m2\r\n }\r\n }\r\n idx += 1\r\n }\r\n\r\n if (sum != 0) {\r\n arr.foreach(v => if (v == sum) {\r\n sum = 0\r\n }\r\n else if (v == last) {\r\n last = 0\r\n }\r\n else {\r\n out.print(v)\r\n out.print(' ')\r\n }\r\n )\r\n }\r\n else {\r\n out.print(\"-1\")\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 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"}], "src_uid": "ce667a8fb60841c994aebedb35a3b0d8"} {"nl": {"description": "There is a river of width $$$n$$$. The left bank of the river is cell $$$0$$$ and the right bank is cell $$$n + 1$$$ (more formally, the river can be represented as a sequence of $$$n + 2$$$ cells numbered from $$$0$$$ to $$$n + 1$$$). There are also $$$m$$$ wooden platforms on a river, the $$$i$$$-th platform has length $$$c_i$$$ (so the $$$i$$$-th platform takes $$$c_i$$$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $$$n$$$.You are standing at $$$0$$$ and want to reach $$$n+1$$$ somehow. If you are standing at the position $$$x$$$, you can jump to any position in the range $$$[x + 1; x + d]$$$. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $$$d=1$$$, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells $$$0$$$ and $$$n+1$$$ belong to wooden platforms.You want to know if it is possible to reach $$$n+1$$$ from $$$0$$$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if $$$n=7$$$, $$$m=3$$$, $$$d=2$$$ and $$$c = [1, 2, 1]$$$, then one of the ways to reach $$$8$$$ from $$$0$$$ is follow: The first example: $$$n=7$$$. ", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$d$$$ ($$$1 \\le n, m, d \\le 1000, m \\le n$$$) \u2014 the width of the river, the number of platforms and the maximum distance of your jump, correspondingly. The second line of the input contains $$$m$$$ integers $$$c_1, c_2, \\dots, c_m$$$ ($$$1 \\le c_i \\le n, \\sum\\limits_{i=1}^{m} c_i \\le n$$$), where $$$c_i$$$ is the length of the $$$i$$$-th platform.", "output_spec": "If it is impossible to reach $$$n+1$$$ from $$$0$$$, print NO in the first line. Otherwise, print YES in the first line and the array $$$a$$$ of length $$$n$$$ in the second line \u2014 the sequence of river cells (excluding cell $$$0$$$ and cell $$$n + 1$$$). If the cell $$$i$$$ does not belong to any platform, $$$a_i$$$ should be $$$0$$$. Otherwise, it should be equal to the index of the platform ($$$1$$$-indexed, platforms are numbered from $$$1$$$ to $$$m$$$ in order of input) to which the cell $$$i$$$ belongs. Note that all $$$a_i$$$ equal to $$$1$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_1$$$, all $$$a_i$$$ equal to $$$2$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_2$$$, ..., all $$$a_i$$$ equal to $$$m$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_m$$$. The leftmost position of $$$2$$$ in $$$a$$$ should be greater than the rightmost position of $$$1$$$, the leftmost position of $$$3$$$ in $$$a$$$ should be greater than the rightmost position of $$$2$$$, ..., the leftmost position of $$$m$$$ in $$$a$$$ should be greater than the rightmost position of $$$m-1$$$. See example outputs for better understanding.", "sample_inputs": ["7 3 2\n1 2 1", "10 1 11\n1", "10 1 5\n2"], "sample_outputs": ["YES\n0 1 0 2 2 0 3", "YES\n0 0 0 0 0 0 0 0 0 1", "YES\n0 0 0 0 1 1 0 0 0 0"], "notes": "NoteConsider the first example: the answer is $$$[0, 1, 0, 2, 2, 0, 3]$$$. The sequence of jumps you perform is $$$0 \\rightarrow 2 \\rightarrow 4 \\rightarrow 5 \\rightarrow 7 \\rightarrow 8$$$.Consider the second example: it does not matter how to place the platform because you always can jump from $$$0$$$ to $$$11$$$.Consider the third example: the answer is $$$[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]$$$. The sequence of jumps you perform is $$$0 \\rightarrow 5 \\rightarrow 6 \\rightarrow 11$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?", "input_spec": "The first line contains two integers, n and x (1\u2009\u2264\u2009n,\u2009x\u2009\u2264\u20092000) \u2014 the number of sweets Evan has and the initial height of Om Nom's jump. Each of the following n lines contains three integers ti,\u2009hi,\u2009mi (0\u2009\u2264\u2009ti\u2009\u2264\u20091;\u00a01\u2009\u2264\u2009hi,\u2009mi\u2009\u2264\u20092000) \u2014 the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.", "output_spec": "Print a single integer \u2014 the maximum number of candies Om Nom can eat.", "sample_inputs": ["5 3\n0 2 4\n1 3 1\n0 8 3\n0 20 10\n1 5 5"], "sample_outputs": ["4"], "notes": "NoteOne of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario: Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3\u2009+\u20094\u2009=\u20097. Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7\u2009+\u20095\u2009=\u200912. At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12\u2009+\u20093\u2009=\u200915. Om Nom eats candy 2, the height of his jump is 15\u2009+\u20091\u2009=\u200916. He cannot reach candy 4. "}, "positive_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\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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.In other words, let's say that bi,\u2009c is the number of pebbles of color c in the i-th pile. Then for any 1\u2009\u2264\u2009c\u2009\u2264\u2009k, 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n the following condition must be satisfied |bi,\u2009c\u2009-\u2009bj,\u2009c|\u2009\u2264\u20091. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi,\u2009c is considered to be zero.", "input_spec": "The first line of the input contains positive integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100), separated by a space \u2014 the number of piles and the number of colors respectively. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) denoting number of pebbles in each of the piles.", "output_spec": "If there is no way to paint the pebbles satisfying the given condition, output \"NO\" (without quotes) . Otherwise in the first line output \"YES\" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1\u2009\u2264\u2009j\u2009\u2264\u2009ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.", "sample_inputs": ["4 4\n1 2 3 4", "5 2\n3 2 4 1 3", "5 4\n3 2 4 3 5"], "sample_outputs": ["YES\n1\n1 4\n1 2 4\n1 2 3 4", "NO", "YES\n1 2 3\n1 3\n1 2 3 4\n1 3 4\n1 1 2 3 4"], "notes": null}, "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)\n if (data.max - data.min > k)\n println(\"NO\")\n else {\n println(\"YES\")\n println(data.map(i => (1 to i).map(_ % k + 1).mkString(\" \")).mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [], "src_uid": "e512285d15340343e34f596de2be82eb"} {"nl": {"description": "Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.Let's assume that we are given a connected weighted undirected graph G\u2009=\u2009(V,\u2009E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G1\u2009=\u2009(V,\u2009E1) that is a tree with the set of edges E1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G1 are the same. You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.", "input_spec": "The first line contains two numbers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105, 0\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105) \u2014 the number of vertices and edges of the graph, respectively. Next m lines contain three integers each, representing an edge \u2014 ui,\u2009vi,\u2009wi \u2014 the numbers of vertices connected by an edge and the weight of the edge (ui\u2009\u2260\u2009vi,\u20091\u2009\u2264\u2009wi\u2009\u2264\u2009109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices. The last line of the input contains integer u (1\u2009\u2264\u2009u\u2009\u2264\u2009n) \u2014 the number of the start vertex.", "output_spec": "In the first line print the minimum total weight of the edges of the tree. In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order. If there are multiple answers, print any of them.", "sample_inputs": ["3 3\n1 2 1\n2 3 1\n1 3 2\n3", "4 4\n1 2 1\n2 3 1\n3 4 1\n4 1 2\n4"], "sample_outputs": ["2\n1 2", "4\n2 3 4"], "notes": "NoteIn the first sample there are two possible shortest path trees: with edges 1\u2009\u2013\u20093 and 2\u2009\u2013\u20093 (the total weight is 3); with edges 1\u2009\u2013\u20092 and 2\u2009\u2013\u20093 (the total weight is 2); And, for example, a tree with edges 1\u2009\u2013\u20092 and 1\u2009\u2013\u20093 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1."}, "positive_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(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)+\" \")}\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 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));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"} {"nl": {"description": "You are given a string $$$s=s_1s_2\\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \\dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \\ldots s_r$$$. A substring $$$s[l \\dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 65000$$$)\u00a0\u2014 the length of the string $$$s$$$. The second line contains a string $$$s$$$ of length $$$n$$$. The string $$$s$$$ consists only of digits $$$1$$$, $$$2$$$, ..., $$$9$$$.", "output_spec": "Print the number of even substrings of $$$s$$$.", "sample_inputs": ["4\n1234", "4\n2244"], "sample_outputs": ["6", "10"], "notes": "NoteIn the first example, the $$$[l, r]$$$ pairs corresponding to even substrings are: $$$s[1 \\dots 2]$$$ $$$s[2 \\dots 2]$$$ $$$s[1 \\dots 4]$$$ $$$s[2 \\dots 4]$$$ $$$s[3 \\dots 4]$$$ $$$s[4 \\dots 4]$$$ In the second example, all $$$10$$$ substrings of $$$s$$$ are even substrings. Note, that while substrings $$$s[1 \\dots 1]$$$ and $$$s[2 \\dots 2]$$$ both define the substring \"2\", they are still counted as different substrings."}, "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 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"}, {"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"} {"nl": {"description": "Eshag has an array $$$a$$$ consisting of $$$n$$$ integers.Eshag can perform the following operation any number of times: choose some subsequence of $$$a$$$ and delete every element from it which is strictly larger than $$$AVG$$$, where $$$AVG$$$ is the average of the numbers in the chosen subsequence.For example, if $$$a = [1 , 4 , 3 , 2 , 4]$$$ and Eshag applies the operation to the subsequence containing $$$a_1$$$, $$$a_2$$$, $$$a_4$$$ and $$$a_5$$$, then he will delete those of these $$$4$$$ elements which are larger than $$$\\frac{a_1+a_2+a_4+a_5}{4} = \\frac{11}{4}$$$, so after the operation, the array $$$a$$$ will become $$$a = [1 , 3 , 2]$$$.Your task is to find the maximum number of elements Eshag can delete from the array $$$a$$$ by applying the operation described above some number (maybe, zero) times.A sequence $$$b$$$ is a subsequence of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements.", "input_spec": "The first line contains an integer $$$t$$$ $$$(1\\le t\\le 100)$$$ \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\\le n\\le 100)$$$ \u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(1\\le a_i \\le 100)$$$ \u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case print a single integer \u2014 the maximum number of elements Eshag can delete from the array $$$a$$$.", "sample_inputs": ["3\n6\n1 1 1 2 2 3\n6\n9 9 9 9 9 9\n6\n6 4 1 1 4 1"], "sample_outputs": ["3\n0\n3"], "notes": "NoteConsider the first test case.Initially $$$a = [1, 1, 1, 2, 2, 3]$$$.In the first operation, Eshag can choose the subsequence containing $$$a_1$$$, $$$a_5$$$ and $$$a_6$$$, their average is equal to $$$\\frac{a_1 + a_5 + a_6}{3} = \\frac{6}{3} = 2$$$. So $$$a_6$$$ will be deleted.After this $$$a = [1, 1, 1, 2, 2]$$$.In the second operation, Eshag can choose the subsequence containing the whole array $$$a$$$, the average of all its elements is equal to $$$\\frac{7}{5}$$$. So $$$a_4$$$ and $$$a_5$$$ will be deleted.After this $$$a = [1, 1, 1]$$$.In the second test case, Eshag can't delete any element."}, "positive_code": [{"source_code": "import scala.io.StdIn._\r\n\r\nobject A extends App {\r\n for (_ <- 0 until readInt) {\r\n println(\r\n readInt - readLine.split(\" \").foldLeft((Int.MaxValue, 1)) {\r\n case (t @ (min, cpt), x) =>\r\n val i = x.toInt\r\n if (i < min)\r\n (i, 1)\r\n else if (i == min)\r\n (i, cpt + 1)\r\n else\r\n t\r\n }._2\r\n )\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "d5627b9fe5f6c5a7247e1f9d9e9b0c6a"} {"nl": {"description": "One department of some software company has $$$n$$$ servers of different specifications. Servers are indexed with consecutive integers from $$$1$$$ to $$$n$$$. Suppose that the specifications of the $$$j$$$-th server may be expressed with a single integer number $$$c_j$$$ of artificial resource units.In order for production to work, it is needed to deploy two services $$$S_1$$$ and $$$S_2$$$ to process incoming requests using the servers of the department. Processing of incoming requests of service $$$S_i$$$ takes $$$x_i$$$ resource units.The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $$$S_i$$$ is deployed using $$$k_i$$$ servers, then the load is divided equally between these servers and each server requires only $$$x_i / k_i$$$ (that may be a fractional number) resource units.Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.", "input_spec": "The first line contains three integers $$$n$$$, $$$x_1$$$, $$$x_2$$$ ($$$2 \\leq n \\leq 300\\,000$$$, $$$1 \\leq x_1, x_2 \\leq 10^9$$$)\u00a0\u2014 the number of servers that the department may use, and resource units requirements for each of the services. The second line contains $$$n$$$ space-separated integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\leq c_i \\leq 10^9$$$)\u00a0\u2014 the number of resource units provided by each of the servers.", "output_spec": "If it is impossible to deploy both services using the given servers, print the only word \"No\" (without the quotes). Otherwise print the word \"Yes\" (without the quotes). In the second line print two integers $$$k_1$$$ and $$$k_2$$$ ($$$1 \\leq k_1, k_2 \\leq n$$$)\u00a0\u2014 the number of servers used for each of the services. In the third line print $$$k_1$$$ integers, the indices of the servers that will be used for the first service. In the fourth line print $$$k_2$$$ integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.", "sample_inputs": ["6 8 16\n3 5 2 9 8 7", "4 20 32\n21 11 11 12", "4 11 32\n5 5 16 16", "5 12 20\n7 8 4 11 9"], "sample_outputs": ["Yes\n3 2\n1 2 6\n5 4", "Yes\n1 3\n1\n2 3 4", "No", "No"], "notes": "NoteIn the first sample test each of the servers 1, 2 and 6 will will provide $$$8 / 3 = 2.(6)$$$ resource units and each of the servers 5, 4 will provide $$$16 / 2 = 8$$$ resource units.In the second sample test the first server will provide $$$20$$$ resource units and each of the remaining servers will provide $$$32 / 3 = 10.(6)$$$ resource units."}, "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, x1, x2) = readLongs(3)\n val n = _n.toInt\n val cs = readLongs(n).zipWithIndex.sortBy(- _._1)\n\n var split1, split2 = -1\n var i = 0\n while (i < n) {\n val cap = cs(i)._1 * (i + 1).toLong\n i += 1\n if (split1 == -1 && cap >= x1) {\n split1 = i\n }\n if (split2 == -1 && cap >= x2) {\n split2 = i\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (split1 > 0) {\n var end = split1\n while (end < n) {\n val cap = cs(end)._1 * (end - split1 + 1).toLong\n end += 1\n if (cap >= x2) {\n println(\"Yes\")\n println(s\"$split1 ${end - split1}\")\n println(cs.take(split1).map(_._2 + 1).mkString(\" \"))\n println(cs.slice(split1, end).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n if (split2 > 0) {\n var end = split2\n while (end < n) {\n val cap = cs(end)._1 * (end - split2 + 1).toLong\n end += 1\n if (cap >= x1) {\n println(\"Yes\")\n println(s\"${end - split2} $split2\")\n println(cs.slice(split2, end).map(_._2 + 1).mkString(\" \"))\n println(cs.take(split2).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\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, x1, x2) = readLongs(3)\n val n = _n.toInt\n val cs = readLongs(n).zipWithIndex.sortBy(- _._1)\n\n var split1, split2 = -1\n var i = 0\n while (i < n) {\n val cap = cs(i)._1 * (i + 1).toLong\n i += 1\n if (split1 == -1 && cap >= x1) {\n split1 = i\n }\n if (split2 == -1 && cap >= x2) {\n split2 = i\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (split1 > 0) {\n var end = split1\n while (end < n) {\n val cap = cs(end)._1 * (end - split1 + 1).toLong\n end += 1\n if (cap >= x2) {\n println(\"Yes\")\n println(s\"$split1 ${end - split1}\")\n println(cs.take(split1).map(_._2 + 1).mkString(\" \"))\n println(cs.slice(split1, end).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n if (split2 > 0) {\n var end = split2\n while (end < n) {\n val cap = cs(end)._1 * (end - split2 + 1).toLong\n end += 1\n if (cap >= x1) {\n println(\"Yes\")\n println(s\"$split2 ${end - split2}\")\n println(cs.slice(split2, end).map(_._2 + 1).mkString(\" \"))\n println(cs.take(split2).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n println(\"No\")\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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, x1, x2) = readInts(3)\n val cs = readLongs(n).zipWithIndex.sortBy(- _._1)\n\n var split1, split2 = -1\n var i = 0\n while (i < n) {\n val cap = (i + 1) * cs(i)._1\n i += 1\n if (split1 == -1 && cap >= x1) {\n split1 = i\n }\n if (split2 == -1 && cap >= x2) {\n split2 = i\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (split1 > 0) {\n var end = split1\n while (end < n) {\n val cap = (end - split1 + 1) * cs(end)._1\n end += 1\n if (cap >= x2) {\n println(\"Yes\")\n println(s\"$split1 ${end - split1}\")\n println(cs.take(split1).map(_._2 + 1).mkString(\" \"))\n println(cs.slice(split1, end).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n if (split2 > 0) {\n var end = split2\n while (end < n) {\n val cap = (end - split2 + 1) * cs(end)._1\n end += 1\n if (cap >= x1) {\n println(\"Yes\")\n println(s\"$split2 ${end - split2}\")\n println(cs.slice(split2, end).map(_._2 + 1).mkString(\" \"))\n println(cs.take(split2).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n println(\"No\")\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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, x1, x2) = readLongs(3)\n val n = _n.toInt\n val cs = readLongs(n).zipWithIndex.sortBy(- _._1)\n\n var split1, split2 = -1\n var i = 0\n while (i < n) {\n val cap = cs(i)._1 * (i + 1).toLong\n i += 1\n if (split1 == -1 && cap >= x1) {\n split1 = i\n }\n if (split2 == -1 && cap >= x2) {\n split2 = i\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (split2 > 0) {\n var end = split2\n while (end < n) {\n val cap = cs(end)._1 * (end - split2 + 1).toLong\n end += 1\n if (cap >= x1) {\n println(\"Yes\")\n println(s\"$split2 ${end - split2}\")\n println(cs.slice(split2, end).map(_._2 + 1).mkString(\" \"))\n println(cs.take(split2).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n if (split1 > 0) {\n var end = split1\n while (end < n) {\n val cap = cs(end)._1 * (end - split1 + 1).toLong\n end += 1\n if (cap >= x2) {\n println(\"Yes\")\n println(s\"$split1 ${end - split1}\")\n println(cs.take(split1).map(_._2 + 1).mkString(\" \"))\n println(cs.slice(split1, end).map(_._2 + 1).mkString(\" \"))\n Console.flush\n System.exit(0)\n }\n }\n }\n\n println(\"No\")\n\n Console.flush\n}\n"}], "src_uid": "aa312ddd875b82eab84fdc92ceec37e5"} {"nl": {"description": "You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have $$$n$$$ tiles in your hand. Each tile has an integer between $$$1$$$ and $$$m$$$ written on it.To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, $$$7, 7, 7$$$ is a valid triple, and so is $$$12, 13, 14$$$, but $$$2,2,3$$$ or $$$2,4,6$$$ are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple.To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.", "input_spec": "The first line contains two integers integer $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^6$$$)\u00a0\u2014 the number of tiles in your hand and the number of tiles types. The second line contains integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le m$$$), where $$$a_i$$$ denotes the number written on the $$$i$$$-th tile.", "output_spec": "Print one integer: the maximum number of triples you can form.", "sample_inputs": ["10 6\n2 3 3 3 4 4 4 5 5 6", "12 6\n1 5 3 3 3 4 3 5 3 2 3 3", "13 5\n1 1 5 1 2 3 3 2 4 2 3 4 5"], "sample_outputs": ["3", "3", "4"], "notes": "NoteIn the first example, we have tiles $$$2, 3, 3, 3, 4, 4, 4, 5, 5, 6$$$. We can form three triples in the following way: $$$2, 3, 4$$$; $$$3, 4, 5$$$; $$$4, 5, 6$$$. Since there are only $$$10$$$ tiles, there is no way we could form $$$4$$$ triples, so the answer is $$$3$$$.In the second example, we have tiles $$$1$$$, $$$2$$$, $$$3$$$ ($$$7$$$ times), $$$4$$$, $$$5$$$ ($$$2$$$ times). We can form $$$3$$$ triples as follows: $$$1, 2, 3$$$; $$$3, 3, 3$$$; $$$3, 4, 5$$$. One can show that forming $$$4$$$ triples is not possible."}, "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, -1)\n val C = Array.ofDim[Int](M)\n REP(N) { i =>\n C(A(i)) += 1\n }\n// debug(C)\n\n // 0: 0, 1: 1, 2: 2\u4ee5\u4e0a\n val dp = Array.fill[Int](M + 1, 5, 3)(-1)\n dp(0)(0)(0) = 0\n\n def transit(i: Int, j: Int, k: Int, chow: Int, pong: Int) = {\n val cur = min(4, C(i) - chow - pong * 3)\n val prev = min(2, j - chow)\n dp(i + 1)(cur)(prev) = max(dp(i + 1)(cur)(prev), dp(i)(j)(k) + chow + pong)\n }\n\n REP(M) { i =>\n REP(5) { j => // 1\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n REP(3) { k => // 2\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n if (dp(i)(j)(k) >= 0) {\n// debug(s\"$i $j $k\")\n // \u30c1\u30fc\u306e\u56de\u6570\n REP(min(min(j, k), C(i)) + 1) { chow =>\n val remain = C(i) - chow\n val pong = remain / 3\n transit(i, j, k, chow, pong) // \u3067\u304d\u308b\u3060\u3051\u30dd\u30f3\n // \u6700\u5f8c\u6b8b\u3059\u3088\u3046\u306b\u30dd\u30f3\u3092\u3059\u308b\n if (pong > 0) transit(i, j, k, chow, pong - 1)\n if (pong > 1) transit(i, j, k, chow, pong - 2)\n }\n }\n }\n }\n }\n\n// REP(M + 1) { i =>\n// REP(5) { j =>\n// REP(3) { k =>\n// debug(s\"$i $j $k ${dp(i)(j)(k)}\")\n// }\n// }\n// }\n\n var ans = 0\n REP(3) { i =>\n REP(3) { j =>\n ans = max(ans, dp(M)(i)(j))\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": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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, -1)\n val C = Array.ofDim[Int](M)\n REP(N) { i =>\n C(A(i)) += 1\n }\n\n\n val dp = Array.fill[Long](M + 1, 3, 3)(-1)\n dp(0)(0)(0) = 0\n\n def transit(i: Int, j: Int, k: Int, next: Int, chow: Int, pong: Int) = {\n dp(i + 1)(next)(j - chow) = max(dp(i + 1)(next)(j - chow), dp(i)(j)(k) + chow + pong)\n }\n\n REP(M) { i =>\n REP(3) { j => // 1\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n REP(3) { k => // 2\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n if (dp(i)(j)(k) >= 0) {\n // \u30c1\u30fc\u306e\u56de\u6570\n REP(min(min(j, k), C(i)) + 1) { l =>\n val remain = C(i) - l\n if (remain >= 3) {\n val pong = remain / 3\n transit(i, j, k, remain % 3, l, pong) // \u3067\u304d\u308b\u3060\u3051\u30dd\u30f3\n transit(i, j, k, 2, l, pong - 1) // \u6700\u5f8c\u6b8b\u3059\u3088\u3046\u306b\u30dd\u30f3\n } else {\n // \u30dd\u30f3\u306a\u3057\n transit(i, j, k, remain, l, 0)\n }\n }\n }\n }\n }\n }\n\n var ans = 0L\n REP(3) { i =>\n REP(3) { j =>\n ans = max(ans, dp(M)(i)(j))\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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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, -1)\n val C = Array.ofDim[Int](M)\n REP(N) { i =>\n C(A(i)) += 1\n }\n// debug(C)\n\n // 0: 0, 1: 1, 2: 2\u4ee5\u4e0a\n val dp = Array.fill[Long](M + 1, 3, 3)(-1)\n dp(0)(0)(0) = 0\n\n def transit(i: Int, j: Int, k: Int, chow: Int, pong: Int) = {\n val remain = min(2, C(i) - chow - pong * 3)\n dp(i + 1)(remain)(j - chow) = max(dp(i + 1)(remain)(j - chow), dp(i)(j)(k) + chow + pong)\n }\n\n REP(M) { i =>\n REP(3) { j => // 1\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n REP(3) { k => // 2\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n if (dp(i)(j)(k) >= 0) {\n// debug(s\"$i $j $k\")\n // \u30c1\u30fc\u306e\u56de\u6570\n REP(min(min(j, k), C(i)) + 1) { chow =>\n val remain = C(i) - chow\n val pong = remain / 3\n transit(i, j, k, chow, pong) // \u3067\u304d\u308b\u3060\u3051\u30dd\u30f3\n if (pong > 0) transit(i, j, k, chow, pong - 1) // \u6700\u5f8c\u6b8b\u3059\u3088\u3046\u306b\u30dd\u30f3\n }\n }\n }\n }\n }\n\n// REP(M + 1) { i =>\n// REP(3) { j =>\n// REP(3) { k =>\n// debug(s\"$i $j $k ${dp(i)(j)(k)}\")\n// }\n// }\n// }\n\n var ans = 0L\n REP(3) { i =>\n REP(3) { j =>\n ans = max(ans, dp(M)(i)(j))\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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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, -1)\n val C = Array.ofDim[Int](M)\n REP(N) { i =>\n C(A(i)) += 1\n }\n\n\n val dp = Array.fill[Int](M + 1, 3, 3)(-1)\n dp(0)(0)(0) = 0\n\n def transit(i: Int, j: Int, k: Int, next: Int, chow: Int, pong: Int) = {\n dp(i + 1)(next)(j - chow) = max(dp(i + 1)(next)(j - chow), dp(i)(j)(k) + chow + pong)\n }\n\n REP(M) { i =>\n REP(3) { j => // 1\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n REP(3) { k => // 2\u3064\u524d\u306e\u724c\u306e\u6b8b\u308a\n if (dp(i)(j)(k) >= 0) {\n // \u30c1\u30fc\u306e\u56de\u6570\n REP(min(min(j, k), C(i)) + 1) { l =>\n val remain = C(i) - l\n if (remain >= 3) {\n val pong = remain / 3\n transit(i, j, k, remain % 3, l, pong) // \u3067\u304d\u308b\u3060\u3051\u30dd\u30f3\n transit(i, j, k, 2, l, pong - 1) // \u6700\u5f8c\u6b8b\u3059\u3088\u3046\u306b\u30dd\u30f3\n } else {\n // \u30dd\u30f3\u306a\u3057\n transit(i, j, k, remain, l, 0)\n }\n }\n }\n }\n }\n }\n\n var ans = 0\n REP(3) { i =>\n REP(3) { j =>\n ans = max(ans, dp(M)(i)(j))\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"}], "src_uid": "b54ca6dbe4905632b8e1844aa691c55e"} {"nl": {"description": "Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.Hemose has an array of $$$n$$$ integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:Choose indices $$$i$$$ and $$$j$$$ such that $$$1 \\le i, j \\le n$$$, and $$$\\lvert i - j \\rvert \\geq x$$$. Then, swap elements $$$a_i$$$ and $$$a_j$$$.Can you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly $$$0$$$)?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \\leq t \\leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \\leq x \\leq n \\leq 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \\leq a_i \\leq 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, you should output a single string. If Samez can sort the array in non-decreasing order using the operation written above, output \"YES\" (without quotes). Otherwise, output \"NO\" (without quotes). You can print each letter of \"YES\" and \"NO\" in any case (upper or lower).", "sample_inputs": ["4\n3 3\n3 2 1\n4 3\n1 2 3 4\n5 2\n5 1 2 3 4\n5 4\n1 2 3 4 4"], "sample_outputs": ["NO\nYES\nYES\nYES"], "notes": "NoteIn the first test case, you can't do any operations.In the second test case, the array is already sorted.In the third test case, you can do the operations as follows: $$$[5,1,2,3,4]$$$, $$$swap(a_1,a_3)$$$ $$$[2,1,5,3,4]$$$, $$$swap(a_2,a_5)$$$ $$$[2,4,5,3,1]$$$, $$$swap(a_2,a_4)$$$ $$$[2,3,5,4,1]$$$, $$$swap(a_1,a_5)$$$ $$$[1,3,5,4,2]$$$, $$$swap(a_2,a_5)$$$ $$$[1,2,5,4,3]$$$, $$$swap(a_3,a_5)$$$ $$$[1,2,3,4,5]$$$ (Here $$$swap(a_i, a_j)$$$ refers to swapping elements at positions $$$i$$$, $$$j$$$)."}, "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": "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"}, {"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"} {"nl": {"description": "You are given an undirected tree of $$$n$$$ vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.How many nice edges are there in the given tree?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 the number of vertices in the tree. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2$$$) \u2014 the colors of the vertices. $$$a_i = 1$$$ means that vertex $$$i$$$ is colored red, $$$a_i = 2$$$ means that vertex $$$i$$$ is colored blue and $$$a_i = 0$$$ means that vertex $$$i$$$ is uncolored. The $$$i$$$-th of the next $$$n - 1$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$v_i \\ne u_i$$$) \u2014 the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.", "output_spec": "Print a single integer \u2014 the number of nice edges in the given tree.", "sample_inputs": ["5\n2 0 0 1 2\n1 2\n2 3\n2 4\n2 5", "5\n1 0 0 0 2\n1 2\n2 3\n3 4\n4 5", "3\n1 1 2\n2 3\n1 3"], "sample_outputs": ["1", "4", "0"], "notes": "NoteHere is the tree from the first example: The only nice edge is edge $$$(2, 4)$$$. Removing it makes the tree fall apart into components $$$\\{4\\}$$$ and $$$\\{1, 2, 3, 5\\}$$$. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.Here is the tree from the second example: Every edge is nice in it.Here is the tree from the third example: Edge $$$(1, 3)$$$ splits the into components $$$\\{1\\}$$$ and $$$\\{3, 2\\}$$$, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge $$$(2, 3)$$$ splits the into components $$$\\{1, 3\\}$$$ and $$$\\{2\\}$$$, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0."}, "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 (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n\n val (_, p, q) = traceBfs(g)\n\n val sumR = A.count(_ == 1)\n val sumB = A.count(_ == 2)\n\n val R, B = Array.ofDim[Int](N)\n var ans = 0\n REP_r(N) { i =>\n val v = q(i)\n\n if (A(v) == 1) R(v) += 1\n if (A(v) == 2) B(v) += 1\n\n val es = g(v)\n REP(es.length) { j =>\n val u = es(j)\n if (u != p(v)) {\n R(v) += R(u)\n B(v) += B(u)\n }\n }\n\n if (sumR == R(v) && B(v) == 0 || sumB == B(v) && R(v) == 0) ans += 1\n }\n\n out.println(ans)\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 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": [], "src_uid": "0d95c84e73aa9b6567eadeb16acfda41"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, \"acab\" is a substring of \"abacaba\" (it starts in position $$$3$$$ and ends in position $$$6$$$), but \"aa\" or \"d\" aren't substrings of this string. So the substring of the string $$$s$$$ from position $$$l$$$ to position $$$r$$$ is $$$s[l; r] = s_l s_{l + 1} \\dots s_r$$$.You have to choose exactly one of the substrings of the given string and reverse it (i.\u2009e. make $$$s[l; r] = s_r s_{r - 1} \\dots s_l$$$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print \"NO\". Otherwise print \"YES\" and any suitable substring.String $$$x$$$ is lexicographically less than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x \\ne y$$$), or there exists such $$$i$$$ ($$$1 \\le i \\le min(|x|, |y|)$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \\le j < i$$$) $$$x_j = y_j$$$. Here $$$|a|$$$ denotes the length of the string $$$a$$$. The lexicographic comparison of strings is implemented by operator < in modern programming languages\u200b\u200b.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.", "output_spec": "If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print \"NO\". Otherwise print \"YES\" and two indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) denoting the substring you have to reverse. If there are multiple answers, you can print any.", "sample_inputs": ["7\nabacaba", "6\naabcfg"], "sample_outputs": ["YES\n2 5", "NO"], "notes": "NoteIn the first testcase the resulting string is \"aacabba\"."}, "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.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 = ni()\n val S = ns(N)\n\n var cur = 0\n REP(N) { i =>\n val c = S(i) - 'a'\n if (c < cur) {\n out.println(\"YES\")\n out.println(s\"$i ${i + 1}\")\n return\n }\n cur = c\n }\n 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 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": "d45f775613e701bbdaa4e457e6e189e2"} {"nl": {"description": "Pay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array $$$a=[a_1, a_2, \\ldots, a_n]$$$ ($$$1 \\le a_i \\le n$$$) is given. Its element $$$a_i$$$ is called special if there exists a pair of indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) such that $$$a_i = a_l + a_{l+1} + \\ldots + a_r$$$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array $$$a$$$.For example, if $$$n=9$$$ and $$$a=[3,1,4,1,5,9,2,6,5]$$$, then the answer is $$$5$$$: $$$a_3=4$$$ is a special element, since $$$a_3=4=a_1+a_2=3+1$$$; $$$a_5=5$$$ is a special element, since $$$a_5=5=a_2+a_3=1+4$$$; $$$a_6=9$$$ is a special element, since $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$; $$$a_8=6$$$ is a special element, since $$$a_8=6=a_2+a_3+a_4=1+4+1$$$; $$$a_9=5$$$ is a special element, since $$$a_9=5=a_2+a_3=1+4$$$. Please note that some of the elements of the array $$$a$$$ may be equal \u2014 if several elements are equal and special, then all of them should be counted in the answer.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 8000$$$) \u2014 the length of the array $$$a$$$. The second line contains integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$8000$$$.", "output_spec": "Print $$$t$$$ numbers \u2014 the number of special elements for each of the given arrays.", "sample_inputs": ["5\n9\n3 1 4 1 5 9 2 6 5\n3\n1 1 2\n5\n1 1 1 1 1\n8\n8 7 6 5 4 3 2 1\n1\n1"], "sample_outputs": ["5\n1\n0\n4\n0"], "notes": null}, "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 n = ni()\n val a = na(n)\n\n val cnt = Array.fill[Int](n+1)(0)\n a.foreach(f => cnt(f) += 1)\n\n var ans = 0L\n REP(n) { i =>\n var sum = 0\n i until n foreach { j =>\n sum += a(j)\n if(j > i && sum <= n) {\n ans += cnt(sum)\n cnt(sum) = 0\n }\n }\n }\n out.println(ans)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "2326470337301e0f4b0d1b1a6195e398"} {"nl": {"description": "The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!", "input_spec": "The first line contains two integers, n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.", "output_spec": "In t lines, print the actions the programmers need to make. In the i-th line print: \"LEFT\" (without the quotes), if the i-th action was \"move the ladder to the left\"; \"RIGHT\" (without the quotes), if the i-th action was \"move the ladder to the right\"; \"PRINT x\" (without the quotes), if the i-th action was to \"go up the ladder, paint character x, go down the ladder\". The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.", "sample_inputs": ["2 2\nR1", "2 1\nR1", "6 4\nGO?GO!"], "sample_outputs": ["PRINT 1\nLEFT\nPRINT R", "PRINT R\nRIGHT\nPRINT 1", "RIGHT\nRIGHT\nPRINT !\nLEFT\nPRINT O\nLEFT\nPRINT G\nLEFT\nPRINT ?\nLEFT\nPRINT O\nLEFT\nPRINT G"], "notes": "NoteNote that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$=\"0101\" the period is $$$k=2$$$, for $$$s$$$=\"0000\" the period is $$$k=1$$$, for $$$s$$$=\"010\" the period is $$$k=2$$$, for $$$s$$$=\"0011\" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that: String $$$s$$$ consists only of 0's and 1's; The length of $$$s$$$ doesn't exceed $$$2 \\cdot |t|$$$; String $$$t$$$ is a subsequence of string $$$s$$$; String $$$s$$$ has smallest possible period among all strings that meet conditions 1\u20143. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$=\"011\" is a subsequence of $$$s$$$=\"10101\".", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 100$$$)\u00a0\u2014 the number of test cases. Next $$$T$$$ lines contain test cases \u2014 one per line. Each line contains string $$$t$$$ ($$$1 \\le |t| \\le 100$$$) consisting only of 0's and 1's.", "output_spec": "Print one string for each test case \u2014 string $$$s$$$ you needed to find. If there are multiple solutions print any one of them.", "sample_inputs": ["4\n00\n01\n111\n110"], "sample_outputs": ["00\n01\n11111\n1010"], "notes": "NoteIn the first and second test cases, $$$s = t$$$ since it's already one of the optimal solutions. Answers have periods equal to $$$1$$$ and $$$2$$$, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $$$s$$$. String $$$s$$$ has period equal to $$$1$$$."}, "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 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"}, {"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"} {"nl": {"description": "Hanh lives in a shared apartment. There are $$$n$$$ people (including Hanh) living there, each has a private fridge. $$$n$$$ fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $$$n$$$ people can open it. For exampe, in the picture there are $$$n=4$$$ people and $$$5$$$ chains. The first person knows passcodes of two chains: $$$1-4$$$ and $$$1-2$$$. The fridge $$$1$$$ can be open by its owner (the person $$$1$$$), also two people $$$2$$$ and $$$4$$$ (acting together) can open it. The weights of these fridges are $$$a_1, a_2, \\ldots, a_n$$$. To make a steel chain connecting fridges $$$u$$$ and $$$v$$$, you have to pay $$$a_u + a_v$$$ dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly $$$m$$$ steel chains so that all fridges are private. A fridge is private if and only if, among $$$n$$$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $$$i$$$ is not private if there exists the person $$$j$$$ ($$$i \\ne j$$$) that the person $$$j$$$ can open the fridge $$$i$$$.For example, in the picture all the fridges are private. On the other hand, if there are $$$n=2$$$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $$$m$$$ chains, and if yes, output any solution that minimizes the total cost. ", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 10$$$). Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \\le n \\le 1000$$$, $$$1 \\le m \\le n$$$)\u00a0\u2014 the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^4$$$)\u00a0\u2014 weights of all fridges.", "output_spec": "For each test case: If there is no solution, print a single integer $$$-1$$$. Otherwise, print a single integer $$$c$$$\u00a0\u2014 the minimum total cost. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$), meaning that the $$$i$$$-th steel chain connects fridges $$$u_i$$$ and $$$v_i$$$. An arbitrary number of chains can be between a pair of fridges. If there are multiple answers, print any.", "sample_inputs": ["3\n4 4\n1 1 1 1\n3 1\n1 2 3\n3 3\n1 2 3"], "sample_outputs": ["8\n1 2\n4 3\n3 2\n4 1\n-1\n12\n3 2\n1 2\n3 1"], "notes": null}, "positive_code": [{"source_code": "object B1255 {\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(n, m) = readInts(2)\n val arr = readInts(n)\n val min = n\n if (m < min || n == 2) {\n out.println(-1)\n } else {\n var res = arr.map(_.toLong).sum * 2\n val smallest = arr.zipWithIndex.sortBy(_._1).take(2)\n res += (smallest(0)._1 + smallest(1)._1).toLong * (m - min).toLong\n out.println(res)\n for (i <- 1 to n) {\n if (i == n)\n out.println(s\"$n 1\")\n else\n out.println(s\"$i ${i + 1}\")\n }\n (1 to m - min).foreach { _ =>\n out.println(s\"${smallest(0)._2 + 1} ${smallest(1)._2 + 1}\")\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 B1255 {\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(n, m) = readInts(2)\n val arr = readInts(n)\n val min = ((n - 1) * n) / 2\n if (m < min) {\n out.println(-1)\n } else {\n var res = arr.map(_.toLong).sum * (n - 1)\n val smallest = arr.zipWithIndex.sortBy(_._1).take(2)\n res += (smallest(0)._1 + smallest(1)._1).toLong * (m - min).toLong\n out.println(res)\n for (i <- 1 to n) {\n for (j <- i + 1 to n) {\n out.println(s\"$i $j\")\n }\n }\n (1 to m - min).foreach { _ =>\n out.println(s\"${smallest(0)._2 + 1} ${smallest(1)._2 + 1}\")\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"}, {"source_code": "object B1255 {\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(n, m) = readInts(2)\n val arr = readInts(n)\n val min = ((n - 1) * n) / 2\n if (m < min || n == 2) {\n out.println(-1)\n } else {\n var res = arr.map(_.toLong).sum * (n - 1)\n val smallest = arr.zipWithIndex.sortBy(_._1).take(2)\n res += (smallest(0)._1 + smallest(1)._1).toLong * (m - min).toLong\n out.println(res)\n for (i <- 1 to n) {\n for (j <- i + 1 to n) {\n out.println(s\"$i $j\")\n }\n }\n (1 to m - min).foreach { _ =>\n out.println(s\"${smallest(0)._2 + 1} ${smallest(1)._2 + 1}\")\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": "f6e219176e846b16c5f52dee81601c8e"} {"nl": {"description": "High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.", "output_spec": "Print the only integer\u00a0\u2014 the maximum beauty of the string Vasya can achieve by changing no more than k characters.", "sample_inputs": ["4 2\nabba", "8 1\naabaabaa"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first sample, Vasya can obtain both strings \"aaaa\" and \"bbbb\".In the second sample, the optimal answer is obtained with the string \"aaaaabaa\" or with the string \"aabaaaaa\"."}, "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"}, {"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"}], "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"} {"nl": {"description": "You have two positive integers $$$a$$$ and $$$b$$$.You can perform two kinds of operations: $$$a = \\lfloor \\frac{a}{b} \\rfloor$$$ (replace $$$a$$$ with the integer part of the division between $$$a$$$ and $$$b$$$) $$$b=b+1$$$ (increase $$$b$$$ by $$$1$$$) Find the minimum number of operations required to make $$$a=0$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The only line of the description of each test case contains two integers $$$a$$$, $$$b$$$ ($$$1 \\le a,b \\le 10^9$$$).", "output_spec": "For each test case, print a single integer: the minimum number of operations required to make $$$a=0$$$.", "sample_inputs": ["6\n9 2\n1337 1\n1 1\n50000000 4\n991026972 997\n1234 5678"], "sample_outputs": ["4\n9\n2\n12\n3\n1"], "notes": "NoteIn the first test case, one of the optimal solutions is: Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 4$$$ and $$$b = 2$$$. Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 2$$$. Increase $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 3$$$. Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 0$$$ and $$$b = 3$$$. "}, "positive_code": [{"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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "2b757fa66ce89046fe18cdfdeafa6660"} {"nl": {"description": "You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than $$$5$$$.Your task is to report the maximum possible number of students in a balanced team.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is a programming skill of the $$$i$$$-th student.", "output_spec": "Print one integer \u2014 the maximum possible number of students in a balanced team.", "sample_inputs": ["6\n1 10 17 12 15 2", "10\n1337 1337 1337 1337 1337 1337 1337 1337 1337 1337", "6\n1 1000 10000 10 100 1000000000"], "sample_outputs": ["3", "10", "1"], "notes": "NoteIn the first example you can create a team with skills $$$[12, 17, 15]$$$.In the second example you can take all students in a team because their programming skills are equal.In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students)."}, "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\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"}, {"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"} {"nl": {"description": "Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \\le l \\le r \\le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \\dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print \"YES\", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print \"NO\".", "sample_inputs": ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"], "sample_outputs": ["YES\nNO\nNO"], "notes": "NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in \u00abBersoft\u00bb company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.", "input_spec": "The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters \u00ab@\u00bb.", "output_spec": "If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.", "sample_inputs": ["a@aa@a", "a@a@a", "@aa@a"], "sample_outputs": ["a@a,a@a", "No solution", "No solution"], "notes": null}, "positive_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.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}"}, {"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"} {"nl": {"description": "One day Petya got a birthday present from his mom: a book called \"The Legends and Myths of Graph Theory\". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h\u2009+\u2009t\u2009+\u20092 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.", "input_spec": "The first line contains four integers n, m, h, t (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 1\u2009\u2264\u2009h,\u2009t\u2009\u2264\u2009100) \u2014 the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, a\u2009\u2260\u2009b) \u2014 the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.", "output_spec": "If graph G has no hydra, print \"NO\" (without the quotes). Otherwise, in the first line print \"YES\" (without the quotes). In the second line print two integers \u2014 the numbers of nodes u and v. In the third line print h numbers \u2014 the numbers of the nodes that are the heads. In the fourth line print t numbers \u2014 the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.", "sample_inputs": ["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"], "sample_outputs": ["YES\n4 1\n5 6 \n9 3 2", "NO"], "notes": "NoteThe first sample is depicted on the picture below: "}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a string $$$s$$$, consisting only of Latin letters 'a', and a string $$$t$$$, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string $$$s$$$ with a string $$$t$$$. Note that after the replacement string $$$s$$$ might contain letters other than 'a'.You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.Two strings are considered different if they have different length, or they differ at some index.", "input_spec": "The first line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a non-empty string $$$s$$$, consisting only of Latin letters 'a'. The length of $$$s$$$ doesn't exceed $$$50$$$. The second line contains a non-empty string $$$t$$$, consisting of lowercase Latin letters. The length of $$$t$$$ doesn't exceed $$$50$$$.", "output_spec": "For each testcase, print the number of different strings $$$s$$$ that can be obtained after an arbitrary amount of moves (including zero). If the number is infinitely large, print -1. Otherwise, print the number.", "sample_inputs": ["3\n\naaaa\n\na\n\naa\n\nabc\n\na\n\nb"], "sample_outputs": ["1\n-1\n2"], "notes": "NoteIn the first example, you can replace any letter 'a' with the string \"a\", but that won't change the string. So no matter how many moves you make, you can't obtain a string other than the initial one.In the second example, you can replace the second letter 'a' with \"abc\". String $$$s$$$ becomes equal to \"aabc\". Then the second letter 'a' again. String $$$s$$$ becomes equal to \"aabcbc\". And so on, generating infinitely many different strings.In the third example, you can either leave string $$$s$$$ as is, performing zero moves, or replace the only 'a' with \"b\". String $$$s$$$ becomes equal to \"b\", so you can't perform more moves on it."}, "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(x: String, y: String) = {\r\n if (y.length == 1 && y.head == 'a') 1\r\n else if (y.contains('a')) -1\r\n else Math.pow(2, x.filter(_ == 'a').length).toLong\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 s = readLine();\r\n t = readLine()\r\n ) println(solve(s, t))\r\n }\r\n}\r\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(x: String, y: String) = {\r\n if (y.forall(_ == 'a')) {\r\n if (y.length == 1) 1\r\n else -1\r\n }\r\n else if (y.contains('a')) -1\r\n else 1 + x.filter(_ == 'a').length * y.length\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 s = readLine();\r\n t = readLine()\r\n ) println(solve(s, t))\r\n }\r\n}\r\n"}], "src_uid": "d6ac9ca9cc5dfd9f43f5f65ce226349e"} {"nl": {"description": "Vova's house is an array consisting of $$$n$$$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $$$i$$$-th element of the array is $$$1$$$ if there is a heater in the position $$$i$$$, otherwise the $$$i$$$-th element of the array is $$$0$$$.Each heater has a value $$$r$$$ ($$$r$$$ is the same for all heaters). This value means that the heater at the position $$$pos$$$ can warm up all the elements in range $$$[pos - r + 1; pos + r - 1]$$$.Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if $$$n = 6$$$, $$$r = 2$$$ and heaters are at positions $$$2$$$ and $$$5$$$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $$$3$$$ elements will be warmed up by the first heater and the last $$$3$$$ elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$r$$$ ($$$1 \\le n, r \\le 1000$$$) \u2014 the number of elements in the array and the value of heaters. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$) \u2014 the Vova's house description.", "output_spec": "Print one integer \u2014 the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.", "sample_inputs": ["6 2\n0 1 1 0 0 1", "5 3\n1 0 0 0 1", "5 10\n0 0 0 0 0", "10 3\n0 0 1 1 0 1 0 0 0 1"], "sample_outputs": ["3", "2", "-1", "3"], "notes": "NoteIn the first example the heater at the position $$$2$$$ warms up elements $$$[1; 3]$$$, the heater at the position $$$3$$$ warms up elements $$$[2, 4]$$$ and the heater at the position $$$6$$$ warms up elements $$$[5; 6]$$$ so the answer is $$$3$$$.In the second example the heater at the position $$$1$$$ warms up elements $$$[1; 3]$$$ and the heater at the position $$$5$$$ warms up elements $$$[3; 5]$$$ so the answer is $$$2$$$.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position $$$3$$$ warms up elements $$$[1; 5]$$$, the heater at the position $$$6$$$ warms up elements $$$[4; 8]$$$ and the heater at the position $$$10$$$ warms up elements $$$[8; 10]$$$ so the answer is $$$3$$$."}, "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 P_buf = ArrayBuffer[Int]()\n rep(N) { i =>\n val a = ni()\n if (a == 1) P_buf += i\n }\n val P = P_buf.toArray\n var ans = 0\n var pos = -1\n var heated = -1\n while(heated < N - 1) {\n val x = heated + r\n val ix = upperBound(P, x) - 1\n if (ix == -1 || ix <= pos) {\n out.println(-1)\n return\n }\n heated = P(ix) + r - 1\n ans += 1\n pos = ix\n }\n\n out.println(ans)\n }\n\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 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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "001d8aca7c8421c3e54863f3fb706f0d"} {"nl": {"description": "Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.", "input_spec": "The first line contains two integer numbers $$$N$$$ ($$$1 \\leq N \\leq 200000$$$) representing number of F1 astronauts, and current position of astronaut $$$D$$$ ($$$1 \\leq D \\leq N$$$) you want to calculate best ranking for (no other competitor will have the same number of points before the race). The second line contains $$$N$$$ integer numbers $$$S_k$$$ ($$$0 \\leq S_k \\leq 10^8$$$, $$$k=1...N$$$), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order. The third line contains $$$N$$$ integer numbers $$$P_k$$$ ($$$0 \\leq P_k \\leq 10^8$$$, $$$k=1...N$$$), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.", "output_spec": "Output contains one integer number \u2014 the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.", "sample_inputs": ["4 3\n50 30 20 10\n15 10 7 3"], "sample_outputs": ["2"], "notes": "NoteIf the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position."}, "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, D = ni()\n val S = na(N)\n val P = na(N)\n val p = P.max + S(D - 1)\n\n def rank(cur: Int, prev: Int): Int = {\n if (cur == 0) 0\n else {\n val next = P.indexWhere(_ <= p - S(cur - 1), prev + 1)\n if (next == - 1) cur // \u5024\u304c\u898b\u3064\u304b\u3089\u306a\u3044\n else rank(cur - 1, next)\n }\n }\n\n out.println(rank(D - 1, 0) + 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}"}], "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, D = ni()\n val S = na(N)\n val P = na(N)\n val t = S(D - 1) + P.max - P.min\n out.println(lowerBound(S, t) + 1)\n }\n\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): 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, D = ni()\n val S = na(N)\n val P = na(N)\n val p = P.max + S(D - 1)\n\n def rank(i: Int, prev: Int): Int = {\n if (i == 0) 0\n else {\n val next = lowerBound(P, p - S(i - 1))\n if (prev == next || next == N) i // \u3088\u308a\u5c0f\u3055\u3044\u5024\u304c\u898b\u3064\u304b\u3089\u306a\u3044\n else rank(i - 1, next)\n }\n }\n\n out.println(rank(D - 1, N) + 1)\n }\n\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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "379133abc6fd643517542aabad79c57f"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers and an integer $$$s$$$. It is guaranteed that $$$n$$$ is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $$$s$$$.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $$$6, 5, 8$$$ is equal to $$$6$$$, since if we sort this array we will get $$$5, 6, 8$$$, and $$$6$$$ is located on the middle position.", "input_spec": "The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1\\le n\\le 2\\cdot 10^5-1$$$, $$$1\\le s\\le 10^9$$$)\u00a0\u2014 the length of the array and the required value of median. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1\\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array $$$a$$$. It is guaranteed that $$$n$$$ is odd.", "output_spec": "In a single line output the minimum number of operations to make the median being equal to $$$s$$$.", "sample_inputs": ["3 8\n6 5 8", "7 20\n21 15 12 11 20 19 12"], "sample_outputs": ["2", "6"], "notes": "NoteIn the first sample, $$$6$$$ can be increased twice. The array will transform to $$$8, 5, 8$$$, which becomes $$$5, 8, 8$$$ after sorting, hence the median is equal to $$$8$$$.In the second sample, $$$19$$$ can be increased once and $$$15$$$ can be increased five times. The array will become equal to $$$21, 20, 12, 11, 20, 20, 12$$$. If we sort this array we get $$$11, 12, 12, 20, 20, 20, 21$$$, this way the median is $$$20$$$."}, "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, 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"}, {"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"}, {"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}"}], "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).", "input_spec": "The first line contains one integer $$$n$$$ ($$$13 \\le n < 10^5$$$, $$$n$$$ is odd) \u2014 the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.", "output_spec": "If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.", "sample_inputs": ["13\n8380011223344", "15\n807345619350641"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all."}, "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.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 = ni()\n val S = ns(N)\n val t = N - 10\n val cnt = S.take(t).count(_ == '8') // \u5de6 t\u500b\u306e\u4e2d\u306b'8'\u304c(t+1)/2\u500b\u4ee5\u4e0a\u3042\u308b\n debug(s\"t:$t cnt:$cnt need:${(t + 1) / 2}\")\n if (cnt >= (t + 1) / 2) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\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}"}], "negative_code": [], "src_uid": "99f37936b243907bf4ac1822dc547a61"} {"nl": {"description": "You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{2n}$$$ ($$$1 \\le a_i \\le 10^6$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "If there's no solution, print \"-1\" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.", "sample_inputs": ["3\n1 2 2 1 3 1", "1\n1 1"], "sample_outputs": ["2 1 3 1 1 2", "-1"], "notes": "NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes\u00a0\u2014 this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size: the size he wanted, if he specified one size; any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.", "input_spec": "The first line of the input contains six non-negative integers\u00a0\u2014 the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100\u2009000. The second line contains positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of participants. The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.", "output_spec": "If it is not possible to present a t-shirt to each participant, print \u00abNO\u00bb (without quotes). Otherwise, print n\u2009+\u20091 lines. In the first line print \u00abYES\u00bb (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them.", "sample_inputs": ["0 1 0 1 1 0\n3\nXL\nS,M\nXL,XXL", "1 1 2 0 1 1\n5\nS\nM\nS,M\nXXL,XXXL\nXL,XXL"], "sample_outputs": ["YES\nXL\nM\nXXL", "NO"], "notes": null}, "positive_code": [{"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"}, {"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 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"}, {"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"}], "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"} {"nl": {"description": "Recently Monocarp got a job. His working day lasts exactly $$$m$$$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $$$n$$$ minutes $$$a_1, a_2, \\dots, a_n$$$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $$$a_i$$$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $$$d$$$ minutes pass between any two coffee breaks. Monocarp also wants to take these $$$n$$$ coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $$$d$$$ minutes pass between the end of any working day and the start of the following working day.For each of the $$$n$$$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent. ", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$, $$$d$$$ $$$(1 \\le n \\le 2\\cdot10^{5}, n \\le m \\le 10^{9}, 1 \\le d \\le m)$$$\u00a0\u2014 the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le m)$$$, where $$$a_i$$$ is some minute when Monocarp wants to have a coffee break.", "output_spec": "In the first line, write the minimum number of days required to make a coffee break in each of the $$$n$$$ given minutes. In the second line, print $$$n$$$ space separated integers. The $$$i$$$-th of integers should be the index of the day during which Monocarp should have a coffee break at minute $$$a_i$$$. Days are numbered from $$$1$$$. If there are multiple optimal solutions, you may print any of them.", "sample_inputs": ["4 5 3\n3 5 1 2", "10 10 1\n10 5 7 4 6 3 2 1 9 8"], "sample_outputs": ["3\n3 1 1 2", "2\n2 1 1 2 2 1 2 1 1 2"], "notes": "NoteIn the first example, Monocarp can take two coffee breaks during the first day (during minutes $$$1$$$ and $$$5$$$, $$$3$$$ minutes will pass between these breaks). One break during the second day (at minute $$$2$$$), and one break during the third day (at minute $$$3$$$).In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day."}, "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.util\n val N, M, D = ni()\n val A = na(N)\n val A_rev = mutable.Map[Int, Int]()\n rep(N) { i =>\n A_rev(A(i)) = i\n }\n val bt = new util.TreeSet[Int]()\n A foreach bt.add\n val ans = Array.ofDim[Int](N)\n var days = 1\n\n while(!bt.isEmpty) {\n var x = bt.first()\n while(x != 0) {\n// System.err.println(x)\n bt.remove(x)\n ans(A_rev(x)) = days\n x = bt.higher(x + D)\n }\n days += 1\n }\n\n out.println(days - 1)\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}"}], "negative_code": [], "src_uid": "cc1b29b49711131d4790d91d0fae4a5a"} {"nl": {"description": "You are given a bracket sequence $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences \"()()\", \"(())\" are regular (the resulting expressions are: \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.You can change the type of some bracket $$$s_i$$$. It means that if $$$s_i = $$$ ')' then you can change it to '(' and vice versa.Your task is to calculate the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 10^6$$$) \u2014 the length of the bracket sequence. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.", "output_spec": "Print one integer \u2014 the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.", "sample_inputs": ["6\n(((())", "6\n()()()", "1\n)", "8\n)))((((("], "sample_outputs": ["3", "0", "0", "0"], "notes": null}, "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 '(' => 1\n case ')' => -1\n }\n val cum = cumSum(S)\n val minL = Array.ofDim[Int](N + 1) // \u5de6\u304b\u3089i\u3053\u307e\u3067\u306ecum\u306emin\n REP(N, 1) { i =>\n minL(i) = min(minL(i - 1), cum(i))\n }\n val minR = Array.ofDim[Int](N + 1) // \u53f3\u304b\u3089i\u3053\u307e\u3067\u306ecum\u306emin\n minR(1) = cum(N)\n REP(N - 1, 2) { i =>\n minR(i) = min(minR(i - 1), cum(N + 1 - i))\n }\n\n def count(d: Int): Int = {\n var sum = 0\n REP(N) { i =>\n if (S(i) == d && minL(i) == 0 && minR(N - i) == d * 2) {\n sum += 1\n }\n }\n sum\n }\n\n val ms = cum.min\n if (ms == 0 && cum(N) == 0 || ms < -2 || cum(N) > 2 || cum(N) < -2) {\n out.println(0)\n } else {\n val ans = cum(N) match {\n case 2 => count(1)\n case -2 => count(-1)\n case _ => 0\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}"}], "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).map {\n case '(' => 1\n case ')' => -1\n }\n val cum = cumSum(S)\n val minR = Array.ofDim[Int](N + 1) // \u53f3\u304b\u3089i\u3053\u307e\u3067\u306ecum\u306emin\n minR(1) = cum(N)\n REP(N - 1, 2) { i =>\n minR(i) = min(minR(i - 1), cum(N + 1 - i))\n }\n\n def find1: Option[Int] = {\n REP(N) { i =>\n if (S(i) == 1 && cum(i + 1) >= 2 && minR(N - i) == 2) {\n return Some(i)\n }\n }\n None\n }\n\n def find_1: Option[Int] = {\n REP(N) { i =>\n if (S(i) == -1 && cum(i + 1) < 0 && minR(N - i) == -2) {\n return Some(i)\n }\n }\n None\n }\n\n val ms = cum.min\n if (ms == 0 && cum(N) == 0 || ms < -2 || cum(N) > 2 || cum(N) < -2) {\n out.println(0)\n } else {\n val ans = cum(N) match {\n case 2 => find1\n case -2 => find_1\n case _ => None\n }\n ans match {\n case None => out.println(0)\n case Some(i) => out.println(i + 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 S = ns(N).map {\n case '(' => 1\n case ')' => -1\n }\n val cum = cumSum(S)\n val minR = Array.ofDim[Int](N + 1) // \u53f3\u304b\u3089i\u3053\u307e\u3067\u306ecum\u306emin\n minR(1) = cum(N)\n REP(N - 1, 2) { i =>\n minR(i) = min(minR(i - 1), cum(N + 1 - i))\n }\n\n def find(d: Int): Option[Int] = {\n REP(N) { i =>\n if (S(i) == d && cum(i + 1) >= d * 2 && minR(N - i) == d * 2) {\n return Some(i)\n }\n }\n None\n }\n\n val ms = cum.min\n if (ms == 0 && cum(N) == 0 || ms < -2 || cum(N) > 2 || cum(N) < -2) {\n out.println(0)\n } else {\n val ans = cum(N) match {\n case 2 => find(1)\n case -2 => find(-1)\n case _ => None\n }\n ans match {\n case None => out.println(0)\n case Some(i) => out.println(i + 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": "13aa9c49ffd62d2aa59f3cd8b16a277f"} {"nl": {"description": "A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \\ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.", "input_spec": "Each test consists of multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \\leq n \\leq 100$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\\dots,a_{n}$$$ ($$$1 \\leq a_{i} \\leq 200$$$)\u00a0\u2014 the elements of the array.", "output_spec": "Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.", "sample_inputs": ["4\n3\n8 1 2\n4\n6 9 4 2\n9\n1 2 3 4 5 6 7 8 9\n3\n200 199 198"], "sample_outputs": ["2\n2 1\n4\n2 1 4 3\n9\n6 9 1 2 3 4 5 7 8\n3\n1 2 3"], "notes": "NoteIn the first test case, the subset $$$\\{a_2, a_1\\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\\{a_1, a_3\\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset."}, "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\r\nimport scala.io.StdIn.readLine\r\n\r\nobject WimbledumOde extends App {\r\n\r\n def f(s: Stream[Int], head: Int): Stream[Int] = {\r\n val r = s filter {\r\n x => if(x % head != 0) true else false\r\n }\r\n r\r\n }\r\n\r\n def numStream(n: Int): Stream[Int] = Stream.from(n)\r\n\r\n def sieve(stream: Stream[Int]): Stream[Int] = stream.head #:: sieve(f(stream.tail, stream.head))\r\n\r\n val primes = sieve(numStream(2))\r\n\r\n def isPrime(n: Int): Boolean = {\r\n for (i <- primes) {\r\n if(i == n) return true\r\n if (i > n) return false\r\n }\r\n false\r\n }\r\n\r\n val t = readLine.trim.toInt\r\n for (_ <- 0 until t) {\r\n val n = readLine.trim.toInt\r\n val arr = readLine.trim.split(' ').map(_.toInt).toList\r\n val sum = arr.sum\r\n if(!isPrime(sum)) {\r\n println(n)\r\n val idx = 1 to n\r\n println(idx.mkString(\" \"))\r\n } else {\r\n val oddIndexes : ListBuffer[Int] = ListBuffer()\r\n for(i <- arr.indices) {\r\n if(arr(i) % 2 != 0) oddIndexes += i\r\n }\r\n\r\n val ans:ListBuffer[Int] = ListBuffer()\r\n for(i <- arr.indices) {\r\n if(i != oddIndexes.head) ans += (i+1)\r\n }\r\n\r\n println(n-1)\r\n println(ans.mkString(\" \"))\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject WimbledumOde extends App {\r\n\r\n def f(s: Stream[Int], head: Int): Stream[Int] = {\r\n val r = s filter {\r\n x => if(x % head != 0) true else false\r\n }\r\n r\r\n }\r\n\r\n def numStream(n: Int): Stream[Int] = Stream.from(n)\r\n\r\n def sieve(stream: Stream[Int]): Stream[Int] = stream.head #:: sieve(f(stream.tail, stream.head))\r\n\r\n val primes = sieve(numStream(2))\r\n\r\n def isPrime(n: Int): Boolean = {\r\n for (i <- primes) {\r\n if(i == n) return true\r\n if (i > n) return false\r\n }\r\n false\r\n }\r\n\r\n val t = readLine.trim.toInt\r\n for (_ <- 0 until t) {\r\n val n = readLine.trim.toInt\r\n val arr = readLine.trim.split(' ').map(_.toInt).toList\r\n val sum = arr.sum\r\n if(!isPrime(sum)) {\r\n println(n)\r\n val idx = 1 to n\r\n println(idx.mkString(\" \"))\r\n } else {\r\n val oddIndexes = arr.map(x => if (x%2 != 0) arr.indexOf(x) else -1).filter(x => x > -1)\r\n val ans = arr.map(x => if(x != oddIndexes.head) arr.indexOf(x)+1 else -1).filter(x => x > -1)\r\n println(n-1)\r\n println(ans.mkString(\" \"))\r\n }\r\n }\r\n}"}], "src_uid": "677972c7d86ce9fd0808105331f77fe0"} {"nl": {"description": "One day, Twilight Sparkle is interested in how to sort a sequence of integers a1,\u2009a2,\u2009...,\u2009an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1,\u2009a2,\u2009...,\u2009an\u2009\u2192\u2009an,\u2009a1,\u2009a2,\u2009...,\u2009an\u2009-\u20091. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.", "sample_inputs": ["2\n2 1", "3\n1 3 2", "2\n1 2"], "sample_outputs": ["1", "-1", "0"], "notes": null}, "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": "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": "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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Let's define the following recurrence: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \\cdot maxDigit(a_{n}).$$$$$$Here $$$minDigit(x)$$$ and $$$maxDigit(x)$$$ are the minimal and maximal digits in the decimal representation of $$$x$$$ without leading zeroes. For examples refer to notes.Your task is calculate $$$a_{K}$$$ for given $$$a_{1}$$$ and $$$K$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of independent test cases. Each test case consists of a single line containing two integers $$$a_{1}$$$ and $$$K$$$ ($$$1 \\le a_{1} \\le 10^{18}$$$, $$$1 \\le K \\le 10^{16}$$$) separated by a space.", "output_spec": "For each test case print one integer $$$a_{K}$$$ on a separate line.", "sample_inputs": ["8\n1 4\n487 1\n487 2\n487 3\n487 4\n487 5\n487 6\n487 7"], "sample_outputs": ["42\n487\n519\n528\n544\n564\n588\n628"], "notes": "Note$$$a_{1} = 487$$$ $$$a_{2} = a_{1} + minDigit(a_{1}) \\cdot maxDigit(a_{1}) = 487 + \\min (4, 8, 7) \\cdot \\max (4, 8, 7) = 487 + 4 \\cdot 8 = 519$$$ $$$a_{3} = a_{2} + minDigit(a_{2}) \\cdot maxDigit(a_{2}) = 519 + \\min (5, 1, 9) \\cdot \\max (5, 1, 9) = 519 + 1 \\cdot 9 = 528$$$ $$$a_{4} = a_{3} + minDigit(a_{3}) \\cdot maxDigit(a_{3}) = 528 + \\min (5, 2, 8) \\cdot \\max (5, 2, 8) = 528 + 2 \\cdot 8 = 544$$$ $$$a_{5} = a_{4} + minDigit(a_{4}) \\cdot maxDigit(a_{4}) = 544 + \\min (5, 4, 4) \\cdot \\max (5, 4, 4) = 544 + 4 \\cdot 5 = 564$$$ $$$a_{6} = a_{5} + minDigit(a_{5}) \\cdot maxDigit(a_{5}) = 564 + \\min (5, 6, 4) \\cdot \\max (5, 6, 4) = 564 + 4 \\cdot 6 = 588$$$ $$$a_{7} = a_{6} + minDigit(a_{6}) \\cdot maxDigit(a_{6}) = 588 + \\min (5, 8, 8) \\cdot \\max (5, 8, 8) = 588 + 5 \\cdot 8 = 628$$$"}, "positive_code": [{"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.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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the number of pearls in a row. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2013 the type of the i-th pearl.", "output_spec": "On the first line print integer k \u2014 the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj,\u2009rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n) \u2014 the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number \"-1\".", "sample_inputs": ["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"], "sample_outputs": ["1\n1 5", "-1", "2\n1 3\n4 7"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": " One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like \"Hidden to the left of the i-th box\" (\"To the left of i\"), \"Hidden to the right of the i-th box\" (\"To the right of i\"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20090\u2009\u2264\u2009m\u2009\u2264\u20091000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like \"To the left of i\" and \"To the right of i\", where i is integer (1\u2009\u2264\u2009i\u2009\u2264\u2009n). The hints may coincide.", "output_spec": "The answer should contain exactly one integer \u2014 the number of boxes that should necessarily be checked or \"-1\" if the hints are contradictory.", "sample_inputs": ["2 1\nTo the left of 2", "3 2\nTo the right of 1\nTo the right of 2", "3 1\nTo the left of 3", "3 2\nTo the left of 2\nTo the right of 1"], "sample_outputs": ["1", "1", "2", "-1"], "notes": null}, "positive_code": [{"source_code": "object P60A extends App {\n val Array(n,m) = readLine.split(\" \").map(_.toInt)\n var l = n+1\n var r = 0\n for(e <- 1 to m) {\n val Array(to, the, direction, of, i) = readLine.split(\" \")\n if(direction == \"left\") l = Math.min(l, i.toInt) else r = Math.max(r, i.toInt)\n }\n print(if (l <= r+1) -1 else l-r-1)\n}\n"}], "negative_code": [], "src_uid": "dabeb9852332f6a6e730acab7fe61a5c"} {"nl": {"description": "Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.", "input_spec": "The first line contains integer $$$n$$$ ($$$2 \\le n \\le 200\\,000$$$)\u00a0\u2014 the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.", "output_spec": "Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.", "sample_inputs": ["5\n0 0 1 0 0", "4\n1 0 0 1"], "sample_outputs": ["3", "3"], "notes": "NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit."}, "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)\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.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 _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"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "653455bb6762effbf7358d75660a7689"} {"nl": {"description": "You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.", "input_spec": "The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.", "output_spec": "The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.", "sample_inputs": ["24\n17:30", "12\n17:30", "24\n99:99"], "sample_outputs": ["17:30", "07:30", "09:09"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).A bill $$$x \\times y$$$ fits into some wallet $$$h \\times w$$$ if either $$$x \\le h$$$ and $$$y \\le w$$$ or $$$y \\le h$$$ and $$$x \\le w$$$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.Now you are asked to perform the queries of two types: $$$+~x~y$$$ \u2014 Polycarp earns a bill of size $$$x \\times y$$$; $$$?~h~w$$$ \u2014 Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \\times w$$$. It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.For each query of type $$$2$$$ print \"YES\" if all the bills he has earned to this moment fit into a wallet of given size. Print \"NO\" otherwise.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 5 \\cdot 10^5$$$) \u2014 the number of queries. Each of the next $$$n$$$ lines contains a query of one of these two types: $$$+~x~y$$$ ($$$1 \\le x, y \\le 10^9$$$) \u2014 Polycarp earns a bill of size $$$x \\times y$$$; $$$?~h~w$$$ ($$$1 \\le h, w \\le 10^9$$$) \u2014 Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \\times w$$$. It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.", "output_spec": "For each query of type $$$2$$$ print \"YES\" if all the bills he has earned to this moment fit into a wallet of given size. Print \"NO\" otherwise.", "sample_inputs": ["9\n+ 3 2\n+ 2 3\n? 1 20\n? 3 3\n? 2 3\n+ 1 5\n? 10 10\n? 1 5\n+ 1 1"], "sample_outputs": ["NO\nYES\nYES\nYES\nNO"], "notes": "NoteThe queries of type $$$2$$$ of the example: Neither bill fits; Both bills fit (just checking that you got that bills can overlap); Both bills fit (both bills are actually the same); All bills fit (too much of free space in a wallet is not a problem); Only bill $$$1 \\times 5$$$ fit (all the others don't, thus it's \"NO\"). "}, "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 // 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}"}, {"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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). ", "output_spec": "For each query print one integer in a single line \u2014 the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.", "sample_inputs": ["2\n5\n3 1 2 3 1\n7\n1 1 1 1 1 2 2"], "sample_outputs": ["3\n3"], "notes": "NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \\rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \\rightarrow [1, 1, 1, 1, 2, 3] \\rightarrow [1, 1, 1, 3, 3] \\rightarrow [2, 1, 3, 3] \\rightarrow [3, 3, 3]$$$."}, "positive_code": [{"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 _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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "e59cddb6c941b1d7556ee9c020701007"} {"nl": {"description": "The Olympic Games have just started and Federico is eager to watch the marathon race.There will be $$$n$$$ athletes, numbered from $$$1$$$ to $$$n$$$, competing in the marathon, and all of them have taken part in $$$5$$$ important marathons, numbered from $$$1$$$ to $$$5$$$, in the past. For each $$$1\\le i\\le n$$$ and $$$1\\le j\\le 5$$$, Federico remembers that athlete $$$i$$$ ranked $$$r_{i,j}$$$-th in marathon $$$j$$$ (e.g., $$$r_{2,4}=3$$$ means that athlete $$$2$$$ was third in marathon $$$4$$$).Federico considers athlete $$$x$$$ superior to athlete $$$y$$$ if athlete $$$x$$$ ranked better than athlete $$$y$$$ in at least $$$3$$$ past marathons, i.e., $$$r_{x,j}<r_{y,j}$$$ for at least $$$3$$$ distinct values of $$$j$$$.Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 50\\,000$$$) \u2014 the number of athletes. Then $$$n$$$ lines follow, each describing the ranking positions of one athlete. The $$$i$$$-th of these lines contains the $$$5$$$ integers $$$r_{i,1},\\,r_{i,2},\\,r_{i,3},\\,r_{i,4},\\, r_{i,5}$$$ ($$$1\\le r_{i,j}\\le 50\\,000$$$) \u2014 the ranking positions of athlete $$$i$$$ in the past $$$5$$$ marathons. It is guaranteed that, in each of the $$$5$$$ past marathons, the $$$n$$$ athletes have distinct ranking positions, i.e., for each $$$1\\le j\\le 5$$$, the $$$n$$$ values $$$r_{1,j},\\, r_{2, j},\\, \\dots,\\, r_{n, j}$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$50\\,000$$$.", "output_spec": "For each test case, print a single integer \u2014 the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print $$$-1$$$. If there is more than such one athlete, print any of them.", "sample_inputs": ["4\n1\n50000 1 50000 50000 50000\n3\n10 10 20 30 30\n20 20 30 10 10\n30 30 10 20 20\n3\n1 1 1 1 1\n2 2 2 2 2\n3 3 3 3 3\n6\n9 5 3 7 1\n7 4 1 6 8\n5 6 7 3 2\n6 7 8 8 6\n4 2 2 4 5\n8 3 6 9 4"], "sample_outputs": ["1\n-1\n1\n5"], "notes": "NoteExplanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal.Explanation of the second test case: There are $$$n=3$$$ athletes. Athlete $$$1$$$ is superior to athlete $$$2$$$. Indeed athlete $$$1$$$ ranks better than athlete $$$2$$$ in the marathons $$$1$$$, $$$2$$$ and $$$3$$$. Athlete $$$2$$$ is superior to athlete $$$3$$$. Indeed athlete $$$2$$$ ranks better than athlete $$$3$$$ in the marathons $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$. Athlete $$$3$$$ is superior to athlete $$$1$$$. Indeed athlete $$$3$$$ ranks better than athlete $$$1$$$ in the marathons $$$3$$$, $$$4$$$ and $$$5$$$. Explanation of the third test case: There are $$$n=3$$$ athletes. Athlete $$$1$$$ is superior to athletes $$$2$$$ and $$$3$$$. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete $$$2$$$ is superior to athlete $$$3$$$. Athlete $$$3$$$ is not superior to any other athlete. Explanation of the fourth test case: There are $$$n=6$$$ athletes. Athlete $$$1$$$ is superior to athletes $$$3$$$, $$$4$$$, $$$6$$$. Athlete $$$2$$$ is superior to athletes $$$1$$$, $$$4$$$, $$$6$$$. Athlete $$$3$$$ is superior to athletes $$$2$$$, $$$4$$$, $$$6$$$. Athlete $$$4$$$ is not superior to any other athlete. Athlete $$$5$$$ is superior to athletes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$6$$$. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete $$$6$$$ is only superior to athlete $$$4$$$. "}, "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 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"}, {"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": "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"}], "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"} {"nl": {"description": " For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it! Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent\u00a0\u2014 cubes.For completing the chamber Wheatley needs $$$n$$$ cubes. $$$i$$$-th cube has a volume $$$a_i$$$.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $$$i>1$$$, $$$a_{i-1} \\le a_i$$$ must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $$$i>1$$$ you can exchange cubes on positions $$$i-1$$$ and $$$i$$$.But there is a problem: Wheatley is very impatient. If Wheatley needs more than $$$\\frac{n \\cdot (n-1)}{2}-1$$$ exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 1000$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \\le n \\le 5 \\cdot 10^4$$$)\u00a0\u2014 number of cubes. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 volumes of cubes. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a word in a single line: \"YES\" (without quotation marks) if the cubes can be sorted and \"NO\" (without quotation marks) otherwise.", "sample_inputs": ["3\n5\n5 3 2 1 4\n6\n2 2 2 2 2 2\n2\n2 1"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteIn the first test case it is possible to sort all the cubes in $$$7$$$ exchanges.In the second test case the cubes are already sorted.In the third test case we can make $$$0$$$ exchanges, but the cubes are not sorted yet, so the answer is \"NO\"."}, "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"}, {"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"}], "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"} {"nl": {"description": "Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1,\u2009v2,\u2009...,\u2009vn a plan, if v1\u2009+\u2009v2\u2009+\u2009...\u2009+\u2009vn\u2009=\u2009m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total.Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod.", "input_spec": "The first line contains four integers n, m, b, mod (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500, 0\u2009\u2264\u2009b\u2009\u2264\u2009500; 1\u2009\u2264\u2009mod\u2009\u2264\u2009109\u2009+\u20097)\u00a0\u2014 the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009500)\u00a0\u2014 the number of bugs per line for each programmer.", "output_spec": "Print a single integer \u2014 the answer to the problem modulo mod.", "sample_inputs": ["3 3 3 100\n1 1 1", "3 6 5 1000000007\n1 2 3", "3 5 6 11\n1 2 1"], "sample_outputs": ["10", "0", "0"], "notes": null}, "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\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": "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 *\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 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 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"} {"nl": {"description": "Let $$$n$$$ be a positive integer. Let $$$a, b, c$$$ be nonnegative integers such that $$$a + b + c = n$$$.Alice and Bob are gonna play rock-paper-scissors $$$n$$$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $$$a$$$ times, paper $$$b$$$ times, and scissors $$$c$$$ times.Alice wins if she beats Bob in at least $$$\\lceil \\frac{n}{2} \\rceil$$$ ($$$\\frac{n}{2}$$$ rounded up to the nearest integer) hands, otherwise Alice loses.Note that in rock-paper-scissors: rock beats scissors; paper beats rock; scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers $$$a, b, c$$$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.If there are multiple answers, print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then, $$$t$$$ testcases follow, each consisting of three lines: The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$). The second line contains three integers, $$$a, b, c$$$ ($$$0 \\le a, b, c \\le n$$$). It is guaranteed that $$$a + b + c = n$$$. The third line contains a string $$$s$$$ of length $$$n$$$. $$$s$$$ is made up of only 'R', 'P', and 'S'. The $$$i$$$-th character is 'R' if for his $$$i$$$-th Bob plays rock, 'P' if paper, and 'S' if scissors. ", "output_spec": "For each testcase: If Alice cannot win, print \"NO\" (without the quotes). Otherwise, print \"YES\" (without the quotes). Also, print a string $$$t$$$ of length $$$n$$$ made up of only 'R', 'P', and 'S' \u2014 a sequence of hands that Alice can use to win. $$$t$$$ must contain exactly $$$a$$$ 'R's, $$$b$$$ 'P's, and $$$c$$$ 'S's. If there are multiple answers, print any of them. The \"YES\" / \"NO\" part of the output is case-insensitive (i.e. \"yEs\", \"no\" or \"YEs\" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive.", "sample_inputs": ["2\n3\n1 1 1\nRPS\n3\n3 0 0\nRPS"], "sample_outputs": ["YES\nPSR\nNO"], "notes": "NoteIn the first testcase, in the first hand, Alice plays paper and Bob plays rock, so Alice beats Bob. In the second hand, Alice plays scissors and Bob plays paper, so Alice beats Bob. In the third hand, Alice plays rock and Bob plays scissors, so Alice beats Bob. Alice beat Bob 3 times, and $$$3 \\ge \\lceil \\frac{3}{2} \\rceil = 2$$$, so Alice wins.In the second testcase, the only sequence of hands that Alice can play is \"RRR\". Alice beats Bob only in the last hand, so Alice can't win. $$$1 < \\lceil \\frac{3}{2} \\rceil = 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 @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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Leha decided to move to a quiet town Vi\u010dkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vi\u010dkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109\u2009+\u20097.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) denoting the number of hacked computers. The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.", "output_spec": "Print a single integer\u00a0\u2014 the required sum modulo 109\u2009+\u20097.", "sample_inputs": ["2\n4 7", "3\n4 3 1"], "sample_outputs": ["3", "9"], "notes": "NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7\u2009-\u20094\u2009=\u20093. In total the answer is 0\u2009+\u20090\u2009+\u20093\u2009=\u20093.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4\u2009-\u20093)\u2009+\u2009(4\u2009-\u20091)\u2009+\u2009(3\u2009-\u20091)\u2009+\u2009(4\u2009-\u20091)\u2009=\u20099."}, "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"}, {"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"}], "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"} {"nl": {"description": "You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino \"1-4\" turns into \"4-1\").", "input_spec": "The first line contains number n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u2009100). Next n lines contains the dominoes. Each of these lines contains two numbers \u2014 the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.", "output_spec": "Print \"No solution\", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character \"+\" (if you don't need to turn the domino) or \"\u2013\" (if you need to turn it).", "sample_inputs": ["5\n1 2\n2 4\n2 4\n6 4\n2 1"], "sample_outputs": ["2 -\n1 -\n5 -\n3 +\n4 -"], "notes": null}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject B {\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 var graph: Array[Array[Int]] = new Array(7);\n var dominoes: List[(Int, Int)] = List();\n\n def dfs(v: Int): List[Int] = {\n var ans: List[Int] = List();\n for (j <- 1 to graph(v)(v)) {\n if (graph(v)(v) > 0) {\n graph(v)(v) = graph(v)(v) - 1;\n ans = dfs(v) ++ ans;\n }\n }\n\n for (i <- 0 to 6) {\n for (j <- 1 to graph(v)(i)) {\n if (graph(v)(i) > 0) {\n graph(v)(i) = graph(v)(i) - 1;\n graph(i)(v) = graph(i)(v) - 1;\n ans = dfs(i) ++ ans;\n }\n }\n }\n v :: ans;\n }\n\n def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {\n if (pair1 == pair2)\n 1;\n else if (pair1.swap == pair2)\n 2;\n else\n 0;\n }\n\n def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {\n val t = get_type(pair, z.head);\n if (t != 0) {\n if (t == 1) {\n println(ind + \" +\");\n } else {\n println(ind + \" -\");\n }\n (-1, -1) :: z.tail;\n } else {\n z.head :: answer(z.tail, pair, ind + 1);\n }\n }\n\n def main(args: Array[String]) {\n val n = nextInt;\n\n for (i <- 0 to 6) {\n graph(i) = new Array(7);\n for (j <- 0 to 6) {\n graph(i)(j) = 0;\n }\n }\n\n for (i <- 1 to n) {\n val a = nextInt;\n val b = nextInt;\n if (a != b) {\n graph(a)(b) = graph(a)(b) + 1;\n graph(b)(a) = graph(b)(a) + 1;\n } else {\n graph(a)(a) = graph(a)(a) + 1;\n }\n dominoes = dominoes ++ List((a, b));\n }\n\n var start = -1;\n var count = 0;\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n sum += graph(i)(i);\n count += (sum % 2);\n }\n\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n sum += graph(i)(i);\n if (sum > 0 && start == -1)\n start = i;\n if (sum % 2 == 1)\n start = i;\n }\n if (count != 2 && count != 0) {\n println(\"No solution\");\n return ;\n }\n val cicle: List[Int] = if (start == -1) List() else dfs(start);\n // println(cicle.toString + \" \" + n);\n if (cicle.length != n + 1) {\n println(\"No solution\");\n return ;\n }\n for (i <- 0 to (cicle.length - 2)) {\n dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);\n }\n }\n}"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject B {\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 var graph: Array[Array[Int]] = new Array(7);\n var dominoes: List[(Int, Int)] = List();\n\n def dfs(v: Int): List[Int] = {\n var ans: List[Int] = List();\n for (i <- 0 to 6) {\n for (j <- 1 to graph(v)(i)) {\n if (graph(v)(i) > 0) {\n graph(v)(i) = graph(v)(i) - 1;\n graph(i)(v) = graph(i)(v) - 1;\n ans = dfs(i) ++ ans;\n }\n }\n }\n v :: ans;\n }\n\n def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {\n if (pair1 == pair2)\n 1;\n else if (pair1.swap == pair2)\n 2;\n else\n 0;\n }\n\n def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {\n val t = get_type(pair, z.head);\n if (t != 0) {\n if (t == 1) {\n println(ind + \" +\");\n } else {\n println(ind + \" -\");\n }\n (-1, -1) :: z.tail;\n } else {\n z.head :: answer(z.tail, pair, ind + 1);\n }\n }\n\n def main(args: Array[String]) {\n val n = nextInt;\n\n for (i <- 0 to 6) {\n graph(i) = new Array(7);\n for (j <- 0 to 6) {\n graph(i)(j) = 0;\n }\n }\n\n for (i <- 1 to n) {\n val a = nextInt;\n val b = nextInt;\n if (a != b) {\n graph(a)(b) = graph(a)(b) + 1;\n graph(b)(a) = graph(b)(a) + 1;\n } else {\n graph(a)(a) = graph(a)(a) + 1;\n }\n dominoes = dominoes ++ List((a, b));\n }\n\n var start = -1;\n var count = 0;\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n count += (sum % 2);\n }\n\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n if (sum > 0 && start == -1)\n start = i;\n if (sum % 2 == 1)\n start = i;\n }\n\n if (count != 2 && count != 0) {\n println(\"No solution\");\n return ;\n }\n val cicle: List[Int] = dfs(start);\n for (i <- 0 to (cicle.length - 2)) {\n dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);\n }\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject B {\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 var graph: Array[Array[Int]] = new Array(7);\n var dominoes: List[(Int, Int)] = List();\n\n def dfs(v: Int): List[Int] = {\n var ans: List[Int] = List();\n for (i <- 0 to 6) {\n for (j <- 1 to graph(v)(i)) {\n if (graph(v)(i) > 0) {\n graph(v)(i) = graph(v)(i) - 1;\n graph(i)(v) = graph(i)(v) - 1;\n ans = dfs(i) ++ ans;\n }\n }\n }\n v :: ans;\n }\n\n def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {\n if (pair1 == pair2)\n 1;\n else if (pair1.swap == pair2)\n 2;\n else\n 0;\n }\n\n def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {\n val t = get_type(pair, z.head);\n if (t != 0) {\n if (t == 1) {\n println(ind + \" +\");\n } else {\n println(ind + \" -\");\n }\n (-1, -1) :: z.tail;\n } else {\n z.head :: answer(z.tail, pair, ind + 1);\n }\n }\n\n def main(args: Array[String]) {\n val n = nextInt;\n\n for (i <- 0 to 6) {\n graph(i) = new Array(7);\n for (j <- 0 to 6) {\n graph(i)(j) = 0;\n }\n }\n\n for (i <- 1 to n) {\n val a = nextInt;\n val b = nextInt;\n if (a != b) {\n graph(a)(b) = graph(a)(b) + 1;\n graph(b)(a) = graph(b)(a) + 1;\n } else {\n graph(a)(a) = graph(a)(a) + 1;\n }\n dominoes = dominoes ++ List((a, b));\n }\n\n var start = -1;\n var count = 0;\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n sum += graph(i)(i);\n count += (sum % 2);\n }\n\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n sum += graph(i)(i);\n if (sum > 0 && start == -1)\n start = i;\n if (sum % 2 == 1)\n start = i;\n }\n\n if (count != 2 && count != 0) {\n println(\"No solution\");\n return ;\n }\n val cicle: List[Int] = dfs(start);\n for (i <- 0 to (cicle.length - 2)) {\n dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);\n }\n }\n}"}, {"source_code": "import java.util.StringTokenizer\n\nobject B {\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 var graph: Array[Array[Int]] = new Array(7);\n var dominoes: List[(Int, Int)] = List();\n\n def dfs(v: Int): List[Int] = {\n var ans: List[Int] = List();\n for (j <- 1 to graph(v)(v)) {\n if (graph(v)(v) > 0) {\n graph(v)(v) = graph(v)(v) - 1;\n ans = dfs(v) ++ ans;\n }\n }\n\n for (i <- 0 to 6) {\n for (j <- 1 to graph(v)(i)) {\n if (graph(v)(i) > 0) {\n graph(v)(i) = graph(v)(i) - 1;\n graph(i)(v) = graph(i)(v) - 1;\n ans = dfs(i) ++ ans;\n }\n }\n }\n v :: ans;\n }\n\n def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {\n if (pair1 == pair2)\n 1;\n else if (pair1.swap == pair2)\n 2;\n else\n 0;\n }\n\n def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {\n val t = get_type(pair, z.head);\n if (t != 0) {\n if (t == 1) {\n println(ind + \" +\");\n } else {\n println(ind + \" -\");\n }\n (-1, -1) :: z.tail;\n } else {\n z.head :: answer(z.tail, pair, ind + 1);\n }\n }\n\n def main(args: Array[String]) {\n val n = nextInt;\n\n for (i <- 0 to 6) {\n graph(i) = new Array(7);\n for (j <- 0 to 6) {\n graph(i)(j) = 0;\n }\n }\n\n for (i <- 1 to n) {\n val a = nextInt;\n val b = nextInt;\n if (a != b) {\n graph(a)(b) = graph(a)(b) + 1;\n graph(b)(a) = graph(b)(a) + 1;\n } else {\n graph(a)(a) = graph(a)(a) + 1;\n }\n dominoes = dominoes ++ List((a, b));\n }\n\n var start = -1;\n var count = 0;\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n sum += graph(i)(i);\n count += (sum % 2);\n }\n\n for (i <- 0 to 6) {\n var sum = 0;\n for (j <- 0 to 6) {\n sum += graph(i)(j);\n }\n sum += graph(i)(i);\n if (sum > 0 && start == -1)\n start = i;\n if (sum % 2 == 1)\n start = i;\n }\n if (count != 2 && count != 0) {\n println(\"No solution\");\n return ;\n }\n val cicle: List[Int] = if (start == -1) List() else dfs(start);\n //println(cicle.toString);\n if (cicle.length != count + 2) {\n println(\"No solution\");\n return ;\n }\n for (i <- 0 to (cicle.length - 2)) {\n dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);\n }\n }\n}"}], "src_uid": "0c0ec1bb75f00f732b8b091ffe73e6c0"} {"nl": {"description": "The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.", "input_spec": "The first line of the input contains two integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1\u2009\u2264\u2009j\u2009\u2264\u2009n, 1\u2009\u2264\u2009i\u2009\u2264\u2009m, 0\u2009\u2264\u2009aij\u2009\u2264\u2009109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.", "output_spec": "Print a single number \u2014 the index of the candidate who won the elections. The candidates are indexed starting from one.", "sample_inputs": ["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"], "sample_outputs": ["2", "1"], "notes": "NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols (\u00ab_\u00bb). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types: transform lowercase letters to uppercase and vice versa; change letter \u00abO\u00bb (uppercase latin letter) to digit \u00ab0\u00bb and vice versa; change digit \u00ab1\u00bb (one) to any letter among \u00abl\u00bb (lowercase latin \u00abL\u00bb), \u00abI\u00bb (uppercase latin \u00abi\u00bb) and vice versa, or change one of these letters to other. For example, logins \u00abCodeforces\u00bb and \u00abcodef0rces\u00bb as well as \u00abOO0OOO00O0OOO0O00OOO0OO_lol\u00bb and \u00abOO0OOO0O00OOO0O00OO0OOO_1oI\u00bb are considered similar whereas \u00abCodeforces\u00bb and \u00abCode_forces\u00bb are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.", "input_spec": "The first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols (\u00ab_\u00bb) with length not exceeding 50 \u00a0\u2014 the login itself. The second line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000)\u00a0\u2014 the number of existing logins. The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.", "output_spec": "Print \u00abYes\u00bb (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it. Otherwise print \u00abNo\u00bb (without quotes).", "sample_inputs": ["1_wat\n2\n2_wat\nwat_1", "000\n3\n00\nooA\noOo", "_i_\n3\n__i_\n_1_\nI", "La0\n3\n2a0\nLa1\n1a0", "abc\n1\naBc", "0Lil\n2\nLIL0\n0Ril"], "sample_outputs": ["Yes", "No", "No", "No", "No", "Yes"], "notes": "NoteIn the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.In the third sample case the new login is similar with the second one."}, "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"}, {"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"} {"nl": {"description": "You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$3 \\le n \\le 3 \\cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) \u2014 the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.", "output_spec": "Print one string \u2014 the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.", "sample_inputs": ["3\n121", "6\n000000", "6\n211200", "6\n120110"], "sample_outputs": ["021", "001122", "211200", "120120"], "notes": null}, "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 // \u3053\u306e\u6642\u70b9\u30671\u4ee5\u5916\u306f+\u306b\u306a\u3063\u3066\u3044\u308b\n // <-\u306e\u65b9\u5411\u30670\u30921\u306b\u3059\u308b\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 // ->\u306e\u65b9\u5411\u30672\u30921\u306b\u3059\u308b\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}"}, {"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"}], "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"} {"nl": {"description": "At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$\u00a0\u2014 is the maximum possible ($$$k$$$\u00a0\u2014 any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.", "input_spec": "The first line of input data contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases . Each test case is a string containing a single integer $$$m$$$ ($$$1 \\le m \\le 10^9$$$)\u00a0\u2014 the price of the item.", "output_spec": "For each test case, output on a separate line a single integer $$$d$$$ ($$$0 \\le d < m$$$) such that if you reduce the cost of the item by $$$d$$$ bourles, the cost of the item will be the maximal possible round number. More formally: $$$m - d = 10^k$$$, where $$$k$$$\u00a0\u2014 the maximum possible non-negative integer.", "sample_inputs": ["7\n\n1\n\n2\n\n178\n\n20\n\n999999999\n\n9000\n\n987654321"], "sample_outputs": ["0\n1\n78\n10\n899999999\n8000\n887654321"], "notes": "NoteIn the example: $$$1 - 0 = 10^0$$$, $$$2 - 1 = 10^0$$$, $$$178 - 78 = 10^2$$$, $$$20 - 10 = 10^1$$$, $$$999999999 - 899999999 = 10^8$$$, $$$9000 - 8000 = 10^3$$$, $$$987654321 - 887654321 = 10^8$$$. Note that in each test case, we get the maximum possible round number."}, "positive_code": [{"source_code": "object p1 extends App{\n val i = io.StdIn.readInt()\n\n for (_ <- 1 to i) {\n val num = io.StdIn.readInt()\n println(num - findRound(num))\n }\n\n\n\n def findRound(i: Int) = {\n var pow = 0\n\n while (math.pow(10, pow +1 ) <= i) {\n pow += 1;\n }\n math.pow(10, pow).asInstanceOf[Int]\n }\n}\n"}], "negative_code": [], "src_uid": "5312a505bd59b55a6c5487f67a33d81a"} {"nl": {"description": "One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.", "input_spec": "The only line of the input contains one integer n (7\u2009\u2264\u2009n\u2009\u2264\u2009777) \u2014 the number of potential employees that sent resumes.", "output_spec": "Output one integer \u2014 the number of different variants of group composition.", "sample_inputs": ["7"], "sample_outputs": ["29"], "notes": null}, "positive_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: 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Valera has 2\u00b7n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer \u2014 the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains 2\u00b7n space-separated integers ai (10\u2009\u2264\u2009ai\u2009\u2264\u200999), denoting the numbers on the cubes.", "output_spec": "In the first line print a single number \u2014 the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2\u00b7n numbers bi (1\u2009\u2264\u2009bi\u2009\u2264\u20092). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.", "sample_inputs": ["1\n10 99", "2\n13 24 13 45"], "sample_outputs": ["1\n2 1", "4\n1 2 2 1"], "notes": "NoteIn the first test case Valera can put the first cube in the first heap, and second cube \u2014 in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313,\u20091345,\u20092413,\u20092445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345."}, "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n val source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if !set.contains(el) =>\n (c1, c2, f1, f2, 2 :: res, set + (el -> 1))\n case ((c1, c2, f1, f2, res, set), el) if set(el) == 1 =>\n (c1, c2, f1, f2, 1 :: res, set + (el -> (set(el) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if f2 <= f1 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set(el) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))\n }._5.reverse.mkString(\" \"))\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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if !set.contains(el) =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> 1))\n case ((c1, c2, f1, f2, res, set), el) if set(el) == 1 =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if f2 >= f1 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set(el) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))\n }._5.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 < f2 =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n }._5.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n println(source.foldLeft((0, 0, List.empty[Int], Set.empty[Int])) {\n case ((c1, c2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, 1 :: res, set)\n else (c1, c2 + 1, 2 :: res, set)\n case ((c1, c2, res, set), el) if set.contains(el) =>\n (c1, c2 + 1, 2 :: res, set)\n case ((c1, c2, res, set), el) =>\n (c1 + 1, c2, 1 :: res, set + el)\n }._3.reverse.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1 + 1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2 + 1, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>\n (c1, c2 + 1, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 <= f2 =>\n (c1 + 1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2 + 1, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n }._5.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1 + 1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2 + 1, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 < f2 =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n }._5.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1 + 1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2 + 1, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 <= f2 =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n }._5.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if !set.contains(el) =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> 1))\n case ((c1, c2, f1, f2, res, set), el) if set(el) == 1 =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if f2 <= f1 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set(el) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))\n }._5.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, List.empty[Int], Set.empty[Int])) {\n case ((c1, c2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, 1 :: res, set)\n else (c1, c2 + 1, 2 :: res, set)\n case ((c1, c2, res, set), el) if set.contains(el) =>\n (c1, c2 + 1, 2 :: res, set)\n case ((c1, c2, res, set), el) =>\n (c1 + 1, c2, 1 :: res, set + el)\n }._3.reverse.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 source = in.next().split(\" \").map(_.toInt)\n val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet\n val double = source.groupBy(x => x).filter(_._2.length > 1).keySet\n val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)\n println(count)\n println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {\n case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>\n if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)\n else (c1, c2 + 1, f1, f2, 2 :: res, set)\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 < f2 =>\n (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n case ((c1, c2, f1, f2, res, set), el) =>\n (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))\n }._5.reverse.mkString(\" \"))\n\n\n}"}], "src_uid": "080287f34b0c1d52eb29eb81dada41dd"} {"nl": {"description": "Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms \u2014 the left one and the right one. The robot can consecutively perform the following actions: Take the leftmost item with the left hand and spend wi\u2009\u00b7\u2009l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; Take the rightmost item with the right hand and spend wj\u2009\u00b7\u2009r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.", "input_spec": "The first line contains five integers n,\u2009l,\u2009r,\u2009Ql,\u2009Qr (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u20091\u2009\u2264\u2009l,\u2009r\u2009\u2264\u2009100;\u20091\u2009\u2264\u2009Ql,\u2009Qr\u2009\u2264\u2009104). The second line contains n integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u2009100).", "output_spec": "In the single line print a single number \u2014 the answer to the problem.", "sample_inputs": ["3 4 4 19 1\n42 3 99", "4 7 2 3 9\n1 2 3 4"], "sample_outputs": ["576", "34"], "notes": "NoteConsider the first sample. As l\u2009=\u2009r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4\u00b742\u2009+\u20094\u00b799\u2009+\u20094\u00b73\u2009=\u2009576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2\u00b74)\u2009+\u2009(7\u00b71)\u2009+\u2009(2\u00b73)\u2009+\u2009(2\u00b72\u2009+\u20099)\u2009=\u200934 energy units."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Monocarp has got two strings $$$s$$$ and $$$t$$$ having equal length. Both strings consist of lowercase Latin letters \"a\" and \"b\". Monocarp wants to make these two strings $$$s$$$ and $$$t$$$ equal to each other. He can do the following operation any number of times: choose an index $$$pos_1$$$ in the string $$$s$$$, choose an index $$$pos_2$$$ in the string $$$t$$$, and swap $$$s_{pos_1}$$$ with $$$t_{pos_2}$$$.You have to determine the minimum number of operations Monocarp has to perform to make $$$s$$$ and $$$t$$$ equal, and print any optimal sequence of operations \u2014 or say that it is impossible to make these strings equal.", "input_spec": "The first line contains one integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^{5})$$$ \u2014 the length of $$$s$$$ and $$$t$$$. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters \"a\" and \"b\". The third line contains one string $$$t$$$ consisting of $$$n$$$ characters \"a\" and \"b\". ", "output_spec": "If it is impossible to make these strings equal, print $$$-1$$$. Otherwise, in the first line print $$$k$$$ \u2014 the minimum number of operations required to make the strings equal. In each of the next $$$k$$$ lines print two integers \u2014 the index in the string $$$s$$$ and the index in the string $$$t$$$ that should be used in the corresponding swap operation. ", "sample_inputs": ["4\nabab\naabb", "1\na\nb", "8\nbabbaabb\nabababaa"], "sample_outputs": ["2\n3 3\n3 2", "-1", "3\n2 6\n1 3\n7 8"], "notes": "NoteIn the first example two operations are enough. For example, you can swap the third letter in $$$s$$$ with the third letter in $$$t$$$. Then $$$s = $$$ \"abbb\", $$$t = $$$ \"aaab\". Then swap the third letter in $$$s$$$ and the second letter in $$$t$$$. Then both $$$s$$$ and $$$t$$$ are equal to \"abab\".In the second example it's impossible to make two strings equal."}, "positive_code": [{"source_code": "object Main extends App {\n import scala.io.StdIn._\n val n = readInt()\n val s = readLine.trim\n val t = readLine.trim\n if ((s.count(_ == 'a') + t.count(_ == 'a')) % 2 != 0) {\n println(-1)\n }else {\n val diffA = (0 until n).filter(i \u21d2 s(i) == 'a' && s(i) != t(i))\n val diffB = (0 until n).filter(i \u21d2 s(i) == 'b' && s(i) != t(i))\n println((diffA.length + 1) / 2 + (diffB.length + 1) / 2)\n for (i \u2190 diffA.indices by 2 if diffA.indices.contains(i + 1)) {\n println(s\"${diffA(i) + 1} ${diffA(i + 1) + 1}\")\n }\n for (i \u2190 diffB.indices by 2 if diffB.indices.contains(i + 1)) {\n println(s\"${diffB(i) + 1} ${diffB(i + 1) + 1}\")\n }\n if (diffA.length % 2 == 1) {\n println(s\"${diffA.last + 1} ${diffA.last + 1}\")\n println(s\"${diffA.last + 1} ${diffB.last + 1}\")\n }\n }\n}"}], "negative_code": [], "src_uid": "181199a0cf37c83cec1ba28d343b50ae"} {"nl": {"description": "Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters \"a\" and \"b\". He calculated $$$c$$$\u00a0\u2014 the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 5 \\cdot 10^5$$$, $$$1 \\leq k \\leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)\u00a0\u2014 the string consisting of letters \"a\" and \"b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)\u00a0\u2014 the string consisting of letters \"a\" and \"b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.", "output_spec": "Print one number\u00a0\u2014 maximal value of $$$c$$$.", "sample_inputs": ["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"], "sample_outputs": ["6", "8", "8"], "notes": "NoteIn the first example, Nut could write strings \"aa\", \"ab\", \"ba\", \"bb\". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as \"a\" and \"b\". Totally, $$$6$$$ strings.In the second example, Nut could write strings \"aba\", \"baa\", \"bba\".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$."}, "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.util\n val N, K = ni()\n val S, T = ns(N)\n\n def start = {\n var i = 0\n while(i < N && S(i) == T(i)) i += 1\n i\n }\n\n def count = {\n val s = start\n var ans = 0L\n ans += s // \u624b\u524d\u307e\u3067\u4e00\u7dd2\u3060\u3063\u305f\u30ce\u30fc\u30c9\u306e\u500b\u6570\n ans += (N - s) * 2 // a, b\u306b\u5225\u308c\u305f\u5f8c\u306eS, T\u306e\u30d1\u30b9\u4e0a\u306e\u30ce\u30fc\u30c9\u6570\n var k = 2L // \u6700\u521d\u306f\u5de6\u306e\u7aef\u3001\u53f3\u306e\u7aef\u306e\u5206k\u3092\u4f7f\u3046\n val D = new BIT(N + 1, 0)(_ + _)\n def add(depth: Int): Unit = {\n // depth\u306b1\u8ffd\u52a0\n D.add(depth, 1)\n D.add(depth + 1, -1)\n }\n\n s + 1 until N foreach { i =>\n if (S(i) == 'a') add(i)\n if (T(i) == 'b') add(i)\n }\n\n var depth = 0\n while(depth < N && k < K) {\n val cnt = min(D.sum(depth + 1), K - k)\n k += cnt\n ans += cnt.toLong * (N - depth)\n D.add(depth + 1, cnt)\n depth += 1\n }\n ans\n }\n\n if (K == 1 || util.Arrays.equals(S, T)) out.println(N)\n else out.println(count)\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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\n */\n def sum(i: Int): Long = {\n assert(i <= n)\n var x = i\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 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\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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.util\n val N, K = ni()\n val S, T = ns(N)\n\n def start = {\n var i = 0\n while(i < N && S(i) == T(i)) i += 1\n i\n }\n\n def count = {\n val s = start\n var ans = 0L\n ans += s // \u624b\u524d\u307e\u3067\u4e00\u7dd2\u3060\u3063\u305f\u30ce\u30fc\u30c9\u306e\u500b\u6570\n ans += (N - s) * 2 // a, b\u306b\u5225\u308c\u305f\u5f8c\u306eS, T\u306e\u30d1\u30b9\u4e0a\u306e\u30ce\u30fc\u30c9\u6570\n var k = 2 // \u6700\u521d\u306f\u5de6\u306e\u7aef\u3001\u53f3\u306e\u7aef\u306e\u5206k\u3092\u4f7f\u3046\n val D = Array.ofDim[Int](N + 1)\n\n s + 1 until N foreach { i =>\n if (S(i) == 'a') D(i) += 1\n if (T(i) == 'b') D(i) += 1\n }\n\n var depth = 0\n while(depth < N && k < K) {\n val cnt = min(D(depth), K - k)\n k += cnt\n ans += cnt.toLong * (N - depth)\n D(depth + 1) += cnt * 2\n depth += 1\n }\n ans\n }\n\n if (K == 1 || util.Arrays.equals(S, T)) out.println(N)\n else out.println(count)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "a88e4a7c476b9af1ff2ca9137214dfd7"} {"nl": {"description": "You are given four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$. Timur and three other people are running a marathon. The value $$$a$$$ is the distance that Timur has run and $$$b$$$, $$$c$$$, $$$d$$$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The description of each test case consists of four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \\leq a, b, c, d \\leq 10^4$$$).", "output_spec": "For each test case, output a single integer\u00a0\u2014 the number of participants in front of Timur.", "sample_inputs": ["4\n\n2 3 4 1\n\n10000 0 1 2\n\n500 600 400 300\n\n0 9999 10000 9998"], "sample_outputs": ["2\n0\n1\n3"], "notes": "NoteFor the first test case, there are $$$2$$$ people in front of Timur, specifically the participants who ran distances of $$$3$$$ and $$$4$$$. The other participant is not in front of Timur because he ran a shorter distance than Timur.For the second test case, no one is in front of Timur, since he ran a distance of $$$10000$$$ while all others ran a distance of $$$0$$$, $$$1$$$, and $$$2$$$ respectively.For the third test case, only the second person is in front of Timur, who ran a total distance of $$$600$$$ while Timur ran a distance of $$$500$$$."}, "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 part = StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n val timur = part(0)\r\n\r\n println(part.drop(1).count(x => x > timur))\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "e829ca4438e9cb30ea1c66eea7d5f7a7"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$m$$$. You have to construct the array $$$a$$$ of length $$$n$$$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $$$m$$$ and the value $$$\\sum\\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ is the maximum possible. Recall that $$$|x|$$$ is the absolute value of $$$x$$$.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $$$a=[1, 3, 2, 5, 5, 0]$$$ then the value above for this array is $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^9$$$) \u2014 the length of the array and its sum correspondingly.", "output_spec": "For each test case, print the answer \u2014 the maximum possible value of $$$\\sum\\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ for the array $$$a$$$ consisting of $$$n$$$ non-negative integers with the sum $$$m$$$.", "sample_inputs": ["5\n1 100\n2 2\n5 5\n2 1000000000\n1000000000 1000000000"], "sample_outputs": ["0\n2\n10\n1000000000\n2000000000"], "notes": "NoteIn the first test case of the example, the only possible array is $$$[100]$$$ and the answer is obviously $$$0$$$.In the second test case of the example, one of the possible arrays is $$$[2, 0]$$$ and the answer is $$$|2-0| = 2$$$.In the third test case of the example, one of the possible arrays is $$$[0, 2, 0, 3, 0]$$$ and the answer is $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka: $$$a$$$ was sorted in non-decreasing order ($$$a_1 \\le a_2 \\le \\dots \\le a_n$$$); $$$n$$$ was even; the following sequence $$$b$$$, consisting of $$$\\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\\frac n 2$$$ integers $$$b_1, b_2, \\dots, b_{\\frac n 2}$$$ ($$$0 \\le b_i \\le 10^{18}$$$) \u2014 sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.", "output_spec": "Print $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^{18}$$$) in a single line. $$$a_1 \\le a_2 \\le \\dots \\le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.", "sample_inputs": ["4\n5 6", "6\n2 1 2"], "sample_outputs": ["2 3 3 3", "0 0 1 1 1 2"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on \u2014 you can go from the (n\u2009-\u20091)-th room to the n-th room. Thus, you can go to room x only from room x\u2009-\u20091.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x\u2009-\u20091, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n\u2009-\u20091 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.", "input_spec": "The first line of the input contains a positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014\u00a0the number of rooms in the house. The second line of the input contains string s of length 2\u00b7n\u2009-\u20092. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters\u00a0\u2014\u00a0the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter \u2014 the type of the key that lies in room number (i\u2009+\u20091)\u2009/\u20092. The even positions in the given string contain uppercase Latin letters \u2014 the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter \u2014 the type of the door that leads from room i\u2009/\u20092 to room i\u2009/\u20092\u2009+\u20091.", "output_spec": "Print the only integer \u2014 the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.", "sample_inputs": ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"], "sample_outputs": ["0", "3", "2"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.", "input_spec": "The single line contains a single integer n (n is even, 2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of Gerald's brothers.", "output_spec": "Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers \u2014 the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order. It is guaranteed that the solution exists at the given limits.", "sample_inputs": ["2"], "sample_outputs": ["1 4\n2 3"], "notes": "NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother."}, "positive_code": [{"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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "You are given two arrays of length $$$n$$$: $$$a_1, a_2, \\dots, a_n$$$ and $$$b_1, b_2, \\dots, b_n$$$.You can perform the following operation any number of times: Choose integer index $$$i$$$ ($$$1 \\le i \\le n$$$); Swap $$$a_i$$$ and $$$b_i$$$. What is the minimum possible sum $$$|a_1 - a_2| + |a_2 - a_3| + \\dots + |a_{n-1} - a_n|$$$ $$$+$$$ $$$|b_1 - b_2| + |b_2 - b_3| + \\dots + |b_{n-1} - b_n|$$$ (in other words, $$$\\sum\\limits_{i=1}^{n - 1}{\\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\\right)}$$$) you can achieve after performing several (possibly, zero) operations?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 4000$$$)\u00a0\u2014 the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$2 \\le n \\le 25$$$)\u00a0\u2014 the length of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 10^9$$$)\u00a0\u2014 the array $$$b$$$.", "output_spec": "For each test case, print one integer\u00a0\u2014 the minimum possible sum $$$\\sum\\limits_{i=1}^{n-1}{\\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\\right)}$$$.", "sample_inputs": ["3\n\n4\n\n3 3 10 10\n\n10 10 3 3\n\n5\n\n1 2 3 4 5\n\n6 7 8 9 10\n\n6\n\n72 101 108 108 111 44\n\n10 87 111 114 108 100"], "sample_outputs": ["0\n8\n218"], "notes": "NoteIn the first test case, we can, for example, swap $$$a_3$$$ with $$$b_3$$$ and $$$a_4$$$ with $$$b_4$$$. We'll get arrays $$$a = [3, 3, 3, 3]$$$ and $$$b = [10, 10, 10, 10]$$$ with sum $$$3 \\cdot |3 - 3| + 3 \\cdot |10 - 10| = 0$$$.In the second test case, arrays already have minimum sum (described above) equal to $$$|1 - 2| + \\dots + |4 - 5| + |6 - 7| + \\dots + |9 - 10|$$$ $$$= 4 + 4 = 8$$$.In the third test case, we can, for example, swap $$$a_5$$$ and $$$b_5$$$."}, "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\r\n def recur(a: Array[Int], b: Array[Int], x: Long, y: Long): Long = {\r\n if (a.isEmpty) 0\r\n else {\r\n val ah = a.head\r\n val bh = b.head\r\n val (low, high) = if (ah < bh) (ah, bh) else (bh, ah)\r\n Math.abs(x - low) + Math.abs(y - high) + recur(a.tail, b.tail, low, high)\r\n }\r\n }\r\n def solve() = {\r\n val n = readLine.toInt\r\n val a = rsi\r\n val b = rsi\r\n\r\n val ah = a.head\r\n val bh = b.head\r\n\r\n val at = a.tail\r\n val bt = b.tail\r\n\r\n if (ah < bh) recur(at, bt, ah, bh)\r\n else recur (at, bt, bh, ah)\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 ) println(solve())\r\n }\r\n}\r\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\r\n def recur(a: Array[Int], b: Array[Int], x: Int, y: Int): Int = {\r\n if (a.isEmpty) 0\r\n else {\r\n val ah = a.head\r\n val bh = b.head\r\n val (low, high) = if (ah < bh) (ah, bh) else (bh, ah)\r\n Math.abs(x - low) + Math.abs(y - high) + recur(a.tail, b.tail, low, high)\r\n }\r\n }\r\n def solve() = {\r\n val n = readLine.toInt\r\n val a = rsi\r\n val b = rsi\r\n\r\n val ah = a.head\r\n val bh = b.head\r\n\r\n val at = a.tail\r\n val bt = b.tail\r\n\r\n if (ah < bh) recur(at, bt, ah, bh)\r\n else recur (at, bt, bh, ah)\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 ) println(solve())\r\n }\r\n}\r\n"}], "src_uid": "94ec011dc830661c226bd860b9d70de5"} {"nl": {"description": "Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.", "input_spec": "The first line of input contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200919, 0\u2009\u2264\u2009m) \u2013 respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n, a\u2009\u2260\u2009b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.", "output_spec": "Output the number of cycles in the given graph.", "sample_inputs": ["4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"], "sample_outputs": ["7"], "notes": "NoteThe example graph is a clique and contains four cycles of length 3 and three cycles of length 4."}, "positive_code": [{"source_code": "//package me.jetblack.tspdp\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject MyDpCycles1 extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n val dp = Array.ofDim[Long](1 << n, n)\n\n\n val ee = Array.ofDim[Boolean](n, n)\n\n (0 until m).map { _ =>\n val a = s.nextInt() - 1\n val b = s.nextInt() - 1\n ee(a)(b) = true\n ee(b)(a) = true\n }\n\n def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0\n\n def first(x: Int): Int = {\n var a = x\n var cnt = 0\n while ((a & 1) == 0) {\n a = a >> 1\n cnt += 1\n }\n cnt\n }\n\n def count(x: Int): Int = {\n var a = x\n var cnt = 0\n while (a > 0) {\n if ((a & 1) == 1) cnt += 1\n a = a >> 1\n }\n cnt\n }\n\n def cnt1(x: Int): Boolean = ((x & (x - 1)) == 0 && (x != 0))\n\n def hasEdge(a: Int, b: Int): Boolean = {\n ee(b)(a) == 1\n }\n\n var acc = 0L\n\n (0 until n) foreach (i => dp(1 << i)(i) = 1)\n\n /*for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {*/\n\n var mask = 1\n var i = 0\n\n while (mask < (1 << n)) {\n while (i < n) {\n val xored = mask ^ (1 << i)\n if (bit(mask, i) && !cnt1(mask) && first(mask) != i) {\n var j = 0\n while (j < n) {\n if (ee(i)(j)) {\n dp(mask)(i) += dp(xored)(j)\n if (bits(mask) >= 3 && ee(first(mask))(i))\n acc += dp(xored)(j)\n }\n j += 1\n }\n }\n i += 1\n }\n i = 0\n mask += 1\n }\n\n\n\n def bits(j: Int): Int = {\n var i = j\n i = i - ((i >> 1) & 0x55555555);\n i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n }\n\n println(acc / 2)\n\n}\n"}], "negative_code": [{"source_code": "//package me.jetblack.tspdp\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject MyDpCycles1 extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n val dp = Array.ofDim[Int](1 << n, n)\n\n\n val ee = Array.ofDim[Boolean](n, n)\n\n //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))\n\n (0 until m).map { _ =>\n val a = s.nextInt() - 1\n val b = s.nextInt() - 1\n ee(a)(b) = true\n ee(b)(a) = true\n }\n\n def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0\n\n def first(x: Int): Int = {\n var a = x\n var cnt = 0\n while ((a & 1) == 0) {\n a = a >> 1\n cnt += 1\n }\n cnt\n }\n\n def count(x: Int): Int = {\n var a = x\n var cnt = 0\n while (a > 0) {\n if ((a & 1) == 1) cnt += 1\n a = a >> 1\n }\n cnt\n }\n\n def cnt1(x: Int): Boolean = ((x & (x - 1)) == 0 && (x != 0))\n\n def hasEdge(a: Int, b: Int): Boolean = {\n ee(b)(a) == 1\n }\n\n var acc = 0L\n\n (0 until n) foreach (i => dp(1 << i)(i) = 1)\n\n for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {\n val xored = mask ^ (1 << i)\n if (bit(mask, i) && !cnt1(mask) && first(mask) != i) {\n var j = 0\n while (j < n) {\n if (ee(i)(j)) {\n dp(mask)(i) += dp(xored)(j)\n if (bits(mask) >= 3 && ee(first(mask))(i))\n acc += dp(xored)(j)\n }\n j += 1\n }\n }\n }\n\n def bits(j: Int): Int = {\n var i = j\n i = i - ((i >> 1) & 0x55555555);\n i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n }\n\n println(acc / 2)\n\n}\n"}, {"source_code": "//package me.jetblack.tspdp\n\nimport java.util.Scanner\n\nobject MyDpCycles extends App {\n\n val n = 4\n val m = 6\n\n val s = new Scanner(System.in)\n\n val dp = Array.ofDim[Long](1 << n, n)\n\n //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))\n\n val edges = (0 until m + 1).map(_ => (s.nextInt(), s.nextInt())).drop(1)\n\n def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0\n\n def first(x: Int): Int = {\n var a = x\n var cnt = 0\n while ((a & 1) == 0) {\n a = a >> 1\n cnt += 1\n }\n cnt\n }\n\n def count(x: Int): Int = {\n var a = x\n var cnt = 0\n while (a > 0) {\n if ((a & 1) == 1) cnt += 1\n a = a >> 1\n }\n cnt\n }\n\n def hasEdge(a: Int, b: Int): Boolean = {\n edges.contains((a + 1, b + 1)) || edges.contains((b + 1, a + 1))\n }\n\n for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {\n val xored = mask ^ (1 << i)\n if (count(mask) == 1 && bit(mask, i)) dp(mask)(i) = 1\n else if (count(mask) > 1 && first(mask) != i && bit(mask, i)) {\n (0 until n).foreach { j =>\n if (hasEdge(i, j)) dp(mask)(i) += dp(xored)(j)\n }\n } else {\n dp(mask)(i) = 0\n }\n }\n\n val res = for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {\n if (hasEdge(first(mask), i) && count(mask) >= 3) dp(mask)(i)\n else 0\n }\n\n val ans = res.sum / 2\n\n println(ans)\n\n}\n"}, {"source_code": "//package me.jetblack.tspdp\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject MyDpCycles1 extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n val dp = Array.ofDim[Int](1 << n, n)\n\n val edges = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer.empty[Int])\n\n val ee = Array.ofDim[Int](n, n)\n\n //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))\n\n (0 until m).map { _ =>\n val a = s.nextInt() - 1\n val b = s.nextInt() - 1\n edges(a) += b\n edges(b) += a\n ee(a)(b) = 1\n ee(b)(a) = 1\n }\n\n def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0\n\n def first(x: Int): Int = {\n var a = x\n var cnt = 0\n while ((a & 1) == 0) {\n a = a >> 1\n cnt += 1\n }\n cnt\n }\n\n def count(x: Int): Int = {\n var a = x\n var cnt = 0\n while (a > 0) {\n if ((a & 1) == 1) cnt += 1\n a = a >> 1\n }\n cnt\n }\n\n def cnt1(x: Int): Boolean = ((x & (x - 1)) == 0 && (x != 0))\n\n def hasEdge(a: Int, b: Int): Boolean = {\n ee(b)(a) == 1\n }\n\n var acc = 0L\n\n for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {\n val xored = mask ^ (1 << i)\n val x = mask\n if (bit(mask, i) && ((x & (x - 1)) == 0 && (x != 0))) dp(mask)(i) = 1\n else if (bit(mask, i) && !cnt1(mask) && first(mask) != i) {\n edges(i).foreach { j =>\n dp(mask)(i) += dp(xored)(j)\n /*if (hasEdge(first(mask), i) && count(mask) >= 3)\n acc += dp(xored)(j)*/\n }\n } else {\n dp(mask)(i) = 0\n }\n }\n\n\n\n println(acc / 2)\n\n}\n"}, {"source_code": "//package me.jetblack.tspdp\n\n//package me.jetblack.tspdp\n\nimport java.util.Scanner\n\nobject MyDpCycles1 extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n val dp = Array.ofDim[Long](1 << n, n)\n\n val edges = Array.ofDim[Int](n, n)\n\n //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))\n\n (0 until m).map { _ =>\n val a = s.nextInt()\n val b = s.nextInt()\n edges(a - 1)(b - 1) = 1\n edges(b - 1)(a - 1) = 1\n }\n\n def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0\n\n def first(x: Int): Int = {\n var a = x\n var cnt = 0\n while ((a & 1) == 0) {\n a = a >> 1\n cnt += 1\n }\n cnt\n }\n\n def count(x: Int): Int = {\n var a = x\n var cnt = 0\n while (a > 0) {\n if ((a & 1) == 1) cnt += 1\n a = a >> 1\n }\n cnt\n }\n\n def hasEdge(a: Int, b: Int): Boolean = {\n false\n }\n\n var acc = 0L\n\n for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {\n val xored = mask ^ (1 << i)\n if (count(mask) == 1 && bit(mask, i)) dp(mask)(i) = 1\n else if (bit(mask, i) && first(mask) != i && count(mask) > 1) {\n (0 until n).foreach { j =>\n if (hasEdge(i, j)) {\n dp(mask)(i) += dp(xored)(j)\n if (hasEdge(first(mask), i) && count(mask) >= 3)\n acc += dp(xored)(j)\n else\n 0\n }\n }\n } else {\n dp(mask)(i) = 0\n }\n }\n\n println(acc / 2)\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject MyDpCycles extends App {\n\n val n = 4\n val m = 6\n\n val s = new Scanner(System.in)\n\n val dp = Array.ofDim[Int](1 << n, n)\n\n //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))\n\n val edges = (0 until m + 1).map(_ => (s.nextInt(), s.nextInt())).drop(1)\n\n def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0\n\n def first(x: Int): Int = {\n var a = x\n var cnt = 0\n while ((a & 1) == 0) {\n a = a >> 1\n cnt += 1\n }\n cnt\n }\n\n def count(x: Int): Int = {\n var a = x\n var cnt = 0\n while (a > 0) {\n if ((a & 1) == 1) cnt += 1\n a = a >> 1\n }\n cnt\n }\n\n def hasEdge(a: Int, b: Int): Boolean = {\n edges.contains((a + 1, b + 1)) || edges.contains((b + 1, a + 1))\n }\n\n for {\n mask <- (1 until (1 << n))\n i <- 0 until n\n } yield {\n val xored = mask ^ (1 << i)\n if (count(mask) == 1 && bit(mask, i)) dp(mask)(i) = 1\n else if (count(mask) > 1 && first(mask) != i && bit(mask, i)) {\n (0 until n).foreach { j =>\n if (hasEdge(i, j)) dp(mask)(i) += dp(xored)(j)\n }\n } else {\n dp(mask)(i) = 0\n }\n }\n\n val res = for {\n mask <- (1 until (1 << n) - 1)\n i <- 0 until n\n } yield {\n if (hasEdge(first(mask), i) && count(mask) >= 2) dp(mask)(i)\n else 0\n }\n\n val ans = res.sum / 2\n\n println(ans)\n\n}\n"}], "src_uid": "ce5cc8512359701696dba1b254c6afda"} {"nl": {"description": "Drazil created a following problem about putting 1\u2009\u00d7\u20092 tiles into an n\u2009\u00d7\u2009m grid:\"There is a grid with some cells that are empty and some cells that are occupied. You should use 1\u2009\u00d7\u20092 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it.\"But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: \"how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' \".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.", "output_spec": "If there is no solution or the solution is not unique, you should print the string \"Not unique\". Otherwise you should print how to cover all empty cells with 1\u2009\u00d7\u20092 tiles. Use characters \"<>\" to denote horizontal tiles and characters \"^v\" to denote vertical tiles. Refer to the sample test for the output format example.", "sample_inputs": ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"], "sample_outputs": ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"], "notes": "NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is \"Not unique\"."}, "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 = 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"}, {"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"} {"nl": {"description": "You are given a sequence $$$a_1, a_2, \\dots, a_n$$$ consisting of $$$n$$$ non-zero integers (i.e. $$$a_i \\ne 0$$$). You have to calculate two following values: the number of pairs of indices $$$(l, r)$$$ $$$(l \\le r)$$$ such that $$$a_l \\cdot a_{l + 1} \\dots a_{r - 1} \\cdot a_r$$$ is negative; the number of pairs of indices $$$(l, r)$$$ $$$(l \\le r)$$$ such that $$$a_l \\cdot a_{l + 1} \\dots a_{r - 1} \\cdot a_r$$$ is positive; ", "input_spec": "The first line contains one integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^{5})$$$ \u2014 the number of elements in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(-10^{9} \\le a_i \\le 10^{9}; a_i \\neq 0)$$$ \u2014 the elements of the sequence.", "output_spec": "Print two integers \u2014 the number of subsegments with negative product and the number of subsegments with positive product, respectively.", "sample_inputs": ["5\n5 -3 3 -1 1", "10\n4 2 -4 3 1 2 -4 3 2 3", "5\n-1 -2 -3 -4 -5"], "sample_outputs": ["8 7", "28 27", "9 6"], "notes": null}, "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.collection.mutable\n\nobject Main extends App {\n import scala.io.StdIn._\n val n = readInt()\n val numbers = readLine.trim.split(' ').map(_.toInt)\n var positive = 0L\n var negative = 0L\n var prevNegative = -1\n var oddNegSection = 0\n var evenNegSection = 0\n for (i \u2190 numbers) {\n if (i > 0){\n evenNegSection += 1\n }else {\n val temp = evenNegSection + 1\n evenNegSection = oddNegSection\n oddNegSection = temp\n }\n positive += evenNegSection\n negative += oddNegSection\n }\n println(s\"$negative $positive\")\n}"}], "negative_code": [], "src_uid": "78d3acc3ade53f488739a59100bfcebd"} {"nl": {"description": "Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page \u2014 to the first or to the fifth; from the sixth page \u2014 to the third or to the ninth; from the eighth \u2014 to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\\le n, d \\le 10^9$$$, $$$1 \\le x, y \\le n$$$) \u2014 the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.", "output_spec": "Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.", "sample_inputs": ["3\n10 4 5 2\n5 1 3 4\n20 4 19 3"], "sample_outputs": ["4\n-1\n5"], "notes": "NoteIn the first test case the optimal sequence is: $$$4 \\rightarrow 2 \\rightarrow 1 \\rightarrow 3 \\rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \\rightarrow 7 \\rightarrow 10 \\rightarrow 13 \\rightarrow 16 \\rightarrow 19$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "\"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come.\" \u2014 The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?", "input_spec": "First line consists of a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of stewards with Jon Snow. Second line consists of n space separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) representing the values assigned to the stewards.", "output_spec": "Output a single integer representing the number of stewards which Jon will feed.", "sample_inputs": ["2\n1 5", "3\n1 2 5"], "sample_outputs": ["0", "1"], "notes": "NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2."}, "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _768A extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val stewards = read[Vector[Int]].sorted\n val minLeft = stewards.scanLeft(Int.MaxValue)(_ min _)\n val maxRight = stewards.scanRight(Int.MinValue)(_ max _)\n\n val ans = stewards.indices count {i =>\n minLeft(i) < stewards(i) && stewards(i) < maxRight(i)\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 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": "acaa8935e6139ad1609d62bb5d35128a"} {"nl": {"description": "Slava plays his favorite game \"Peace Lightning\". Now he is flying a bomber on a very specific map.Formally, map is a checkered field of size 1\u2009\u00d7\u2009n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n\u2009-\u20091, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.Help Slava to destroy all tanks using as few bombs as possible.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the size of the map.", "output_spec": "In the first line print m \u2014 the minimum number of bombs Slava needs to destroy all tanks. In the second line print m integers k1,\u2009k2,\u2009...,\u2009km. The number ki means that the i-th bomb should be dropped at the cell ki. If there are multiple answers, you can print any of them.", "sample_inputs": ["2", "3"], "sample_outputs": ["3\n2 1 2", "4\n2 1 3 2"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Inna and Dima bought a table of size n\u2009\u00d7\u2009m in the shop. Each cell of the table contains a single letter: \"D\", \"I\", \"M\", \"A\".Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: initially, Inna chooses some cell of the table where letter \"D\" is written; then Inna can move to some side-adjacent table cell that contains letter \"I\"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter \"M\"; then she can go to a side-adjacent cell that contains letter \"A\". Then Inna assumes that she has gone through her sweetheart's name; Inna's next move can be going to one of the side-adjacent table cells that contains letter \"D\" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter \"D\" she always goes to the letter \"I\", from the letter \"I\" she always goes the to letter \"M\", from the letter \"M\" she always goes to the letter \"A\", and from the letter \"A\" she always goes to the letter \"D\". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103). Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: \"D\", \"I\", \"M\", \"A\". Note that it is not guaranteed that the table contains at least one letter \"D\".", "output_spec": "If Inna cannot go through name DIMA once, print on a single line \"Poor Dima!\" without the quotes. If there is the infinite number of names DIMA Inna can go through, print \"Poor Inna!\" without the quotes. Otherwise print a single integer \u2014 the maximum number of times Inna can go through name DIMA.", "sample_inputs": ["1 2\nDI", "2 2\nMA\nID", "5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID"], "sample_outputs": ["Poor Dima!", "Poor Inna!", "4"], "notes": "NoteNotes to the samples:In the first test sample, Inna cannot go through name DIMA a single time.In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times. "}, "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 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[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\"\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}"}, {"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}"}], "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"} {"nl": {"description": "You are given an integer $$$n$$$ ($$$n \\ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \\cdot b^{k-1} + a_2 \\cdot b^{k-2} + \\ldots a_{k-1} \\cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\\cdot17^2+15\\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.", "input_spec": "The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\\le b\\le 100$$$, $$$1\\le k\\le 10^5$$$)\u00a0\u2014 the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \\ldots, a_k$$$ ($$$0\\le a_i < b$$$)\u00a0\u2014 the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.", "output_spec": "Print \"even\" if $$$n$$$ is even, otherwise print \"odd\". You can print each letter in any case (upper or lower).", "sample_inputs": ["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"], "sample_outputs": ["even", "odd", "odd", "even"], "notes": "NoteIn the first example, $$$n = 3 \\cdot 13^2 + 2 \\cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \\cdot 99^4 + 92 \\cdot 99^3 + 85 \\cdot 99^2 + 74 \\cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$."}, "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 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"}, {"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"} {"nl": {"description": "Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1,\u2009y1) and has radius R and Fafa's laptop is located at (x2,\u2009y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.", "input_spec": "The single line of the input contains 5 space-separated integers R,\u2009x1,\u2009y1,\u2009x2,\u2009y2 (1\u2009\u2264\u2009R\u2009\u2264\u2009105, |x1|,\u2009|y1|,\u2009|x2|,\u2009|y2|\u2009\u2264\u2009105).", "output_spec": "Print three space-separated numbers xap,\u2009yap,\u2009r where (xap,\u2009yap) is the position which Fifa chose for the access point and r is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10\u2009-\u20096 absolutely or relatively, and also the radius you printed can be changed by no more than 10\u2009-\u20096 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.", "sample_inputs": ["5 3 3 1 1", "10 5 5 5 15"], "sample_outputs": ["3.7677669529663684 3.7677669529663684 3.914213562373095", "5.0 5.0 10.0"], "notes": null}, "positive_code": [{"source_code": "object _935C 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 import java.awt.geom.Point2D.{Double => Point}\n val r, x1, y1, x2, y2 = io.read[Double]\n val p1 = new Point(x1, y1)\n val p2 = new Point(x2, y2)\n val d = p1.distance(p2)\n\n val ans = if (d > r) {\n Seq(x1, y1, r)\n } else if (d <= eps) {\n Seq(x1, y1 + r/2, r/2)\n } else {\n val r2 = (d + r)/2\n val t = r2/d\n val (x3, y3) = ((1 - t)*x2 + t*x1, (1 - t)*y2 + t*y1)\n Seq(x3, y3, r2)\n }\n io.writeAll(ans)\n }\n\n def circle(x: Double, y: Double, r: Double) = new java.awt.geom.Ellipse2D.Double(x, y, r, r)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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": [{"source_code": "object _935C 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 import java.awt.geom.Point2D.{Double => Point}\n val r, x1, y1, x2, y2 = io.read[Double]\n val p1 = new Point(x1, y1)\n val p2 = new Point(x2, y2)\n val d = p1.distance(p2)\n\n val ans = if (d > r) {\n Seq(x1, y1, r)\n } else if (d <= eps) {\n val room = circle(x1, y1, r/2)\n val bound = room.getBounds2D\n Seq(bound.getHeight, bound.getWidth, r/2)\n } else {\n val r2 = (d + r)/2\n val t = r2/d\n val (x3, y3) = ((1 - t)*x2 + t*x1, (1 - t)*y2 + t*y1)\n Seq(x3, y3, r2)\n }\n io.writeAll(ans)\n }\n\n def circle(x: Double, y: Double, r: Double) = new java.awt.geom.Ellipse2D.Double(x, y, r, r)\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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"}], "src_uid": "29d4ca13888c0e172dde315b66380fe5"} {"nl": {"description": "This is an interactive problem. In the interaction section below you will see the information about flushing the output.In this problem, you will be playing a game with Hongcow. How lucky of you!Hongcow has a hidden n by n matrix M. Let Mi,\u2009j denote the entry i-th row and j-th column of the matrix. The rows and columns are labeled from 1 to n.The matrix entries are between 0 and 109. In addition, Mi,\u2009i\u2009=\u20090 for all valid i. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each i, you must find .To do this, you can ask Hongcow some questions.A question consists of giving Hongcow a subset of distinct indices {w1,\u2009w2,\u2009...,\u2009wk}, with 1\u2009\u2264\u2009k\u2009\u2264\u2009n. Hongcow will respond with n integers. The i-th integer will contain the minimum value of min1\u2009\u2264\u2009j\u2009\u2264\u2009kMi,\u2009wj.You may only ask Hongcow at most 20 questions\u00a0\u2014 he thinks you only need that many questions answered.When you are ready to answer, print out a single integer \u2009-\u20091 on its own line, then n integers on the next line. The i-th integer should be the minimum value in the i-th row of the matrix, excluding the i-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.You will get Wrong Answer verdict if Your question or answers are not in the format described in this statement. You ask strictly more than 20 questions. Your question contains duplicate indices. The value of k in your question does not lie in the range from 1 to n, inclusive. Your final answer is not correct. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).", "input_spec": "The first line of input will contain a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091,\u2009000).", "output_spec": "To print the final answer, print out the string -1 on its own line. Then, the next line should contain n integers. The i-th integer should be the minimum value of the i-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer!", "sample_inputs": ["3\n0 0 0\n2 7 0\n0 0 4\n3 0 8\n0 5 4", "2\n0 0\n0 0"], "sample_outputs": ["3\n1 2 3\n1\n3\n2\n1 2\n1\n2\n1\n1\n-1\n2 5 4", "1\n2\n1\n1\n-1\n0 0"], "notes": "NoteIn the first sample, Hongcow has the hidden matrix [ [0, 3, 2], [5, 0, 7], [4, 8 ,0],]Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant. 3 3 1 2 30 0 0 1 32 7 0 2 1 20 0 4 1 23 0 8 1 10 5 4 -1 2 5 4For the second sample, it is possible for off-diagonal elements of the matrix to be zero."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject B 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 Some(k) = (1 to 10).find { x => (1 << x) >= n }\n\n var mins = Array.fill(n + 1)(INF)\n\n def request(mask: Int) = {\n val (a, b) = (1 to n).partition(x => (x & mask) != 0)\n println(a.size)\n println(a.mkString(\" \"))\n Console.flush()\n read()\n (1 to n).foreach { j =>\n val x = int()\n if ((j & mask) == 0)\n if (x < mins(j))\n mins(j) = x\n }\n\n println(b.size)\n println(b.mkString(\" \"))\n Console.flush()\n read()\n (1 to n).foreach { j =>\n val x = int()\n if ((j & mask) != 0)\n if (x < mins(j))\n mins(j) = x\n }\n }\n\n (0 until k).map(1 << _).foreach(request)\n\n val ans = mins.drop(1).mkString(\" \")\n println(-1)\n println(ans)\n Console.flush()\n\n}\n"}], "negative_code": [], "src_uid": "0f43df0d2560e55af524e2657f0b2af0"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \\cdot a_j = i + j$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^5$$$)\u00a0\u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 2 \\cdot n$$$)\u00a0\u2014 the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \\cdot a_j = i + j$$$.", "sample_inputs": ["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"], "sample_outputs": ["1\n1\n3"], "notes": "NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \\cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$."}, "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 = 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \\leq x,y,z \\leq n$$$), $$$a_{x}+a_{y} \\neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases. Description of the test cases follows. The only line of each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.", "output_spec": "For each test case, print a complete array on a single line. All elements have to be integers between $$$1$$$ and $$$1000$$$ and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \\leq x,y,z \\leq n$$$) (not necessarily distinct), $$$a_{x}+a_{y} \\neq a_{z}$$$ must hold. If multiple solutions exist, you may print any.", "sample_inputs": ["2\n5\n4"], "sample_outputs": ["1 5 3 77 12\n384 384 44 44"], "notes": "NoteIt can be shown that the outputs above are valid for each test case. For example, $$$44+44 \\neq 384$$$.Below are some examples of arrays that are NOT complete for the 1st test case:$$$[1,2,3,4,5]$$$ Notice that $$$a_{1}+a_{2} = a_{3}$$$.$$$[1,3000,1,300,1]$$$ Notice that $$$a_{2} = 3000 > 1000$$$."}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "The Little Elephant has got a problem \u2014 somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, \u2014 array a. Note that the elements of the array are not necessarily distinct numbers.", "output_spec": "In a single line print \"YES\" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["2\n1 2", "3\n3 2 1", "4\n4 3 2 1"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is \"YES\".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is \"YES\".In the third sample we can't sort the array in more than one swap operation, so the answer is \"NO\"."}, "positive_code": [{"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"}, {"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": "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"}], "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"} {"nl": {"description": "Pig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x;\u2009y], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of teleports and the location of the friend's house. The next n lines contain information about teleports. The i-th of these lines contains two integers ai and bi (0\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009m), where ai is the location of the i-th teleport, and bi is its limit. It is guaranteed that ai\u2009\u2265\u2009ai\u2009-\u20091 for every i (2\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "Print \"YES\" if there is a path from Pig's house to his friend's house that uses only teleports, and \"NO\" otherwise. You can print each letter in arbitrary case (upper or lower).", "sample_inputs": ["3 5\n0 2\n2 4\n3 5", "3 7\n0 4\n2 5\n6 7"], "sample_outputs": ["YES", "NO"], "notes": "NoteThe first example is shown on the picture below: Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.The second example is shown on the picture below: You can see that there is no path from Pig's house to his friend's house that uses only teleports."}, "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 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"}, {"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"} {"nl": {"description": "In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.", "input_spec": "The first line of the input contains the only integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \\le p_i \\le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.", "output_spec": "For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.", "sample_inputs": ["3\n2 3 2", "3\n1 2 3"], "sample_outputs": ["2 2 3", "1 2 3"], "notes": "NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge."}, "positive_code": [{"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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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"}], "negative_code": [], "src_uid": "c0abbbf1cf6c8ec11e942cdaaf01ad7c"} {"nl": {"description": "This is an interactive problem.Ayush devised a new scheme to set the password of his lock. The lock has $$$k$$$ slots where each slot can hold integers from $$$1$$$ to $$$n$$$. The password $$$P$$$ is a sequence of $$$k$$$ integers each in the range $$$[1, n]$$$, $$$i$$$-th element of which goes into the $$$i$$$-th slot of the lock.To set the password of his lock, Ayush comes up with an array $$$A$$$ of $$$n$$$ integers each in the range $$$[1, n]$$$ (not necessarily distinct). He then picks $$$k$$$ non-empty mutually disjoint subsets of indices $$$S_1, S_2, ..., S_k$$$ $$$(S_i \\underset{i \\neq j} \\cap S_j = \\emptyset)$$$ and sets his password as $$$P_i = \\max\\limits_{j \\notin S_i} A[j]$$$. In other words, the $$$i$$$-th integer in the password is equal to the maximum over all elements of $$$A$$$ whose indices do not belong to $$$S_i$$$.You are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. You can ask no more than 12 queries.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \\leq n \\leq 1000, 1 \\leq k \\leq n)$$$\u00a0\u2014 the size of the array and the number of subsets. $$$k$$$ lines follow. The $$$i$$$-th line contains an integer $$$c$$$ $$$(1 \\leq c \\lt n)$$$\u00a0\u2014 the size of subset $$$S_i$$$, followed by $$$c$$$ distinct integers in the range $$$[1, n]$$$ \u00a0\u2014 indices from the subset $$$S_i$$$. It is guaranteed that the intersection of any two subsets is empty.", "output_spec": null, "sample_inputs": ["1\n4 2\n2 1 3\n2 2 4\n\n1\n\n2\n\n3\n\n4\n\nCorrect"], "sample_outputs": ["? 1 1\n\n? 1 2\n\n? 1 3\n\n? 1 4\n\n! 4 3"], "notes": "NoteThe array $$$A$$$ in the example is $$$[1, 2, 3, 4]$$$. The length of the password is $$$2$$$. The first element of the password is the maximum of $$$A[2]$$$, $$$A[4]$$$ (since the first subset contains indices $$$1$$$ and $$$3$$$, we take maximum over remaining indices). The second element of the password is the maximum of $$$A[1]$$$, $$$A[3]$$$ (since the second subset contains indices $$$2$$$, $$$4$$$).Do not forget to read the string \"Correct\" / \"Incorrect\" after guessing the password."}, "positive_code": [{"source_code": "//package codeforces.contests._1363\n\nobject GuessTheMaximums {\n\n def ask(seq: Traversable[Int]): Int = {\n val c = seq.size\n\n println(s\"? $c ${seq.mkString(\" \")}\")\n System.out.flush()\n\n io.StdIn.readInt()\n }\n\n def findIndexOfMaximumElement(n: Int): (Int, Int) = {\n val maxValue = ask(1 to n)\n\n @scala.annotation.tailrec\n def binarySearch(start: Int, end: Int): Int = {\n if (start == end) start\n else {\n val mid = (start + end) / 2\n\n val key = ask(start to mid)\n\n if (key == maxValue) binarySearch(start, mid) else binarySearch(mid + 1, end)\n }\n }\n\n (binarySearch(1, n), maxValue)\n }\n\n def solve: Boolean = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val subsets = {\n val arr = new Array[Set[Int]](k)\n for (i <- 0 until k) {\n val indices = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(i) = indices.view.tail.toSet\n }\n arr\n }\n\n val (idx, max) = findIndexOfMaximumElement(n)\n\n println {\n s\"! ${subsets.map(set => if (set(idx)) ask((1 to n).toSet -- set) else max).mkString(\" \")}\"\n }\n\n io.StdIn.readLine == \"Correct\"\n }\n\n def main(args: Array[String]): Unit = {\n val t = io.StdIn.readInt()\n (1 to t).takeWhile(_ => solve)\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1363\n\nobject GuessTheMaximums {\n\n def ask(seq: Traversable[Int]): Int = {\n val c = seq.size\n\n println(s\"? $c ${seq.mkString(\" \")}\")\n System.out.flush()\n\n io.StdIn.readInt()\n }\n\n def findIndexOfMaximumElement(n: Int): (Int, Int) = {\n val maxValue = ask(1 to n)\n\n @scala.annotation.tailrec\n def binarySearch(start: Int, end: Int): Int = {\n if (start == end) start\n else {\n val mid = (start + end) / 2\n\n val key = ask(start to mid)\n\n if (key == maxValue) binarySearch(start, mid) else binarySearch(mid + 1, end)\n }\n }\n\n (binarySearch(1, n), maxValue)\n }\n\n def solve: Boolean = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val subsets = {\n val arr = new Array[Set[Int]](k)\n for (i <- 0 until k) {\n val indices = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(i) = indices.view.tail.toSet\n }\n arr\n }\n\n val (idx, max) = findIndexOfMaximumElement(n)\n\n println {\n s\"! ${subsets.map(set => if (set(idx)) ask((1 to n).toSet -- set) else max).mkString(\" \")}\"\n }\n\n io.StdIn.readLine == \"CORRECT\"\n }\n\n def main(args: Array[String]): Unit = {\n val t = io.StdIn.readInt()\n (1 to t).takeWhile(_ => solve)\n }\n}\n"}], "src_uid": "b0bce8524eb69b695edc1394ff86b913"} {"nl": {"description": "Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!", "input_spec": "The first line contains an odd positive integer n\u00a0\u2014 the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.", "output_spec": "If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print \u2009-\u20091. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.", "sample_inputs": ["527", "4573", "1357997531"], "sample_outputs": ["572", "3574", "-1"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$, both of length $$$n$$$. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions: choose an occurrence of \"ab\" in $$$s$$$ and replace it with \"ba\"; choose an occurrence of \"bc\" in $$$s$$$ and replace it with \"cb\". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $$$s$$$ to make it equal to string $$$t$$$?", "input_spec": "The first line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of strings $$$s$$$ and $$$t$$$. The second line contains string $$$s$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The third line contains string $$$t$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^5$$$.", "output_spec": "For each testcase, print \"YES\" if you can change string $$$s$$$ to make it equal to string $$$t$$$ by performing an arbitrary amount of moves (possibly, zero). Otherwise, print \"NO\".", "sample_inputs": ["5\n\n3\n\ncab\n\ncab\n\n1\n\na\n\nb\n\n6\n\nabbabc\n\nbbaacb\n\n10\n\nbcaabababc\n\ncbbababaac\n\n2\n\nba\n\nab"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": null}, "positive_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n def reread(s: String): String = {\r\n val s1 = for (l <- s if l != \"b\"(0)) yield {\r\n l\r\n }\r\n s1\r\n }\r\n\r\n for (i <- 1 to n) {\r\n val k = readInt()\r\n val s = readLine()\r\n val t = readLine()\r\n var a = 0\r\n var c = 0\r\n var ac = 1\r\n for (j <- 0 until k) {\r\n if (s(j) == \"a\"(0)) {\r\n a = a + 1\r\n }\r\n if (t(j) == \"a\"(0)) {\r\n a = a - 1\r\n }\r\n if (s(j) == \"c\"(0)) {\r\n c = c - 1\r\n }\r\n if (t(j) == \"c\"(0)) {\r\n c = c + 1\r\n }\r\n if ((a < 0) || (c < 0) || (a * c != 0) || (j == k - 1 && a * a + c * c != 0) )\r\n ac = 0\r\n }\r\n if (reread(s) != reread(t)) {\r\n ac = 0\r\n }\r\n\r\n if (ac == 0) println(\"NO\")\r\n else println(\"YES\")\r\n }\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n def reread(s: String): String = {\r\n val s1 = for (l <- s if l != \"b\"(0)) yield {\r\n l\r\n }\r\n s1\r\n }\r\n\r\n for (i <- 1 to n) {\r\n val k = readInt()\r\n val s = readLine()\r\n val t = readLine()\r\n var a = 0\r\n var c = 0\r\n var ac = 1\r\n for (j <- 0 to k - 1) {\r\n if (s(j) == \"a\"(0)) {\r\n a = a + 1\r\n }\r\n if (t(j) == \"a\"(0)) {\r\n a = a - 1\r\n }\r\n if (s(j) == \"c\"(0)) {\r\n c = c - 1\r\n }\r\n if (t(j) == \"c\"(0)) {\r\n c = c + 1\r\n }\r\n if ((a < 0) || (a > 1) || (c < 0) || (c > 1) || (a * c != 0) || (j == k - 1 && a * a + c * c != 0) )\r\n ac = 0\r\n }\r\n if (reread(s) != reread(t)) {\r\n ac = 0\r\n }\r\n\r\n if (ac == 0) println(\"NO\")\r\n else println(\"YES\")\r\n }\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n val n = readInt()\r\n for (i <- 1 to n) {\r\n val k = readInt()\r\n val s= readLine()\r\n val t = readLine()\r\n var a = 0\r\n var c = 0\r\n var ac = 1\r\n for (j <- 0 to k-1) {\r\n if (s(j) == \"a\"(0)) {\r\n a = a + 1\r\n }\r\n if (t(j) == \"a\"(0)) {\r\n a = a - 1\r\n }\r\n if (s(j) == \"c\"(0)) {\r\n c = c - 1\r\n }\r\n if (t(j) == \"c\"(0)) {\r\n c = c + 1\r\n }\r\n if ((a < 0) || (a > 1) || (c < 0) || (c > 1) || (a*c != 0) || (j == k-1 && a*a + c*c !=0))\r\n ac = 0\r\n }\r\n if (ac == 0)\r\n println(\"NO\")\r\n\r\n else println(\"YES\")\r\n }\r\n}\r\n"}], "src_uid": "235ddb32dbe19c0da1f77069e36128bb"} {"nl": {"description": "Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.", "input_spec": "The first line of input contains three space separated integers d, n, and m (1\u2009\u2264\u2009n\u2009\u2264\u2009d\u2009\u2264\u2009109, 1\u2009\u2264\u2009m\u2009\u2264\u2009200 000)\u00a0\u2014 the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively. Each of the next m lines contains two integers xi, pi (1\u2009\u2264\u2009xi\u2009\u2264\u2009d\u2009-\u20091, 1\u2009\u2264\u2009pi\u2009\u2264\u2009106)\u00a0\u2014 the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.", "output_spec": "Print a single integer\u00a0\u2014 the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.", "sample_inputs": ["10 4 4\n3 5\n5 8\n6 3\n8 4", "16 5 2\n8 2\n5 1"], "sample_outputs": ["22", "-1"], "notes": "NoteIn the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2\u00b75\u2009+\u20094\u00b73\u2009=\u200922 dollars.In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center."}, "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 def readLongs(n: Int) = { val tl = tokenizeLine; 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"}, {"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"} {"nl": {"description": "The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1,\u2009a2,\u2009...,\u2009an (16\u2009\u2264\u2009ai\u2009\u2264\u200932768); number ai denotes the maximum data transfer speed on the i-th computer.", "output_spec": "Print a single integer \u2014 the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.", "sample_inputs": ["3 2\n40 20 30", "6 4\n100 20 40 20 50 50"], "sample_outputs": ["30", "40"], "notes": "NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "6eca08d7cc2dec6f4f84d3faa9a8a915"} {"nl": {"description": "You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.", "input_spec": "The first line contains the integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \\le u,v \\le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.", "output_spec": "Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).", "sample_inputs": ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"], "sample_outputs": ["0\n1", "0\n3\n2\n4\n1"], "notes": "NoteThe tree from the second sample:"}, "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"}, {"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}"}], "negative_code": [], "src_uid": "5ef966b7d9fbf27e6197b074eca31b15"} {"nl": {"description": "Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $$$n$$$ players arranged in a circle, so that for all $$$j$$$ such that $$$2 \\leq j \\leq n$$$, player $$$j - 1$$$ is to the left of the player $$$j$$$, and player $$$j$$$ is to the right of player $$$j - 1$$$. Additionally, player $$$n$$$ is to the left of player $$$1$$$, and player $$$1$$$ is to the right of player $$$n$$$.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $$$0$$$, $$$1$$$, or $$$2$$$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $$$1$$$ other player, then they should logically attack that player in response. If instead a player is being attacked by $$$0$$$ or $$$2$$$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $$$n$$$ players in the game to make them instead attack another player \u00a0\u2014 i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). The descriptions of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$3 \\leq n \\leq 2 \\cdot 10^5$$$) \u00a0\u2014 the amount of players (and therefore beds) in this game of Bed Wars. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. The $$$j$$$-th character of $$$s$$$ is equal to L if the $$$j$$$-th player is attacking the player to their left, and R if the $$$j$$$-th player is attacking the player to their right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy. It can be proven that it is always possible for Omkar to achieve this under the given constraints.", "sample_inputs": ["5\n4\nRLRL\n6\nLRRRRL\n8\nRLLRRRLL\n12\nLLLLRRLRRRLL\n5\nRRRRR"], "sample_outputs": ["0\n1\n1\n3\n2"], "notes": "NoteIn the first test case, players $$$1$$$ and $$$2$$$ are attacking each other, and players $$$3$$$ and $$$4$$$ are attacking each other. Each player is being attacked by exactly $$$1$$$ other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer $$$0$$$.In the second test case, not every player acts logically: for example, player $$$3$$$ is attacked only by player $$$2$$$, but doesn't attack him in response. Omkar can talk to player $$$3$$$ to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer $$$1$$$."}, "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 var s = nextLine\n var res = 0\n\n if (s.distinct.size == 1) {\n if (n > 2) {\n res = (n + 2) / 3\n }\n } else {\n val sl = s.takeWhile(_ == s.last)\n val sr = s.dropWhile(_ == s.last)\n s = sr + sl\n\n var prev = s(0)\n var cnt = 1\n for (i <- 1 until n) {\n if (s(i) == prev) {\n cnt += 1\n } else {\n res += cnt / 3\n prev = s(i)\n cnt = 1\n }\n }\n res += cnt / 3\n }\n\n out.println(res)\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": [{"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 s = nextLine\n\n var prev = s.last\n var cnt = 1\n var res = 0\n for (i <- 0 until n) {\n if (s(i) == prev) {\n cnt += 1\n } else {\n res += (cnt - 1) / 2\n prev = s(i)\n cnt = 1\n }\n }\n res += (cnt - 1) / 2\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 D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n var s = nextLine\n var res = 0\n\n if (s.distinct.size == 1) {\n if (n > 2) {\n res = n / 2\n }\n } else {\n val sl = s.takeWhile(_ == s.last)\n val sr = s.dropWhile(_ == s.last)\n s = sr + sl\n\n var prev = s(0)\n var cnt = 1\n for (i <- 1 until n) {\n if (s(i) == prev) {\n cnt += 1\n } else {\n res += cnt / 3\n prev = s(i)\n cnt = 1\n }\n }\n res += cnt / 3\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 D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n var s = nextLine\n val sl = s.takeWhile(_ == s.last)\n val sr = s.dropWhile(_ == s.last)\n s = sr + sl\n\n var prev = s.last\n var cnt = 1\n var res = 0\n for (i <- 0 until n) {\n if (s(i) == prev) {\n cnt += 1\n } else {\n res += cnt / 3\n prev = s(i)\n cnt = 1\n }\n }\n res += cnt / 3\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": "b06d5b48525cd386a0141bdf44579a5c"} {"nl": {"description": "Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1,\u2009a2,\u2009...,\u2009an. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105), that denote the number of counters Valera has and the number of pairs of counters connected by wires. Each of the following m lines contains two space-separated integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi), that mean that counters with numbers ui and vi are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input. The last line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009105), where ai is the value that Ignat choose for the i-th counter.", "output_spec": "If Valera can't win the dispute print in the first line -1. Otherwise, print in the first line integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009n). In the second line print k distinct space-separated integers \u2014 the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order. If there exists multiple answers, you are allowed to print any of them.", "sample_inputs": ["5 5\n2 3\n4 1\n1 5\n5 3\n2 1\n1 1 2 0 2", "4 2\n1 2\n3 4\n0 0 0 0"], "sample_outputs": ["2\n1 2", "3\n1 3 4"], "notes": null}, "positive_code": [{"source_code": "object D{\n import scala.collection.mutable.{Queue=>Mqueue}\n\n def main(args: Array[String]){\n\n val (n,m)={\n val sp=readLine.split(\" \")\n (sp(0).toInt,sp(1).toInt)\n }\n\n val g={\n val gg= Array.fill(n)(List[Int]())\n\n for(_<- 1 to m){\n val sp=readLine.split(\" \")\n val (u,v)=(sp(0).toInt-1,sp(1).toInt-1)\n gg(u)::=v\n gg(v)::=u\n }\n gg\n }\n\n val a=readLine.split(\" \").map(_.toInt)\n\n val list={\n var list=List[Int]()\n val now=Array.fill(n)(0)\n val q=new Mqueue[Int]()\n for(i<- 0 until n if(a(i)==0)){\n q.enqueue(i)\n }\n while(q.size>0){\n val idx=q.dequeue\n if(now(idx)==a(idx)){\n list::=idx\n now(idx)+=1\n g(idx).foreach{ii=>\n now(ii)+=1\n if(now(ii)==a(ii)){\n q.enqueue(ii)\n }\n }\n }\n }\n list\n }\n\n println(list.size)\n println(list.map(_+1).mkString(\" \"))\n }\n}\n"}], "negative_code": [], "src_uid": "5c64671081f9f5332d0ad57503091a54"} {"nl": {"description": "You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that: No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$); the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.", "output_spec": "For each query, print the answer on it \u2014 the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)", "sample_inputs": ["4\n4\n2 10 1 20\n2\n3 6\n5\n2 3 4 99 100\n1\n42"], "sample_outputs": ["2\n1\n2\n1"], "notes": "NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students."}, "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": "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"}, {"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"} {"nl": {"description": "A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \\odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \\% 3$$$ (where $$$\\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \\odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \\odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 5 \\cdot 10^4$$$) \u2014 the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \\cdot 10^4$$$ ($$$\\sum n \\le 5 \\cdot 10^4$$$).", "output_spec": "For each test case, print the answer \u2014 two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \\odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any.", "sample_inputs": ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"], "sample_outputs": ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i,\u2009j), such that the distance between them is not less than the sum of their weights, or more formally: |xi\u2009-\u2009xj|\u2009\u2265\u2009wi\u2009+\u2009wj.Find the size of the maximum clique in such graph.", "input_spec": "The first line contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000) \u2014 the number of points. Each of the next n lines contains two numbers xi, wi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009wi\u2009\u2264\u2009109) \u2014 the coordinate and the weight of a point. All xi are different.", "output_spec": "Print a single number \u2014 the number of vertexes in the maximum clique of the given graph.", "sample_inputs": ["4\n2 3\n3 1\n6 1\n0 2"], "sample_outputs": ["3"], "notes": "NoteIf you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!The picture for the sample test. "}, "positive_code": [{"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 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 (value <= array(mid)) {\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 vertex = new Array[Tuple2[Int, Int]](n)\n var dp = new Array[Int](n)\n for (i <- 0 until n) {\n var pos = nextInt\n var weight = nextInt\n vertex(i) = Tuple2(pos + weight, pos - weight)\n }\n util.Sorting.quickSort(vertex)\n for (i <- 0 until n) {\n val pos = upperBound(vertex, Tuple2(vertex(i)._2, Int.MaxValue)) - 1\n if (pos == -1) {\n dp(i) = 1\n } else {\n dp(i) = dp(pos) + 1\n }\n if (i > 0) dp(i) = math.max(dp(i), dp(i - 1))\n }\n println(dp.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"}], "negative_code": [], "src_uid": "c5d15bbebfe57bc7cddb443229fb7d61"} {"nl": {"description": "There is a weighted tree with $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are conveniently labeled from $$$1$$$ to $$$n$$$. The weights are positive integers at most $$$100$$$. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes.Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes $$$p$$$ and $$$q$$$, and the judge will return the maximum distance between a node in $$$p$$$ and a node in $$$q$$$. In the words, maximum distance between $$$x$$$ and $$$y$$$, where $$$x \\in p$$$ and $$$y \\in q$$$. After asking not more than $$$9$$$ questions, you must report the maximum distance between any pair of nodes.", "input_spec": null, "output_spec": null, "sample_inputs": ["2\n5\n9\n6\n10\n9\n10\n2\n99"], "sample_outputs": ["1 4 1 2 3 4 5\n1 4 2 3 4 5 1\n1 4 3 4 5 1 2\n1 4 4 5 1 2 3\n1 4 5 1 2 3 4\n-1 10\n1 1 1 2\n-1 99"], "notes": "NoteIn the first example, the first tree looks as follows: In the first question, we have $$$p = {1}$$$, and $$$q = {2, 3, 4, 5}$$$. The maximum distance between a node in $$$p$$$ and a node in $$$q$$$ is $$$9$$$ (the distance between nodes $$$1$$$ and $$$5$$$).The second tree is a tree with two nodes with an edge with weight $$$99$$$ between them."}, "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(tests) = readInts(1)\n\n for (_ <- 1 to tests) {\n val Array(n) = readInts(1)\n val other = (2 to n).toArray\n println(s\"1 ${other.length} 1 \" + other.mkString(\" \"))\n val max = readLine.toInt\n var (right, left) = other.splitAt((other.size + 1) / 2)\n do {\n println(s\"1 ${right.length} 1 \" + right.mkString(\" \"))\n val dist = readLine.toInt\n val (r, l) = if (dist >= max) {\n right.splitAt((right.size + 1) / 2)\n } else {\n left.splitAt((left.size + 1) / 2)\n }\n right = r\n left = l\n if (dist == -1) System.exit(0)\n } while (left.size > 0)\n\n val r = right.head\n val notR = (1 to n).filterNot(_ == r)\n println(s\"1 ${notR.length} $r \" + notR.mkString(\" \"))\n\n val dist = readLine.toInt\n if (dist == -1) System.exit(0)\n println(s\"-1 $dist\")\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(tests) = readInts(1)\n\n for (_ <- 1 to tests) {\n val Array(n) = readInts(1)\n val other = (2 to n).toArray\n println(s\"1 ${other.length} 1 \" + other.mkString(\" \"))\n val max = readLine.toInt\n var (right, left) = other.splitAt((other.size + 1) / 2)\n do {\n println(s\"1 ${right.length} 1 \" + right.mkString(\" \"))\n val dist = readLine.toInt\n val (r, l) = if (dist >= max) {\n right.splitAt((right.size + 1) / 2)\n } else {\n left.splitAt((left.size + 1) / 2)\n }\n right = r\n left = l\n if (dist == -1) System.exit(0)\n } while (left.size > 0)\n\n val r = right.head\n val notR = (1 to n).filterNot(_ == r)\n println(s\"1 ${notR.length} $r \" + notR.mkString(\" \"))\n\n val dist = readLine.toInt\n if (dist == -1) System.exit(0)\n println(dist)\n }\n}\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(tests) = readInts(1)\n\n for (_ <- 1 to tests) {\n val Array(n) = readInts(1)\n val other = (2 to n).toArray\n println(s\"1 1 ${other.length} \" + other.mkString(\" \"))\n val max = readLine.toInt\n var (right, left) = other.splitAt((other.size + 1) / 2)\n do {\n println(s\"1 1 ${right.length} \" + right.mkString(\" \"))\n val dist = readLine.toInt\n val (r, l) = if (dist >= max) {\n right.splitAt((right.size + 1) / 2)\n } else {\n left.splitAt((left.size + 1) / 2)\n }\n right = r\n left = l\n if (dist == -1) System.exit(0)\n } while (left.size > 0)\n\n val r = right.head\n val notR = (1 to n).filterNot(_ == r)\n println(s\"1 $r ${notR.length} \" + notR.mkString(\" \"))\n\n val dist = readLine.toInt\n if (dist == -1) System.exit(0)\n println(dist)\n }\n}\n"}], "src_uid": "20e2cf707d39c22eaf111f12b2ae6d30"} {"nl": {"description": "There are $$$n$$$ kids, numbered from $$$1$$$ to $$$n$$$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (all these numbers are from $$$1$$$ to $$$n$$$ and are distinct, so $$$p$$$ is a permutation). Let the next kid for a kid $$$p_i$$$ be kid $$$p_{i + 1}$$$ if $$$i < n$$$ and $$$p_1$$$ otherwise. After the dance, each kid remembered two kids: the next kid (let's call him $$$x$$$) and the next kid for $$$x$$$. Each kid told you which kids he/she remembered: the kid $$$i$$$ remembered kids $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$. However, the order of $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ can differ from their order in the circle. Example: 5 kids in a circle, $$$p=[3, 2, 4, 1, 5]$$$ (or any cyclic shift). The information kids remembered is: $$$a_{1,1}=3$$$, $$$a_{1,2}=5$$$; $$$a_{2,1}=1$$$, $$$a_{2,2}=4$$$; $$$a_{3,1}=2$$$, $$$a_{3,2}=4$$$; $$$a_{4,1}=1$$$, $$$a_{4,2}=5$$$; $$$a_{5,1}=2$$$, $$$a_{5,2}=3$$$. You have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of the kids. The next $$$n$$$ lines contain $$$2$$$ integers each. The $$$i$$$-th line contains two integers $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ ($$$1 \\le a_{i, 1}, a_{i, 2} \\le n, a_{i, 1} \\ne a_{i, 2}$$$) \u2014 the kids the $$$i$$$-th kid remembered, given in arbitrary order.", "output_spec": "Print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ \u2014 permutation of integers from $$$1$$$ to $$$n$$$, which corresponds to the order of kids in the circle. If there are several answers, you may print any (for example, it doesn't matter which kid is the first in the circle). It is guaranteed that at least one solution exists.", "sample_inputs": ["5\n3 5\n1 4\n2 4\n1 5\n2 3", "3\n2 3\n3 1\n1 2"], "sample_outputs": ["3 2 4 1 5", "3 1 2"], "notes": null}, "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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 \u30ce\u30fc\u30c9\u6570\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}"}], "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 \u30ce\u30fc\u30c9\u6570\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 \u30ce\u30fc\u30c9\u6570\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"} {"nl": {"description": "She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of $$$n$$$ nodes with $$$m$$$ edges. You also have $$$q$$$ queries. Each query consists of two nodes $$$a$$$ and $$$b$$$.Initially, all edges in the graph have a weight of $$$0$$$. For each query, you must choose a simple path starting from $$$a$$$ and ending at $$$b$$$. Then you add $$$1$$$ to every edge along this path. Determine if it's possible, after processing all $$$q$$$ queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query. If it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed $$$10^{18}$$$ under the given constraints.A simple path is defined as any path that does not visit a node more than once.An edge is said to have an even weight if its value is divisible by $$$2$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$, $$$n-1 \\leq m \\leq \\min{\\left(\\frac{n(n-1)}{2}, 3 \\cdot 10^5\\right)}$$$). Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\leq x, y \\leq n$$$, $$$x\\neq y$$$) indicating an undirected edge between node $$$x$$$ and $$$y$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \\leq q \\leq 3 \\cdot 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\leq a, b \\leq n, a \\neq b$$$), the description of each query. It is guaranteed that $$$nq \\leq 3 \\cdot 10^5$$$.", "output_spec": "If it is possible to force all edge weights to be even, print \"YES\" on the first line, followed by $$$2q$$$ lines indicating the choice of path for each query in the same order the queries are given. For each query, the first line should contain a single integer $$$x$$$: the number of nodes in the chosen path. The next line should then contain $$$x$$$ spaced separated integers $$$p_i$$$ indicating the path you take ($$$p_1 = a, p_x = b$$$ and all numbers should fall between $$$1$$$ and $$$n$$$). This path cannot contain duplicate nodes and must be a valid simple path in the graph. If it is impossible to force all edge weights to be even, print \"NO\" on the first line and the minimum number of added queries on the second line.", "sample_inputs": ["6 7\n2 1\n2 3\n3 5\n1 4\n6 1\n5 6\n4 5\n3\n1 4\n5 1\n4 5", "5 7\n4 3\n4 5\n2 1\n1 4\n1 3\n3 5\n3 2\n4\n4 2\n3 5\n5 1\n4 5"], "sample_outputs": ["YES\n2\n1 4\n4\n5 3 2 1\n5\n4 1 2 3 5", "NO\n2"], "notes": "NoteHere is what the queries look like for the first test case (red corresponds to the 1st query, blue 2nd query, and green 3rd query): Notice that every edge in the graph is part of either $$$0$$$ or $$$2$$$ colored query edges.The graph in the second test case looks like this: There does not exist an assignment of paths that will force all edges to have even weights with the given queries. One must add at least $$$2$$$ new queries to obtain a set of queries that can satisfy the condition."}, "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 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 class pair(var v: Int, var ok: Boolean)\n\n val t = 1//readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n val g = new Array[Vector[pair]](n+1)\n val g2 = new Array[Vector[Int]](n+1)\n val deg = new Array[Int](n+1)\n var query = Vector[(Int, Int)]()\n for (i <- 1 to n) {\n g(i) = Vector[pair]()\n g2(i) = Vector[Int]()\n }\n for (i <- 1 to m) {\n val a = readInt()\n val b = readInt()\n g(a) :+= new pair(b, false)\n g(b) :+= new pair(a, false)\n }\n val mk = new Array[Boolean](n+1)\n def dfs1(v: Int): Unit = {\n mk(v) = true\n for (i <- g(v).indices) {\n val u = g(v)(i).v\n if (!mk(u)) {\n g2(v) :+= u\n g2(u) :+= v\n dfs1(u)\n }\n }\n }\n dfs1(1)\n val q = readInt()\n for (i <- 1 to q) {\n val a = readInt()\n val b = readInt()\n query :+= (a, b)\n deg(a) += 1\n deg(b) += 1\n }\n var ans = 0\n for (i <- 1 to n) {\n ans += deg(i) % 2\n }\n if (ans != 0) {\n writer.println(\"NO\")\n writer.println(ans/2)\n } else {\n writer.print(\"YES\")\n for (i <- 0 until q) {\n dfs(query(i)._2, query(i)._1, 0, 1)\n def dfs(v:Int, end:Int, p: Int, d:Int): Boolean = {\n if (v == end) {\n writer.println()\n writer.println(d)\n writer.print(v + \" \")\n return true\n }\n for (i <- g2(v).indices) {\n val u = g2(v)(i)\n if (u != p) {\n if (dfs(u, end, v, d+1)) {\n writer.print(v + \" \")\n return true\n }\n }\n }\n return false\n }\n }\n }\n }\n writer.flush()\n}\n"}], "negative_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 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 class pair(var v: Int, var ok: Boolean)\n\n val t = 1//readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n val g = new Array[Vector[pair]](n+1)\n val deg = new Array[Int](n+1)\n var query = Vector[(Int, Int)]()\n for (i <- 1 to n) {\n g(i) = Vector[pair]()\n }\n for (i <- 1 to m) {\n val a = readInt()\n val b = readInt()\n g(a) :+= new pair(b, true)\n g(b) :+= new pair(a, true)\n }\n val mk = new Array[Boolean](n+1)\n def dfs1(v: Int): Unit = {\n mk(v) = true\n for (i <- g(v).indices) {\n val u = g(v)(i).v\n if (mk(u)) {\n g(v)(i).ok = false\n } else {\n dfs1(u)\n }\n }\n }\n val q = readInt()\n for (i <- 1 to q) {\n val a = readInt()\n val b = readInt()\n query :+= (a, b)\n deg(a) += 1\n deg(b) += 1\n }\n var ans = 0\n for (i <- 1 to n) {\n ans += deg(i) % 2\n }\n if (ans != 0) {\n writer.println(\"NO\")\n writer.println(ans/2)\n } else {\n writer.print(\"YES\")\n for (i <- 0 until q) {\n val mark = new Array[Boolean](n+1)\n dfs(query(i)._2, query(i)._1, 1)\n\n def dfs(v:Int, end:Int, d:Int): Boolean = {\n mark(v) = true\n if (v == end) {\n writer.println()\n writer.println(d)\n writer.print(v + \" \")\n return true\n }\n for (i <- g(v).indices) {\n val u = g(v)(i).v\n val ok = g(v)(i).ok\n if (ok && !mark(u)) {\n if (dfs(u, end, d+1)) {\n writer.print(v + \" \")\n return true\n }\n }\n }\n return false\n }\n }\n }\n }\n writer.flush()\n}\n"}], "src_uid": "8c06963c45469f638a1c7c4769295be9"} {"nl": {"description": "Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n\u2009\u00d7\u2009n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1\u00b71\u2009+\u20091\u00b70\u2009+\u20091\u00b71)\u2009+\u2009(0\u00b71\u2009+\u20091\u00b71\u2009+\u20091\u00b70)\u2009+\u2009(1\u00b71\u2009+\u20090\u00b71\u2009+\u20090\u00b70)\u2009=\u20090\u2009+\u20091\u2009+\u20091\u2009=\u20090.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1\u2009-\u2009w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?", "input_spec": "The first line of input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0\u2009\u2264\u2009aij\u2009\u2264\u20091) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i \u2014 flip the values of the i-th row; 2 i \u2014 flip the values of the i-th column; 3 \u2014 output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.", "output_spec": "Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.", "sample_inputs": ["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"], "sample_outputs": ["01001"], "notes": null}, "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\n val n = readInt\n val as = Array.ofDim[Int](n, n)\n \n for (i <- 0 until n) as(i) = readInts(n)\n \n var sum = 0\n for (i <- 0 until n; j <- 0 until n) sum += as(i)(j) * as(j)(i)\n \n sum %= 2\n\n val m = readInt\n \n val res = new mutable.ArrayBuffer[Int](m)\n for (i <- 1 to m) {\n val cmd = readLine\n if (cmd.head == '3') res += sum else sum = 1 - sum\n }\n\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 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 n = readInt\n\n println()\n}"}], "src_uid": "332902284154faeaf06d5d05455b7eb6"} {"nl": {"description": "The mobile application store has a new game called \"Subway Roller\".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column. ", "input_spec": "Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u200910 for pretests and tests or t\u2009=\u20091 for hacks; see the Notes section for details) \u2014 the number of sets. Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009k\u2009\u2264\u200926) \u2014 the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.", "output_spec": "For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.", "sample_inputs": ["2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....", "2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY..."], "sample_outputs": ["YES\nNO", "YES\nNO"], "notes": "NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset."}, "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val t = in.next().toInt\n val res = (1 to t).map {j =>\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n\n val str = (1 to 3).map(_ => in.next())\n var y = if (str.head.head == 's') (true, false, false)\n else if (str(1).head == 's') (false, true, false)\n else (false, false, true)\n var x = 0\n var stop = false\n def good(y: Int, x: Int, yStart: Int) = {\n (x >= n - 1) || (str(yStart)(x + 1) == '.' && (x + 1 to Math.min(x + 1 + 2, n - 1)).forall(j => str(y)(j) == '.'))\n }\n\n while (x < n && !stop) {\n y = y match {\n case(a, b, c) =>\n ((if (a) good(0, x, 0) else false) || (if (b) good(0, x, 1) else false),\n (if (a) good(1, x, 0) else false) || (if (b) good(1, x, 1) else false) || (if (c) good(1, x, 2) else false),\n (if (b) good(2, x, 1) else false) || (if (c) good(2, x, 2) else false))\n }\n if (y == (false, false, false))\n stop = true\n x += 3\n }\n if (stop)\n \"NO\"\n else\n \"YES\"\n }\n println(res.mkString(\"\\n\"))\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 val res = (1 to t).map {j =>\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n\n val str = (1 to 3).map(_ => in.next())\n var y = if (str.head.head == 's') (true, false, false)\n else if (str(1).head == 's') (false, true, false)\n else (false, false, true)\n var x = 0\n var stop = false\n def good(y: Int, x: Int, yStart: Int) = {\n (x >= n - 1) || (str(yStart)(x + 1) == '.' && (x + 2 to Math.min(x + 2 + 3, n - 1)).forall(j => str(y)(j) == '.'))\n }\n\n while (x < n && !stop) {\n y = y match {\n case(a, b, c) =>\n ((if (a) good(0, x, 0) else false) || (if (b) good(0, x, 1) else false),\n (if (a) good(1, x, 0) else false) || (if (b) good(1, x, 1) else false) || (if (c) good(1, x, 2) else false),\n (if (b) good(2, x, 1) else false) || (if (c) good(2, x, 2) else false))\n }\n if (y == (false, false, false))\n stop = true\n x += 3\n }\n if (stop)\n \"NO\"\n else\n \"YES\"\n }\n println(res.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// var key = 0\n val res = (1 to t).map {j =>\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n\n val str = (1 to 3).map(_ => in.next())\n var y = if (str.head.head == 's') (true, false, false)\n else if (str(1).head == 's') (false, true, false)\n else (false, false, true)\n// if (key == 1)\n// throw new Exception(str.mkString(\"\\n\"))\n// if (n == 98 && k == 10)\n// key = 1\n var x = 0\n var stop = false\n def good(y: Int, x: Int) = {\n (x + 1 to Math.min(x + 1 + 3, n - 1)).forall(j => str(y)(j) == '.')\n }\n\n while (x < n && !stop) {\n y = y match {\n case(_, true, _) =>\n (good(0, x), good(1, x), good(2, x))\n case(true, false, true) =>\n (good(0, x), good(1, x), good(2, x))\n case(true, _, false) =>\n (good(0, x), good(1, x), false)\n case(false, _, true) =>\n (false, good(1, x), good(2, x))\n }\n if (y == (false, false, false))\n stop = true\n x += 3\n }\n if (stop)\n \"NO\"\n else\n \"YES\"\n }\n println(res.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 val res = (1 to t).map {j =>\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val str = (1 to 3).map(_ => in.next())\n var y = if (str.head.head == 's') (true, false, false)\n else if (str(1).head == 's') (false, true, false)\n else (false, false, true)\n var x = 0\n var stop = false\n def good(y: Int, x: Int) = {\n (x + 1 to Math.min(x + 1 + 3, n - 1)).forall(j => str(y)(j) == '.')\n }\n\n while (x < n && !stop) {\n y = y match {\n case(_, true, _) =>\n (good(0, x), good(1, x), good(2, x))\n case(true, false, true) =>\n (good(0, x), good(1, x), good(2, x))\n case(true, _, false) =>\n (good(0, x), good(1, x), false)\n case(false, _, true) =>\n (false, good(1, x), good(2, x))\n }\n if (y == (false, false, false))\n stop = true\n x += 3\n }\n if (stop)\n \"NO\"\n else\n \"YES\"\n }\n println(res.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 val res = (1 to t).map {j =>\n val Array(n, k) = in.next().split(\" \").map(_.toInt)\n val str = (1 to 3).map(_ => in.next())\n var y = if (str.head.head == 's') (true, false, false)\n else if (str(1).head == 's') (false, true, false)\n else (false, false, true)\n var x = 0\n var stop = false\n def good(y: Int, x: Int) = {\n (x + 1 to Math.min(x + 1 + 2, n - 1)).forall(j => str(y)(j) == '.')\n }\n\n while (x < n && !stop) {\n y = y match {\n case(_, true, _) =>\n (good(0, x), good(1, x), good(2, x))\n case(true, false, true) =>\n (good(0, x), good(1, x), good(2, x))\n case(true, _, false) =>\n (good(0, x), good(1, x), false)\n case(false, _, true) =>\n (false, good(1, x), good(2, x))\n }\n if (y == (false, false, false))\n stop = true\n x += 3\n }\n if (stop)\n \"NO\"\n else\n \"YES\"\n }\n println(res.mkString(\"\\n\"))\n\n}"}], "src_uid": "5c1707b614dc3326a9bb092e6ca24280"} {"nl": {"description": "Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens: If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece. Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.", "input_spec": "The first line of the input contains integers n, h and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009h\u2009\u2264\u2009109)\u00a0\u2014 the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009h)\u00a0\u2014 the heights of the pieces.", "output_spec": "Print a single integer\u00a0\u2014 the number of seconds required to smash all the potatoes following the process described in the problem statement.", "sample_inputs": ["5 6 3\n5 4 3 2 1", "5 6 3\n5 5 5 5 5", "5 6 3\n1 2 1 1 1"], "sample_outputs": ["5", "10", "2"], "notes": "NoteConsider the first sample. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3. During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2\u00b75\u2009=\u200910 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds."}, "positive_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(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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier \u2014 a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.", "input_spec": "The first line contains two integers: x (1\u2009\u2264\u2009x\u2009\u2264\u20094000) \u2014 the round Sereja is taking part in today, and k (0\u2009\u2264\u2009k\u2009<\u20094000) \u2014 the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: \"1 num2 num1\" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1\u2009-\u2009num2\u2009=\u20091. If Sereja took part in a usual Div2 round, then the corresponding line looks like: \"2 num\" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.", "output_spec": "Print in a single line two integers \u2014 the minimum and the maximum number of rounds that Sereja could have missed.", "sample_inputs": ["3 2\n2 1\n2 2", "9 3\n1 2 3\n2 8\n1 4 5", "10 0"], "sample_outputs": ["0 0", "2 3", "5 9"], "notes": "NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds."}, "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"}, {"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"}], "negative_code": [], "src_uid": "fb77c9339250f206e7188b951902a221"} {"nl": {"description": "The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If x\u2009=\u20091, exit the function. Otherwise, call f(x\u2009-\u20091), and then make swap(ax\u2009-\u20091,\u2009ax) (swap the x-th and (x\u2009-\u20091)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.", "input_spec": "A single line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the size of permutation.", "output_spec": "In a single line print n distinct integers from 1 to n \u2014 the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.", "sample_inputs": ["1", "2"], "sample_outputs": ["1", "2 1"], "notes": null}, "positive_code": [{"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"}, {"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": "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"}, {"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"}], "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"} {"nl": {"description": "This is the easy version of the problem. The only difference is that in this version $$$n \\leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 2000$$$) \u2014 the number of potions. The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$) which represent the change in health after drinking that potion.", "output_spec": "Output a single integer, the maximum number of potions you can drink without your health becoming negative.", "sample_inputs": ["6\n4 -4 1 -3 1 -3"], "sample_outputs": ["5"], "notes": "NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point"}, "positive_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[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"}, {"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": "\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}"}], "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"} {"nl": {"description": "Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi\u00a0\u2014 the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.", "input_spec": "The first line contains four positive integers n, k, s and t (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009k\u2009\u2264\u20092\u00b7105, 2\u2009\u2264\u2009s\u2009\u2264\u2009109, 1\u2009\u2264\u2009t\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1\u2009\u2264\u2009ci,\u2009vi\u2009\u2264\u2009109)\u00a0\u2014 the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1,\u2009g2,\u2009...,\u2009gk (1\u2009\u2264\u2009gi\u2009\u2264\u2009s\u2009-\u20091)\u00a0\u2014 the positions of the gas stations on the road in arbitrary order.", "output_spec": "Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.", "sample_inputs": ["3 1 8 10\n10 8\n5 7\n11 9\n3", "2 2 10 18\n10 4\n20 6\n5 3"], "sample_outputs": ["10", "20"], "notes": "NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel. "}, "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 case class Car(cost: Int, volume: Int)\n\n val Array(n, k, s, t) = readInts(4)\n\n val cars = Array.fill(n) {\n val Array(c, v) = readInts(2)\n Car(c, v)\n }\n\n val gs = readInts(k).sorted\n\n def timeToTravel(dist: Int, fuel: Int): Double = {\n val distAtHiSpeed = if (fuel > dist) Math.min(fuel - dist, dist) else 0d\n val distAtLoSpeed = if (fuel >= dist) dist - distAtHiSpeed else Double.PositiveInfinity\n\n distAtLoSpeed * 2 + distAtHiSpeed\n }\n\n def can(tankVolume: Int): Boolean = {\n var currentPos = 0\n var currentTime = 0d\n var i = 0\n while (i < k && currentTime <= t) {\n val dist = gs(i) - currentPos\n currentTime += timeToTravel(dist, tankVolume)\n currentPos = gs(i)\n i += 1\n }\n currentTime += timeToTravel(s - currentPos, tankVolume)\n\n currentTime <= t\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\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 minVolume = binSearch(1, cars.maxBy(_.volume).volume)\n\n val suitableCars = cars.filter(_.volume >= minVolume)\n\n if (suitableCars.isEmpty) println(-1)\n else println(suitableCars.minBy(_.cost).cost)\n}\n"}], "negative_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 case class Car(cost: Int, volume: Int)\n\n val Array(n, k, s, t) = readInts(4)\n\n val cars = Array.fill(n) {\n val Array(c, v) = readInts(2)\n Car(c, v)\n }\n\n val gs = readInts(k).sorted\n\n def timeToTravel(dist: Int, fuel: Int): Int = {\n val distAtHiSpeed = if (fuel > dist) Math.min(fuel - dist, dist) else 0\n val distAtLoSpeed = if (fuel >= dist) dist - distAtHiSpeed else t\n\n distAtLoSpeed * 2 + distAtHiSpeed\n }\n\n def can(tankVolume: Int): Boolean = {\n var currentPos = 0\n var currentTime = 0d\n var i = 0\n while (i < k && currentTime <= t) {\n val dist = gs(i) - currentPos\n currentTime += timeToTravel(dist, tankVolume)\n currentPos = gs(i)\n i += 1\n }\n currentTime += timeToTravel(s - currentPos, tankVolume)\n\n currentTime <= t\n }\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\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 minVolume = binSearch(1, cars.maxBy(_.volume).volume)\n\n val suitableCars = cars.filter(_.volume >= minVolume)\n\n if (suitableCars.isEmpty) println(-1)\n else println(suitableCars.minBy(_.cost).cost)\n}\n"}], "src_uid": "740a1ee41a5a4c55b505abb277c06b8a"} {"nl": {"description": "Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: \"Can you solve a problem I'm stuck at all day?\"We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009m) type of ice cream form a connected subgraph. We build a new graph G with m vertices. We put an edge between the v-th and the u-th (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009m, u\u2009\u2260\u2009v) vertices in G if and only if there exists a vertex in T that has both the v-th and the u-th types of ice cream in its set. The problem is to paint the vertices of G with minimum possible number of colors in a way that no adjacent vertices have the same color.Please note that we consider that empty set of vertices form a connected subgraph in this problem.As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.", "input_spec": "The first line contains two integer n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20093\u00b7105)\u00a0\u2014 the number of vertices in T and the number of ice cream types. n lines follow, the i-th of these lines contain single integer si (0\u2009\u2264\u2009si\u2009\u2264\u20093\u00b7105) and then si distinct integers, each between 1 and m\u00a0\u2014 the types of ice cream in the i-th vertex. The sum of si doesn't exceed 5\u00b7105. n\u2009-\u20091 lines follow. Each of these lines describes an edge of the tree with two integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n)\u00a0\u2014 the indexes of connected by this edge vertices.", "output_spec": "Print single integer c in the first line\u00a0\u2014 the minimum number of colors to paint the vertices in graph G. In the second line print m integers, the i-th of which should be the color of the i-th vertex. The colors should be between 1 and c. If there are some answers, print any of them.", "sample_inputs": ["3 3\n1 1\n2 2 3\n1 2\n1 2\n2 3", "4 5\n0\n1 1\n1 3\n3 2 4 5\n2 1\n3 2\n4 3"], "sample_outputs": ["2\n1 1 2", "3\n1 1 1 2 3"], "notes": "NoteIn the first example the first type of ice cream is present in the first vertex only, so we can color it in any color. The second and the third ice cream are both presented in the second vertex, so we should paint them in different colors.In the second example the colors of the second, the fourth and the fifth ice cream should obviously be distinct."}, "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 val Array(n, m) = readInts(2)\n\n val cols = Array.fill(m){ 0 }\n val ices = Array.ofDim[Array[Int]](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val s = tl.nextToken.toInt\n ices(i) = Array.fill(s){tl.nextToken.toInt - 1}\n }\n\n var leaf = 0\n val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\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 val adjs = adjBuilders.map(_.result)\n\n def dfs(u: Int, parent: Int): Unit = {\n\n val used = new mutable.BitSet\n val ics = ices(u)\n\n var j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) > 0) used += cols(i)\n j += 1\n }\n\n var next = 1\n\n j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) == 0) {\n while (used(next)) next += 1\n cols(i) = next\n next += 1\n }\n j += 1\n }\n\n j = 0\n while (j < adjs(u).length) {\n val v = adjs(u)(j)\n if (v != parent) dfs(v, u)\n j += 1\n }\n\n }\n\n dfs(0, -1)\n\n for (i <- cols.indices) if (cols(i) == 0) cols(i) = 1\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(cols.max)\n println(cols.mkString(\" \"))\n\n Console.flush\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 val Array(n, m) = readInts(2)\n\n val cols = Array.fill(m){ 0 }\n val ices = Array.ofDim[Array[Int]](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val s = tl.nextToken.toInt\n ices(i) = Array.fill(s){tl.nextToken.toInt - 1}\n }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n }\n\n val icesSorted = ices.sortBy(- _.length)\n\n val used = new mutable.BitSet\n\n for (ics <- icesSorted) {\n\n used.clear()\n//println(ics.mkString(\", \"))\n var j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) > 0) used += cols(i)\n j += 1\n }\n\n var next = 1\n\n j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) == 0) {\n while (used(next)) next += 1\n cols(i) = next\n next += 1\n }\n j += 1\n }\n }\n\n for (i <- cols.indices) if (cols(i) == 0) cols(i) = 1\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(cols.max)\n println(cols.mkString(\" \"))\n\n Console.flush\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 cols = Array.fill(m){ 0 }\n val ices = Array.ofDim[Array[Int]](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val s = tl.nextToken.toInt\n ices(i) = Array.fill(s){tl.nextToken.toInt - 1}\n }\n\n for (i <- 1 until n) {\n val Array(u, v) = readInts(2)\n }\n\n val icesSorted = ices.sortBy(- _.length)\n\n val used = new mutable.BitSet\n\n for (ics <- icesSorted) {\n\n used.clear()\n//println(ics.mkString(\", \"))\n var j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) > 0) used += cols(i)\n j += 1\n }\n\n var next = 1\n\n j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) == 0) {\n while (used(next)) next += 1\n cols(i) = next\n next += 1\n }\n j += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(cols.max)\n println(cols.mkString(\" \"))\n\n Console.flush\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 cols = Array.fill(m){ 0 }\n val ices = Array.ofDim[Array[Int]](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val s = tl.nextToken.toInt\n ices(i) = Array.fill(s){tl.nextToken.toInt - 1}\n }\n\n val icesSorted = ices.sortBy(- _.length)\n\n val used = new mutable.BitSet\n\n for (ics <- icesSorted) {\n\n used.clear()\n//println(ics.mkString(\", \"))\n var j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) > 0) used += cols(i)\n j += 1\n }\n\n var next = 1\n\n j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) == 0) {\n while (used(next)) next += 1\n cols(i) = next\n next += 1\n }\n j += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(cols.max)\n println(cols.mkString(\" \"))\n\n Console.flush\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 cols = Array.fill(m){ 0 }\n val ices = Array.ofDim[Array[Int]](n)\n\n for (i <- 0 until n) {\n val tl = tokenizeLine\n val s = tl.nextToken.toInt\n ices(i) = Array.fill(s){tl.nextToken.toInt - 1}\n }\n\n val icesSorted = ices.sortBy(- _.length)\n\n val used = new mutable.BitSet\n\n for (ics <- icesSorted) {\n used.clear()\n var j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) > 0) used += cols(i)\n j += 1\n }\n var next = 1\n j = 0\n while (j < ics.length) {\n val i = ics(j)\n if (cols(i) == 0) {\n while (used(next)) next += 1\n cols(i) = next\n next += 1\n }\n j += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(cols.max)\n println(cols.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "62241c11a5724d6c7e97a0892cd4f6fb"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \\cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2000$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \\le n \\le 100; -100 \\le a, b \\le 100$$$)\u00a0\u2014 the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the maximum number of points that you can score.", "sample_inputs": ["3\n3 2 0\n000\n5 -2 5\n11001\n6 1 -4\n100111"], "sample_outputs": ["6\n15\n-2"], "notes": "NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \\cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \\cdot 1 + 5 = 3$$$ points, i.\u2009e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \\cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \\cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations."}, "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 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"}, {"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"} {"nl": {"description": "You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands: for $$$n$$$ \u2014 for loop; end \u2014 every command between \"for $$$n$$$\" and corresponding \"end\" is executed $$$n$$$ times; add \u2014 adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every \"for $$$n$$$\" is matched with \"end\", thus the function is guaranteed to be valid. \"for $$$n$$$\" can be immediately followed by \"end\".\"add\" command can be outside of any for loops.Notice that \"add\" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some \"add\" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output \"OVERFLOW!!!\", otherwise print the resulting value of $$$x$$$.", "input_spec": "The first line contains a single integer $$$l$$$ ($$$1 \\le l \\le 10^5$$$) \u2014 the number of lines in the function. Each of the next $$$l$$$ lines contains a single command of one of three types: for $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 for loop; end \u2014 every command between \"for $$$n$$$\" and corresponding \"end\" is executed $$$n$$$ times; add \u2014 adds 1 to $$$x$$$. ", "output_spec": "If overflow happened during execution of $$$f(0)$$$, then output \"OVERFLOW!!!\", otherwise print the resulting value of $$$x$$$.", "sample_inputs": ["9\nadd\nfor 43\nend\nfor 10\nfor 15\nadd\nend\nadd\nend", "2\nfor 62\nend", "11\nfor 100\nfor 100\nfor 100\nfor 100\nfor 100\nadd\nend\nend\nend\nend\nend"], "sample_outputs": ["161", "0", "OVERFLOW!!!"], "notes": "NoteIn the first example the first \"add\" is executed 1 time, the second \"add\" is executed 150 times and the last \"add\" is executed 10 times. Note that \"for $$$n$$$\" can be immediately followed by \"end\" and that \"add\" can be outside of any for loops.In the second example there are no commands \"add\", thus the returning value is 0.In the third example \"add\" command is executed too many times, which causes $$$x$$$ to go over $$$2^{32}-1$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers ti (1\u2009\u2264\u2009ti\u2009\u2264\u2009109), separated by spaces.", "output_spec": "Print a single number \u2014 the maximum number of not disappointed people in the queue.", "sample_inputs": ["5\n15 2 1 5 3"], "sample_outputs": ["4"], "notes": "NoteValue 4 is achieved at such an arrangement, for example: 1,\u20092,\u20093,\u20095,\u200915. Thus, you can make everything feel not disappointed except for the person with time 5."}, "positive_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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part \u2014 circle of radius r\u2009-\u2009d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i\u00a0-th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.", "input_spec": "First string contains two integer numbers r and d (0\u2009\u2264\u2009d\u2009<\u2009r\u2009\u2264\u2009500)\u00a0\u2014 the radius of pizza and the width of crust. Next line contains one integer number n\u00a0\u2014 the number of pieces of sausage (1\u2009\u2264\u2009n\u2009\u2264\u2009105). Each of next n lines contains three integer numbers xi, yi and ri (\u2009-\u2009500\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009500, 0\u2009\u2264\u2009ri\u2009\u2264\u2009500), where xi and yi are coordinates of the center of i-th peace of sausage, ri\u00a0\u2014 radius of i-th peace of sausage.", "output_spec": "Output the number of pieces of sausage that lay on the crust.", "sample_inputs": ["8 4\n7\n7 8 1\n-7 3 2\n0 2 1\n0 -2 2\n-3 -3 1\n0 6 2\n5 3 1", "10 8\n4\n0 0 9\n0 0 10\n1 0 1\n1 0 2"], "sample_outputs": ["2", "0"], "notes": "NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust. "}, "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}"}, {"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"}], "negative_code": [], "src_uid": "fce9d78ad7d4ea01be1704f588e42d37"} {"nl": {"description": "Recently, you found a bot to play \"Rock paper scissors\" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \\dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \\le pos \\le n$$$), and then it can play any number of rounds. In the first round, he chooses \"Rock\", \"Scissors\" or \"Paper\" based on the value of $$$s_{pos}$$$: if $$$s_{pos}$$$ is equal to R the bot chooses \"Rock\"; if $$$s_{pos}$$$ is equal to S the bot chooses \"Scissors\"; if $$$s_{pos}$$$ is equal to P the bot chooses \"Paper\"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round\u00a0\u2014 on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \\dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \\dots c_n$$$ such that $$$\\frac{win(1) + win(2) + \\dots + win(n)}{n}$$$ is maximum possible.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain test cases\u00a0\u2014 one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \\dots s_{n}$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$s_i \\in \\{\\text{R}, \\text{S}, \\text{P}\\}$$$)\u00a0\u2014 the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print $$$n$$$ choices $$$c_1 c_2 \\dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.", "sample_inputs": ["3\nRRRR\nRSP\nS"], "sample_outputs": ["PPPP\nRSP\nR"], "notes": "NoteIn the first test case, the bot (wherever it starts) will always choose \"Rock\", so we can always choose \"Paper\". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case: if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$; if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$; if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$; The average is equal to $$$\\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining \"Rock paper scissors\" game: "}, "positive_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') => 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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging\u00a0\u2014 but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1,\u2009...,\u2009an. There aren't any big jumps between consecutive data points\u00a0\u2014 for each 1\u2009\u2264\u2009i\u2009<\u2009n, it's guaranteed that |ai\u2009+\u20091\u2009-\u2009ai|\u2009\u2264\u20091.A range [l,\u2009r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l\u2009\u2264\u2009i\u2009\u2264\u2009r; the range [l,\u2009r] is almost constant if M\u2009-\u2009m\u2009\u2264\u20091.Find the length of the longest almost constant range.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of data points. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100\u2009000).", "output_spec": "Print a single number\u00a0\u2014 the maximum length of an almost constant range of the given sequence.", "sample_inputs": ["5\n1 2 3 3 2", "11\n5 4 5 5 6 7 8 8 8 7 6"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first sample, the longest almost constant range is [2,\u20095]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1,\u20094], [6,\u20099] and [7,\u200910]; the only almost constant range of the maximum length 5 is [6,\u200910]."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1,\u20094,\u20091] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1,\u20094] (from index 1 to index 2), imbalance value is 3; [1,\u20094,\u20091] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4,\u20091] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 size of the array a. The second line contains n integers a1,\u2009a2... an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 elements of the array.", "output_spec": "Print one integer \u2014 the imbalance value of a.", "sample_inputs": ["3\n1 4 1"], "sample_outputs": ["9"], "notes": null}, "positive_code": [{"source_code": "//hint: https://codeforces.com/contest/817/submission/27832753\n/* Divide and conquer */\n\nimport scala.math.min\nimport scala.math.max\n\nobject d extends App{\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 val n = InOut.nextInt\n val arr:Array[Int] = InOut.nextInts(n)\n val max_at:Array[Int] = new Array[Int](n)\n val min_at:Array[Int] = new Array[Int](n)\n\n def get_max(start:Int, end:Int):Long = {\n if (start == end){\n return arr(start)\n }\n\n val mid:Int = (start+end)/2\n var sum:Long = 0L\n var ans:Long = 0L\n var curr_max:Int = 0\n for(i <- mid+1 to end){\n curr_max = max(curr_max, arr(i))\n sum += curr_max\n max_at(i) = curr_max\n }\n\n var right = mid+1\n curr_max = 0\n for (i <- mid to start by -1){\n curr_max = max(curr_max, arr(i))\n while (right <= end && max_at(right) <= curr_max){\n sum -= max_at(right)\n right += 1\n }\n val scope:Long = right-mid-1\n ans += (sum + curr_max * scope)\n }\n return ans + get_max(start, mid) + get_max(mid+1, end) \n }\n\n def get_min(start:Int, end:Int):Long = {\n if (start == end){\n return arr(start)\n }\n val mid:Int = (start+end)/2\n var sum:Long = 0L\n var curr_min:Int = 100000000\n for (i <- mid+1 to end){\n curr_min = min(curr_min, arr(i))\n sum += curr_min\n min_at(i) = curr_min\n }\n\n var right:Int = mid+1\n curr_min = 100000000\n var ans:Long = 0L\n for (i <- mid to start by -1){\n curr_min = min(curr_min, arr(i))\n while (right <= end && min_at(right) > curr_min){\n sum -= min_at(right)\n right += 1\n }\n val scope:Long = right-mid-1\n ans += (sum + curr_min * scope)\n }\n return ans + get_min(start, mid) + get_min(mid+1, end)\n }\n\n print(get_max(0, n-1) - get_min(0, n-1))\n}\n"}], "negative_code": [{"source_code": "//hint: https://codeforces.com/contest/817/submission/27832753\n/* Divide and conquer */\n\nimport scala.math.min\nimport scala.math.max\n\nobject d extends App{\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 val n = InOut.nextInt\n val arr:Array[Int] = InOut.nextInts(n)\n val max_at:Array[Int] = new Array[Int](n)\n val min_at:Array[Int] = new Array[Int](n)\n\n def get_max(start:Int, end:Int):Long = {\n if (start == end){\n return arr(start)\n }\n\n val mid:Int = (start+end)>>1\n var sum:Long = 0\n var ans:Long = 0\n var curr_max:Int = 0\n for(i <- mid+1 to end){\n curr_max = max(curr_max, arr(i))\n sum += curr_max\n max_at(i) = curr_max\n }\n\n var right = mid+1\n curr_max = 0\n for (i <- mid to start by -1){\n curr_max = max(curr_max, arr(i))\n while (right <= end && max_at(right) <= curr_max){\n sum -= max_at(right)\n right += 1\n }\n ans += (sum + curr_max * (right-mid-1))\n }\n return ans + get_max(start, mid) + get_max(mid+1, end) \n }\n\n def get_min(start:Int, end:Int):Long = {\n if (start == end){\n return arr(start)\n }\n val mid:Int = (start+end) >> 1\n var ans:Long = 0\n var sum:Long = 0\n var curr_min:Int = 10000000\n for (i <- mid+1 to end){\n curr_min = min(curr_min, arr(i))\n sum += curr_min\n min_at(i) = curr_min\n }\n\n var right = mid+1\n curr_min = 10000000\n for (i <- mid to start by -1){\n curr_min = min(curr_min, arr(i))\n while (right <= end && min_at(right) > curr_min){\n sum -= min_at(right)\n right += 1\n }\n ans += (sum + curr_min * (right-mid-1))\n }\n return ans + get_min(start, mid) + get_min(mid+1, end)\n }\n\n print(get_max(0, n-1) - get_min(0, n-1))\n}\n"}, {"source_code": "//hint: https://codeforces.com/contest/817/submission/27832753\n/* Divide and conquer */\n\nimport scala.math.min\nimport scala.math.max\n\nobject d extends App{\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 val n = InOut.nextInt\n val arr:Array[Int] = InOut.nextInts(n)\n val max_at:Array[Int] = new Array[Int](n)\n val min_at:Array[Int] = new Array[Int](n)\n\n def get_max(start:Int, end:Int):Long = {\n if (start == end){\n return arr(start)\n }\n\n val mid:Int = (start+end)>>1\n var sum:Long = 0L\n var ans:Long = 0L\n var curr_max:Int = 0\n for(i <- mid+1 to end){\n curr_max = max(curr_max, arr(i))\n sum += curr_max\n max_at(i) = curr_max\n }\n\n var right = mid+1\n curr_max = 0\n for (i <- mid to start by -1){\n curr_max = max(curr_max, arr(i))\n while (right <= end && max_at(right) <= curr_max){\n sum -= max_at(right)\n right += 1\n }\n ans += (sum + curr_max * (right-mid-1))\n }\n return ans + get_max(start, mid) + get_max(mid+1, end) \n }\n\n def get_min(start:Int, end:Int):Long = {\n if (start == end){\n return arr(start)\n }\n val mid:Int = (start+end) >> 1\n var ans:Long = 0L\n var sum:Long = 0L\n var curr_min:Int = 100000000\n for (i <- mid+1 to end){\n curr_min = min(curr_min, arr(i))\n sum += curr_min\n min_at(i) = curr_min\n }\n\n var right = mid+1\n curr_min = 100000000\n for (i <- mid to start by -1){\n curr_min = min(curr_min, arr(i))\n while (right <= end && min_at(right) > curr_min){\n sum -= min_at(right)\n right += 1\n }\n ans += (sum + curr_min * (right-mid-1))\n }\n return ans + get_min(start, mid) + get_min(mid+1, end)\n }\n\n print(get_max(0, n-1) - get_min(0, n-1))\n}\n"}], "src_uid": "38210a3dcb16ce2bbc81aa1d39d23112"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \\leq x$$$ holds for each $$$i$$$ ($$$1 \\le i \\le n$$$).", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\leq n \\leq 50$$$; $$$1 \\leq x \\leq 1000$$$)\u00a0\u2014 the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_1 \\le a_2 \\le \\dots \\le a_n \\leq x$$$)\u00a0\u2014 the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\leq b_1 \\le b_2 \\le \\dots \\le b_n \\leq x$$$)\u00a0\u2014 the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.", "output_spec": "For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \\leq x$$$ holds for each $$$i$$$ ($$$1 \\le i \\le n$$$) or No otherwise. Each character can be printed in any case.", "sample_inputs": ["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"], "sample_outputs": ["Yes\nYes\nNo\nNo"], "notes": "NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \\leq 4$$$; $$$2 + 2 \\leq 4$$$; $$$3 + 1 \\leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \\leq 6$$$; $$$4 + 2 \\leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$."}, "positive_code": [{"source_code": "\nobject P1445A extends App {\n import scala.collection.{immutable, mutable}\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(a: Seq[Int], b: Seq[Int], x: Int): Boolean = {\n var bSorted = new mutable.TreeMap[Int, Int]()(Ordering[Int].reverse)\n\n b.foreach((k) => bSorted(k)=bSorted.getOrElse(k, 0)+1)\n\n def haveNoMatch(v: Int) : Boolean = {\n val it = bSorted.iteratorFrom(x-v)\n if (!it.hasNext) true\n else {\n val (bVal, bCnt) = it.next()\n if (bCnt <= 1)\n bSorted.remove(bVal)\n else\n bSorted(bVal) = bSorted(bVal) - 1\n false\n }\n }\n\n !a.exists(haveNoMatch)\n }\n\n val nCases = scanInts(1)(0)\n\n for (nCase <- 1 to nCases) {\n val s = scanInts(2)\n val n = s(0)\n val x = s(1)\n\n val a = scanInts(n)\n val b = scanInts(n)\n scala.io.StdIn.readLine()\n\n println(if (solve(a, b, x)) \"Yes\" else \"No\")\n }\n}"}], "negative_code": [], "src_uid": "7e765c1b0e3f3e9c44de825a79bc1da2"} {"nl": {"description": "The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0\u2009\u2264\u2009si\u2009\u2264\u2009c).Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t\u2009+\u20091) this star will have brightness x\u2009+\u20091, if x\u2009+\u20091\u2009\u2264\u2009c, and 0, otherwise.You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right\u00a0\u2014 (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.A star lies in a rectangle if it lies on its border or lies strictly inside it.", "input_spec": "The first line contains three integers n, q, c (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009105, 1\u2009\u2264\u2009c\u2009\u2264\u200910)\u00a0\u2014 the number of the stars, the number of the views and the maximum brightness of the stars. The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009100, 0\u2009\u2264\u2009si\u2009\u2264\u2009c\u2009\u2264\u200910)\u00a0\u2014 the coordinates of i-th star and its initial brightness. The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0\u2009\u2264\u2009ti\u2009\u2264\u2009109, 1\u2009\u2264\u2009x1i\u2009<\u2009x2i\u2009\u2264\u2009100, 1\u2009\u2264\u2009y1i\u2009<\u2009y2i\u2009\u2264\u2009100)\u00a0\u2014 the moment of the i-th view and the coordinates of the viewed rectangle.", "output_spec": "For each view print the total brightness of the viewed stars.", "sample_inputs": ["2 3 3\n1 1 1\n3 2 0\n2 1 1 2 2\n0 2 1 4 5\n5 1 1 5 5", "3 4 5\n1 1 2\n2 3 0\n3 3 1\n0 1 1 100 100\n1 2 2 4 4\n2 2 1 4 7\n1 50 50 51 51"], "sample_outputs": ["3\n0\n3", "3\n3\n5\n0"], "notes": "NoteLet's consider the first example.At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3."}, "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, 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"}, {"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"} {"nl": {"description": "n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji\u2009=\u20091\u2009-\u2009aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200918) \u2014 the amount of fish in the lake. Then there follow n lines with n real numbers each \u2014 matrix a. aij (0\u2009\u2264\u2009aij\u2009\u2264\u20091) \u2014 the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij\u2009=\u20091\u2009-\u2009aji. All real numbers are given with not more than 6 characters after the decimal point.", "output_spec": "Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.", "sample_inputs": ["2\n0 0.5\n0.5 0", "5\n0 1 1 1 1\n0 0 0.5 0.5 0.5\n0 0.5 0 0.5 0.5\n0 0.5 0.5 0 0.5\n0 0.5 0.5 0.5 0"], "sample_outputs": ["0.500000 0.500000", "1.000000 0.000000 0.000000 0.000000 0.000000"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by Meepo on 17/3/14.\n */\nobject Main extends App\n{\n val input = new Scanner(System.in)\n val n = input.nextInt()\n val arr = Array.ofDim[Double](n, n)\n for (i <- arr.indices; j <- arr.indices)\n arr(i)(j) = input.nextDouble()\n\n val dp = Array.ofDim[Double](1 << n)\n dp((1 << n) - 1) = 1.0\n\n def fishNum(stateInput: Int): Int =\n {\n var state = stateInput\n var fish = 0\n while (state != 0)\n {\n fish += state & 1\n state = state >> 1\n }\n fish\n }\n\n var i = (1 << n) - 1\n while (i >= 1)\n {\n val fish = fishNum(i)\n if (fish != 1)\n {\n val choose = 2.0 * dp(i) / fish / (fish - 1)\n for (j <- 0 until n)\n {\n if ((i & (1 << j)) != 0)\n {\n for (k <- 0 until n)\n {\n if ((i & (1 << k)) != 0)\n dp(i ^ (1 << k)) += choose * arr(j)(k)\n }\n }\n }\n\n\n }\n i -= 1\n }\n\n val ans =\n {\n for (i <- 0 until n) yield\n dp(1 << i).formatted(\"%.6f\")\n }.mkString(\" \")\n println(ans)\n\n}\n"}], "negative_code": [], "src_uid": "da2d76d47c1ed200982495dc4a234014"} {"nl": {"description": " Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $$$n$$$ steps. At the $$$i$$$-th step, a place is chosen for the number $$$i$$$ $$$(1 \\leq i \\leq n)$$$. The position for the number $$$i$$$ is defined as follows: For all $$$j$$$ from $$$1$$$ to $$$n$$$, we calculate $$$r_j$$$ \u00a0\u2014 the minimum index such that $$$j \\leq r_j \\leq n$$$, and the position $$$r_j$$$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $$$r_j$$$ is not defined. For all $$$t$$$ from $$$1$$$ to $$$n$$$, we calculate $$$count_t$$$ \u00a0\u2014 the number of positions $$$1 \\leq j \\leq n$$$ such that $$$r_j$$$ is defined and $$$r_j = t$$$. Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $$$count$$$ array is maximum. The generator selects one of these positions for the number $$$i$$$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example: Let $$$n = 5$$$ and the algorithm has already arranged the numbers $$$1, 2, 3$$$ in the permutation. Consider how the generator will choose a position for the number $$$4$$$: The values of $$$r$$$ will be $$$r = [3, 3, 3, 4, \\times]$$$, where $$$\\times$$$ means an indefinite value. Then the $$$count$$$ values will be $$$count = [0, 0, 3, 1, 0]$$$. There are only two unoccupied positions in the permutation: $$$3$$$ and $$$4$$$. The value in the $$$count$$$ array for position $$$3$$$ is $$$3$$$, for position $$$4$$$ it is $$$1$$$. The maximum value is reached only for position $$$3$$$, so the algorithm will uniquely select this position for number $$$4$$$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $$$p_1, p_2, \\ldots, p_n$$$ and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10^5)$$$ \u00a0\u2014 the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ $$$(1 \\leq n \\leq 10^5)$$$ \u00a0\u2014 the size of the permutation. The second line of the test case contains $$$n$$$ different integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\leq p_i \\leq n$$$) \u00a0\u2014 the permutation written by Denis. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "Print \"Yes\" if this permutation could be obtained as a result of the generator. Otherwise, print \"No\". All letters can be displayed in any case.", "sample_inputs": ["5\n5\n2 3 4 5 1\n1\n1\n3\n1 3 2\n4\n4 2 3 1\n5\n1 5 2 4 3"], "sample_outputs": ["Yes\nYes\nNo\nYes\nNo"], "notes": "NoteLet's simulate the operation of the generator in the first test.At the $$$1$$$ step, $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. The maximum value is reached in any free position, so the generator can choose a random position from $$$1$$$ to $$$5$$$. In our example, it chose $$$5$$$.At the $$$2$$$ step, $$$r = [1, 2, 3, 4, \\times], count = [1, 1, 1, 1, 0]$$$. The maximum value is reached in positions from $$$1$$$ to $$$4$$$, so the generator can choose a random position among them. In our example, it chose $$$1$$$.At the $$$3$$$ step, $$$r = [2, 2, 3, 4, \\times], count = [0, 2, 1, 1, 0]$$$. The maximum value is $$$2$$$ and is reached only at the $$$2$$$ position, so the generator will choose this position.At the $$$4$$$ step, $$$r = [3, 3, 3, 4, \\times], count = [0, 0, 3, 1, 0]$$$. The maximum value is $$$3$$$ and is reached only at the $$$3$$$ position, so the generator will choose this position.At the $$$5$$$ step, $$$r = [4, 4, 4, 4, \\times], count = [0, 0, 0, 4, 0]$$$. The maximum value is $$$4$$$ and is reached only at the $$$4$$$ position, so the generator will choose this position.In total, we got a permutation of $$$2, 3, 4, 5, 1$$$, that is, a generator could generate it."}, "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 ps = nextInts(n).map(_ - 1)\n val pos = Array.ofDim[Int](n)\n val counts = mutable.TreeMap.empty[Int, Int].withDefaultValue(0)\n counts(1) = n\n val countsByPos = Array.fill(n)(1)\n val next = new java.util.TreeSet[Int]\n for (i <- 0 until n) {\n pos(ps(i)) = i\n next.add(i)\n }\n var i = 0\n var ok = true\n while (i < n) {\n val p = pos(i)\n val c = countsByPos(p)\n if (c == counts.max._1) {\n val r: Integer = next.higher(p)\n if (r != null && r > p) {\n countsByPos(r) += countsByPos(p)\n counts(countsByPos(r)) += 1\n }\n next.remove(p)\n counts(countsByPos(p)) -= 1\n if (counts(countsByPos(p)) == 0) {\n counts.remove(countsByPos(p))\n }\n countsByPos(p) = 0\n } else {\n ok = false\n i = n\n }\n i += 1\n }\n\n out.println(if (ok) \"Yes\" else \"No\")\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": "dc03b66a4c6aac69372d594784f3f083"} {"nl": {"description": "Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which two planks of length at least $$$k+1$$$ \u2014 the base of the ladder; $$$k$$$ planks of length at least $$$1$$$ \u2014 the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps. You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised \"ladder\" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^5$$$) \u2014 the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.", "sample_inputs": ["4\n4\n1 3 1 3\n3\n3 3 2\n5\n2 3 3 4 2\n3\n1 1 2"], "sample_outputs": ["2\n1\n2\n0"], "notes": "NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders: "}, "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": "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.", "input_spec": "The first line of the input contains three integers n, m, k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u20091000)\u00a0\u2014 the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20092). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. ", "output_spec": "Print a single integer \u2014 the minimum number of times Valera will need to wash a plate/bowl.", "sample_inputs": ["3 1 1\n1 2 1", "4 3 1\n1 1 1 1", "3 1 2\n2 2 2", "8 2 2\n1 2 1 2 1 2 1 2"], "sample_outputs": ["1", "1", "0", "4"], "notes": "NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl."}, "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 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 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 // \u9700\u8981\u6d17\u7684\u7897\n val needWashBowl = if (m - needBowl >= 0) {\n 0\n } else {\n needBowl - m\n }\n\n // \u9700\u8981\u6d17\u7684\u5176\u4ed6\n val needWashAny: Int = if (needWashBowl == 0) {\n needAny - (m - needBowl + k) // \u5b58\u91cf\u7684\u5176\u4ed6\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": "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}"}, {"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 // \u9700\u8981\u6d17\u7684\u7897\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"} {"nl": {"description": "Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 7000$$$) \u2014 the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \\leq a_i < 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \\leq b_i \\leq 10^9$$$).", "output_spec": "Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.", "sample_inputs": ["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"], "sample_outputs": ["15", "0", "0"], "notes": "NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util\n val n = ni()\n val a = nal(n)\n val b = na(n)\n val c = Array.ofDim[Int](n)\n REP(n) { i =>\n REP(n) { j =>\n if (i != j) {\n if ((a(i)^a(j)&a(i)) > 0) {\n c(i) += 1\n }\n }\n }\n }\n val alive = Array.fill[Boolean](n)(true)\n val q = new util.ArrayDeque[Int]\n REP(n) { i =>\n if (c(i) == n - 1) {\n alive(i) = false\n q.add(i)\n }\n }\n\n var setCnt = n\n while (!q.isEmpty) {\n val v = q.poll()\n debug(s\"v:$v\")\n setCnt -= 1\n REP(n) { u =>\n if ((a(v)^a(u)&a(v)) > 0 && alive(u)) {\n if ((a(u) ^ a(v) & a(u)) > 0) c(u) -= 1\n if (c(u) == setCnt - 1) {\n alive(u) = false\n q.add(u)\n }\n }\n }\n }\n debug(alive)\n var ans = 0L\n REP(n) { i =>\n if (alive(i)) ans += b(i)\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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util\n val n = ni()\n val a = nal(n)\n val b = na(n)\n val c = Array.ofDim[Int](n)\n val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())\n REP(n) { i =>\n REP(n) { j =>\n if (i != j) {\n if ((a(i)^a(j)&a(i)) > 0) {\n g(i) += j\n c(i) += 1\n }\n }\n }\n }\n debug(g.mkString(\" \"))\n val alive = Array.fill[Boolean](n)(true)\n val q = new util.ArrayDeque[Int]\n REP(n) { i =>\n if (c(i) == n - 1) q.add(i)\n }\n\n var setCnt = n\n while (!q.isEmpty) {\n val v = q.poll()\n debug(s\"v:$v\")\n setCnt -= 1\n alive(v) = false\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (alive(u)) {\n if ((a(u) ^ a(v) & a(u)) > 0) c(u) -= 1\n if (c(u) == setCnt - 1) q.add(u)\n }\n }\n }\n debug(alive)\n var ans = 0L\n REP(n) { i =>\n if (alive(i)) ans += b(i)\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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util\n val n = ni()\n val a = nal(n)\n val b = na(n)\n val c = Array.ofDim[Int](n)\n val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())\n REP(n) { i =>\n REP(n) { j =>\n if (i != j) {\n if ((a(i)^a(j)&a(i)) > 0) {\n g(i) += j\n c(i) += 1\n }\n }\n }\n }\n debug(g.mkString(\" \"))\n val alive = Array.fill[Boolean](n)(true)\n val q = new util.ArrayDeque[Int]\n REP(n) { i =>\n if (c(i) == n - 1) q.add(i)\n }\n\n var setCnt = n\n while (!q.isEmpty) {\n val v = q.poll()\n debug(s\"v:$v\")\n setCnt -= 1\n alive(v) = false\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if ((a(u)^a(v)&a(u)) > 0) c(u) -= 1\n if (c(u) == setCnt - 1) q.add(u)\n }\n }\n debug(alive)\n var ans = 0L\n REP(n) { i =>\n if (alive(i)) ans += b(i)\n }\n out.println(ans)\n }\n}"}], "src_uid": "9404ec14922a69082f3573bbaf78ccf0"} {"nl": {"description": "Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin \"A\", vitamin \"B\" and vitamin \"C\". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.", "input_spec": "The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 1\\,000)$$$ \u2014 the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \\le c_i \\le 100\\,000)$$$ and a string $$$s_i$$$ \u2014 the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are \"A\", \"B\" and \"C\". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.", "output_spec": "Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.", "sample_inputs": ["4\n5 C\n6 B\n16 BAC\n4 A", "2\n10 AB\n15 BA", "5\n10 A\n9 BC\n11 CA\n4 A\n5 B", "6\n100 A\n355 BCA\n150 BC\n160 AC\n180 B\n190 CA", "2\n5 BA\n11 CB"], "sample_outputs": ["15", "-1", "13", "250", "16"], "notes": "NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin \"C\"."}, "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 Inf = 1e7.toInt\n val map = mutable.Map[String, Int]() withDefaultValue Inf\n\n rep(N) { _ =>\n val v = ni()\n val vit = ns().sorted\n if (v < map(vit)) map(vit) = v\n }\n\n val vals = map map {\n case (\"A\", v) => min(map(\"B\") + map(\"C\"), map(\"BC\")) + v\n case (\"B\", v) => min(map(\"A\") + map(\"C\"), map(\"AC\")) + v\n case (\"C\", v) => min(map(\"A\") + map(\"B\"), map(\"AB\")) + v\n case (\"AB\", v) => min(min(map(\"C\"), map(\"AC\")), map(\"BC\")) + v\n case (\"AC\", v) => min(min(map(\"B\"), map(\"AB\")), map(\"BC\")) + v\n case (\"BC\", v) => min(min(map(\"A\"), map(\"AB\")), map(\"AC\")) + v\n case (\"ABC\", v) => v\n }\n\n val ans = vals.min\n\n out.println(if (ans >= Inf) -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 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": "02d62bb1eb4cc0e373b862a980d6b29c"} {"nl": {"description": "You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 10^5; 1 \\le m \\le 10^5$$$)\u00a0\u2014 the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \\le s_j, t_j \\le n; s_j \\ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.", "output_spec": "Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.", "sample_inputs": ["7 6\n10 8 9 6 8 12 7\n1 2\n1 7\n4 6\n7 1\n3 5\n4 2"], "sample_outputs": ["2\n10\n0\n7\n3\n1"], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "a6f42cb2627a7d1f6e01860322c5aac5"} {"nl": {"description": "Petya's friends made him a birthday present \u2014 a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning \"(\" into \")\" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if: $$$s$$$ is empty; $$$s$$$ is equal to \"($$$t$$$)\", where $$$t$$$ is correct bracket sequence; $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, \"(()())\", \"()\" are correct, while \")(\" and \"())\" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.", "input_spec": "First of line of input contains a single number $$$n$$$ ($$$1 \\leq n \\leq 200\\,000$$$)\u00a0\u2014 length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols \"(\" and \")\".", "output_spec": "Print \"Yes\" if Petya can make his sequence correct moving at most one bracket. Otherwise print \"No\".", "sample_inputs": ["2\n)(", "3\n(()", "2\n()", "10\n)))))((((("], "sample_outputs": ["Yes", "No", "Yes", "No"], "notes": "NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into \"()\", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets."}, "positive_code": [{"source_code": "object C {\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) = readInts(1)\n val s = readLine\n\n var x = 0\n var ok = true\n for (c <- s) {\n if (c == '(') x += 1 else x -= 1\n if (x < -1) ok = false\n }\n\n val res = ok && x == 0\n println(if (res) \"Yes\" else \"No\")\n}\n"}], "negative_code": [], "src_uid": "e30085b163c820cff68fb24b94088ec1"} {"nl": {"description": "Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or \u2009-\u20091. To pass the level, he needs to find a \u00abgood\u00bb subset of edges of the graph or say, that it doesn't exist. Subset is called \u00abgood\u00bb, if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di\u2009=\u2009\u2009-\u20091 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105, n\u2009-\u20091\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105) \u2014 number of vertices and edges. The second line contains n integers d1,\u2009d2,\u2009...,\u2009dn (\u2009-\u20091\u2009\u2264\u2009di\u2009\u2264\u20091) \u2014 numbers on the vertices. Each of the next m lines contains two integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n) \u2014 edges. It's guaranteed, that graph in the input is connected.", "output_spec": "Print \u2009-\u20091 in a single line, if solution doesn't exist. Otherwise in the first line k \u2014 number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.", "sample_inputs": ["1 0\n1", "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4", "2 1\n1 1\n1 2", "3 3\n0 -1 1\n1 2\n2 3\n1 3"], "sample_outputs": ["-1", "0", "1\n1", "1\n2"], "notes": "NoteIn the first sample we have single vertex without edges. It's degree is 0 and we can not get 1."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. Also you have a string $$$z$$$ which is initially empty. You want string $$$z$$$ to be equal to string $$$t$$$. You can perform the following operation to achieve this: append any subsequence of $$$s$$$ at the end of string $$$z$$$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $$$z = ac$$$, $$$s = abcde$$$, you may turn $$$z$$$ into following strings in one operation: $$$z = acace$$$ (if we choose subsequence $$$ace$$$); $$$z = acbcd$$$ (if we choose subsequence $$$bcd$$$); $$$z = acbce$$$ (if we choose subsequence $$$bce$$$). Note that after this operation string $$$s$$$ doesn't change.Calculate the minimum number of such operations to turn string $$$z$$$ into string $$$t$$$. ", "input_spec": "The first line contains the integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of test cases. The first line of each testcase contains one string $$$s$$$ ($$$1 \\le |s| \\le 10^5$$$) consisting of lowercase Latin letters. The second line of each testcase contains one string $$$t$$$ ($$$1 \\le |t| \\le 10^5$$$) consisting of lowercase Latin letters. It is guaranteed that the total length of all strings $$$s$$$ and $$$t$$$ in the input does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print one integer \u2014 the minimum number of operations to turn string $$$z$$$ into string $$$t$$$. If it's impossible print $$$-1$$$.", "sample_inputs": ["3\naabce\nace\nabacaba\naax\nty\nyyt"], "sample_outputs": ["1\n-1\n3"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Nezzar's favorite digit among $$$1,\\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\\ldots,a_q$$$, for each $$$1 \\le i \\le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 9$$$) \u2014 the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \\le q \\le 10^4$$$, $$$1 \\le d \\le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\\ldots,a_q$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "For each integer in each test case, print \"YES\" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print \"NO\". You can print letters in any case (upper or lower).", "sample_inputs": ["2\n3 7\n24 25 27\n10 7\n51 52 53 54 55 56 57 58 59 60"], "sample_outputs": ["YES\nNO\nYES\nYES\nYES\nNO\nYES\nYES\nYES\nYES\nYES\nYES\nNO"], "notes": "NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers."}, "positive_code": [{"source_code": "object CF1478B {\n def readIntArr(): Array[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toArray\n\n def main(args: Array[String]): Unit = {\n var T = scala.io.StdIn.readInt()\n for (t <- 0 until T) {\n var qd = readIntArr()\n var q = qd(0)\n var d = qd(1)\n\n var dp = new Array[Boolean](10 * d)\n dp(0) = true\n for (i <- 0 until 10 * d) {\n for (j <- 0 until d) {\n if (i + 10 * j + d < 10 * d)\n dp(i + 10 * j + d) |= dp(i)\n }\n }\n\n var u = readIntArr()\n for (i <- 0 until q) {\n if (u(i) >= 10 * d || dp(u(i))) {\n println(\"YES\")\n } else println(\"NO\")\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "7975af65a23bad6a0997921c7e31d3ca"} {"nl": {"description": "You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092000)\u00a0\u2014 the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1\u2009\u2264\u2009r\u2009\u2264\u2009n, 1\u2009\u2264\u2009c\u2009\u2264\u2009m)\u00a0\u2014 index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009109)\u00a0\u2014 the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.", "output_spec": "Print exactly one integer\u00a0\u2014 the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.", "sample_inputs": ["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."], "sample_outputs": ["10", "7"], "notes": "NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++. "}, "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.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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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"} {"nl": {"description": "Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \\dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$3 \\le n \\le 10^9$$$) \u2014 the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \\dots + 2^{k-1} x = n$$$.", "output_spec": "Print one integer \u2014 any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \\dots + 2^{k-1} x = n$$$.", "sample_inputs": ["7\n3\n6\n7\n21\n28\n999999999\n999999984"], "sample_outputs": ["1\n2\n1\n7\n4\n333333333\n333333328"], "notes": "NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \\cdot 1 + 2 \\cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \\cdot 2 + 2 \\cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \\cdot 1 + 2 \\cdot 1 + 4 \\cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \\cdot 7 + 2 \\cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \\cdot 4 + 2 \\cdot 4 + 4 \\cdot 4$$$ equals $$$n=28$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "DZY has a hash table with p buckets, numbered from 0 to p\u2009-\u20091. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x)\u2009=\u2009x\u00a0mod\u00a0p. Operation a\u00a0mod\u00a0b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a \"conflict\" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.", "input_spec": "The first line contains two integers, p and n (2\u2009\u2264\u2009p,\u2009n\u2009\u2264\u2009300). Then n lines follow. The i-th of them contains an integer xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109).", "output_spec": "Output a single integer \u2014 the answer to the problem.", "sample_inputs": ["10 5\n0\n21\n53\n41\n53", "5 5\n0\n1\n2\n3\n4"], "sample_outputs": ["4", "-1"], "notes": null}, "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": "\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"}, {"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"} {"nl": {"description": "Two integer sequences existed initially \u2014 one of them was strictly increasing, and the other one \u2014 strictly decreasing.Strictly increasing sequence is a sequence of integers $$$[x_1 < x_2 < \\dots < x_k]$$$. And strictly decreasing sequence is a sequence of integers $$$[y_1 > y_2 > \\dots > y_l]$$$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.They were merged into one sequence $$$a$$$. After that sequence $$$a$$$ got shuffled. For example, some of the possible resulting sequences $$$a$$$ for an increasing sequence $$$[1, 3, 4]$$$ and a decreasing sequence $$$[10, 4, 2]$$$ are sequences $$$[1, 2, 3, 4, 4, 10]$$$ or $$$[4, 2, 1, 10, 4, 3]$$$.This shuffled sequence $$$a$$$ is given in the input.Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one \u2014 strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print \"NO\".", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2 \\cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print \"NO\" in the first line. Otherwise print \"YES\" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. In the second line print $$$n_i$$$ \u2014 the number of elements in the strictly increasing sequence. $$$n_i$$$ can be zero, in this case the increasing sequence is empty. In the third line print $$$n_i$$$ integers $$$inc_1, inc_2, \\dots, inc_{n_i}$$$ in the increasing order of its values ($$$inc_1 < inc_2 < \\dots < inc_{n_i}$$$) \u2014 the strictly increasing sequence itself. You can keep this line empty if $$$n_i = 0$$$ (or just print the empty line). In the fourth line print $$$n_d$$$ \u2014 the number of elements in the strictly decreasing sequence. $$$n_d$$$ can be zero, in this case the decreasing sequence is empty. In the fifth line print $$$n_d$$$ integers $$$dec_1, dec_2, \\dots, dec_{n_d}$$$ in the decreasing order of its values ($$$dec_1 > dec_2 > \\dots > dec_{n_d}$$$) \u2014 the strictly decreasing sequence itself. You can keep this line empty if $$$n_d = 0$$$ (or just print the empty line). $$$n_i + n_d$$$ should be equal to $$$n$$$ and the union of printed sequences should be a permutation of the given sequence (in case of \"YES\" answer).", "sample_inputs": ["7\n7 2 7 3 3 1 4", "5\n4 3 1 5 3", "5\n1 1 2 1 2", "5\n0 1 2 3 4"], "sample_outputs": ["YES\n2\n3 7 \n5\n7 4 3 2 1", "YES\n1\n3 \n4\n5 4 3 1", "NO", "YES\n0\n\n5\n4 3 2 1 0"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "cdb19d87ad3713dac104252737153411"} {"nl": {"description": "Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1,\u2009a2,\u2009...,\u2009ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n\u2009-\u2009k cities, and, of course, flour delivery should be paid\u00a0\u2014 for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai\u2009\u2260\u2009b for every 1\u2009\u2264\u2009i\u2009\u2264\u2009k) and choose a storage in some city s (s\u2009=\u2009aj for some 1\u2009\u2264\u2009j\u2009\u2264\u2009k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.", "input_spec": "The first line of the input contains three integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, 1\u2009\u2264\u2009l\u2009\u2264\u2009109, u\u2009\u2260\u2009v) meaning that there is a road between cities u and v of length of l kilometers . If k\u2009>\u20090, then the last line of the input contains k distinct integers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009n)\u00a0\u2014 the number of cities having flour storage located in. If k\u2009=\u20090 then this line is not presented in the input.", "output_spec": "Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print \u2009-\u20091 in the only line.", "sample_inputs": ["5 4 2\n1 2 5\n1 2 3\n2 3 4\n1 4 10\n1 5", "3 1 1\n1 2 3\n3"], "sample_outputs": ["3", "-1"], "notes": "NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened. "}, "positive_code": [{"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"}, {"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 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"}, {"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}"}], "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"} {"nl": {"description": "Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $$$a$$$ minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $$$b$$$ minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $$$a$$$ minutes in total, then he sets his alarm to go off in $$$c$$$ minutes after it is reset and spends $$$d$$$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $$$c$$$ minutes and tries to fall asleep for $$$d$$$ minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains four integers $$$a, b, c, d$$$ ($$$1 \\le a, b, c, d \\le 10^9$$$)\u00a0\u2014 the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.", "output_spec": "For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.", "sample_inputs": ["7\n10 3 6 4\n11 3 6 4\n5 9 4 10\n6 5 2 3\n1 1 1 1\n3947465 47342 338129 123123\n234123843 13 361451236 361451000"], "sample_outputs": ["27\n27\n9\n-1\n1\n6471793\n358578060125049"], "notes": "NoteIn the first testcase Polycarp wakes up after $$$3$$$ minutes. He only rested for $$$3$$$ minutes out of $$$10$$$ minutes he needed. So after that he sets his alarm to go off in $$$6$$$ minutes and spends $$$4$$$ minutes falling asleep. Thus, he rests for $$$2$$$ more minutes, totaling in $$$3+2=5$$$ minutes of sleep. Then he repeats the procedure three more times and ends up with $$$11$$$ minutes of sleep. Finally, he gets out of his bed. He spent $$$3$$$ minutes before the first alarm and then reset his alarm four times. The answer is $$$3+4 \\cdot 6 = 27$$$.The second example is almost like the first one but Polycarp needs $$$11$$$ minutes of sleep instead of $$$10$$$. However, that changes nothing because he gets $$$11$$$ minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $$$b=9$$$.In the fourth testcase Polycarp wakes up after $$$5$$$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :("}, "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"}, {"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}"}], "negative_code": [], "src_uid": "1ab174688ba76168ca047ed2b06b0670"} {"nl": {"description": "A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.", "input_spec": "The first input line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105;\u00a02\u2009\u2264\u2009k\u2009\u2264\u200926). The second line contains n uppercase English letters. Letter \"A\" stands for the first color, letter \"B\" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.", "output_spec": "Print a single integer \u2014 the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.", "sample_inputs": ["6 3\nABBACC", "3 2\nBBB"], "sample_outputs": ["2\nABCACA", "1\nBAB"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?", "input_spec": "The first line of the input contains three integers n, m and a (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105; 0\u2009\u2264\u2009a\u2009\u2264\u2009109). The second line contains the sequence of integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1,\u2009p2,\u2009...,\u2009pm (1\u2009\u2264\u2009pj\u2009\u2264\u2009109), where pj is the price for renting the j-th bike.", "output_spec": "Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r\u2009=\u2009s\u2009=\u20090.", "sample_inputs": ["2 2 10\n5 5\n7 6", "4 5 2\n8 1 1 2\n6 3 7 5 2"], "sample_outputs": ["2 3", "3 8"], "notes": "NoteIn the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money."}, "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"}, {"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"}], "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"} {"nl": {"description": "Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others \u2014 a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.", "input_spec": "The only line contains s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105) consisting of lowercase latin letters.", "output_spec": "Print \u00abYes\u00bb if the string can be split according to the criteria above or \u00abNo\u00bb otherwise. Each letter can be printed in arbitrary case.", "sample_inputs": ["ababa", "zzcxx", "yeee"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteIn sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.There's no suitable partition in sample case three."}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val s = readString()\n var f = new mutable.HashMap[Char, Int]()\n\n s.foreach(c => f.get(c) match {\n case Some(x) => f += c -> (x + 1)\n case None => f += c -> 1\n })\n\n if (f.size > 4 || f.size < 2) {\n print(\"No\")\n return\n }\n\n if (f.size == 4) {\n print(\"Yes\")\n return\n }\n\n if (f.size == 3)\n if (f.exists(p => p._2 > 1)) {\n print(\"Yes\")\n return\n } else {\n print(\"No\")\n return\n }\n\n if (f.size == 2)\n if (f.exists(p => p._2 < 2)) {\n print(\"No\")\n return\n } else {\n print(\"Yes\")\n return\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n /*val Array(hh, mm) = readInt()\n val Array(h, d, c, n) = readInt().map(_.toFloat)\n\n var price = 0.0\n if (hh >= 20) price = Math.ceil(h / n) * c * 0.8\n else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)\n\n print(\"%.4f\".format(price))*/\n\n val s = readString()\n val s1 = new mutable.HashSet[Char]()\n val s2 = new mutable.HashSet[Char]()\n val f1 = new Array[Int](s.length)\n val f2 = new Array[Int](s.length)\n\n for (i <- 0 until s.length) {\n s1 += s(i)\n f1(i) = s1.size\n }\n\n for (i <- s.length - 1 to 0 by -1) {\n s2 += s(i)\n f2(i) = s2.size\n }\n\n for (i <- 0 until s.length - 1)\n if (f1(i) == f2(i + 1) && f1(i) == 2) {\n print(\"Yes\")\n return\n }\n print(\"No\")\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n /*val Array(hh, mm) = readInt()\n val Array(h, d, c, n) = readInt().map(_.toFloat)\n\n var price = 0.0\n if (hh >= 20) price = Math.ceil(h / n) * c * 0.8\n else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)\n\n print(\"%.4f\".format(price))*/\n\n val s = readString()\n val s1 = new mutable.HashSet[Char]()\n val s2 = new mutable.HashSet[Char]()\n val f1 = new Array[Int](s.length)\n val f2 = new Array[Int](s.length)\n\n for (i <- 0 until s.length) {\n s1 += s(i)\n f1(i) = s1.size\n }\n\n for (i <- s.length - 1 to 0 by -1) {\n s2 += s(i)\n f2(i) = s2.size\n }\n\n for (i <- 0 until s.length)\n if (f1(i) == f2(i) && f1(i) == 2) {\n print(\"Yes\")\n return\n }\n print(\"No\")\n }\n}\n"}], "src_uid": "6190db9007f8f5eba095a6fcfc3652fc"} {"nl": {"description": "Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present \u2014 the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai\u2009\u2264\u2009d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d\u2009+\u20091, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.", "input_spec": "The first line contains the single number d \u2014 the maximum number of the day that Vasya's clock can show (1\u2009\u2264\u2009d\u2009\u2264\u2009106). The second line contains a single integer n \u2014 the number of months in the year (1\u2009\u2264\u2009n\u2009\u2264\u20092000). The third line contains n space-separated integers: ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009d) \u2014 the number of days in each month in the order in which they follow, starting from the first one. ", "output_spec": "Print a single number \u2014 the number of times Vasya manually increased the day number by one throughout the last year.", "sample_inputs": ["4\n2\n2 2", "5\n3\n3 4 3", "31\n12\n31 28 31 30 31 30 31 31 30 31 30 31"], "sample_outputs": ["2", "3", "7"], "notes": "NoteIn the first sample the situation is like this: Day 1. Month 1. The clock shows 1. Vasya changes nothing. Day 2. Month 1. The clock shows 2. Vasya changes nothing. Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. Day 2. Month 2. The clock shows 2. Vasya changes nothing. In total, Vasya manually changed the day number by 1 exactly 2 times."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad\u2014'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0,\u20091,\u20090,\u20091}, {1,\u20090,\u20091}, and {1,\u20090,\u20091,\u20090} are alternating sequences, while {1,\u20090,\u20090} and {0,\u20091,\u20090,\u20091,\u20091} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring\u2014that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.", "input_spec": "The first line contains the number of questions on the olympiad n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). The following line contains a binary string of length n representing Kevin's results on the USAICO. ", "output_spec": "Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.", "sample_inputs": ["8\n10000011", "2\n01"], "sample_outputs": ["5", "2"], "notes": "NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score."}, "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": "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"}, {"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"} {"nl": {"description": "Tavas is a strange creature. Usually \"zzz\" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x1\u2009<\u2009x2\u2009<\u2009...\u2009<\u2009xk where p matches s. More formally, for each xi (1\u2009\u2264\u2009i\u2009\u2264\u2009k) he condition sxisxi\u2009+\u20091... sxi\u2009+\u2009|p|\u2009-\u20091\u2009=\u2009p is fullfilled.Then Malekas wrote down one of subsequences of x1,\u2009x2,\u2009... xk (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.Answer can be very large, so Tavas wants you to print the answer modulo 109\u2009+\u20097.", "input_spec": "The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1\u2009\u2264\u2009n\u2009\u2264\u2009106 and 0\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009-\u2009|p|\u2009+\u20091). The second line contains string p (1\u2009\u2264\u2009|p|\u2009\u2264\u2009n). The next line contains m space separated integers y1,\u2009y2,\u2009...,\u2009ym, Malekas' subsequence (1\u2009\u2264\u2009y1\u2009<\u2009y2\u2009<\u2009...\u2009<\u2009ym\u2009\u2264\u2009n\u2009-\u2009|p|\u2009+\u20091).", "output_spec": "In a single line print the answer modulo 1000\u2009000\u2009007.", "sample_inputs": ["6 2\nioi\n1 3", "5 2\nioi\n1 2"], "sample_outputs": ["26", "0"], "notes": "NoteIn the first sample test all strings of form \"ioioi?\" where the question mark replaces arbitrary English letter satisfy.Here |x| denotes the length of string x.Please note that it's possible that there is no such string (answer is 0)."}, "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) = 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 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 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(p.length + 1)(0)\n var k = 0\n for (j <- 1 until p.length) {\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 }\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 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)+1s.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)+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 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"} {"nl": {"description": "\u041e\u0441\u043d\u043e\u0432\u043e\u0439 \u043b\u044e\u0431\u043e\u0439 \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0441\u0435\u0442\u0438 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043e\u0442\u043d\u043e\u0448\u0435\u043d\u0438\u0435 \u0434\u0440\u0443\u0436\u0431\u044b \u043c\u0435\u0436\u0434\u0443 \u0434\u0432\u0443\u043c\u044f \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f\u043c\u0438 \u0432 \u0442\u043e\u043c \u0438\u043b\u0438 \u0438\u043d\u043e\u043c \u0441\u043c\u044b\u0441\u043b\u0435. \u0412 \u043e\u0434\u043d\u043e\u0439 \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0439 \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0441\u0435\u0442\u0438 \u0434\u0440\u0443\u0436\u0431\u0430 \u0441\u0438\u043c\u043c\u0435\u0442\u0440\u0438\u0447\u043d\u0430, \u0442\u043e \u0435\u0441\u0442\u044c \u0435\u0441\u043b\u0438 a \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0434\u0440\u0443\u0433\u043e\u043c b, \u0442\u043e b \u0442\u0430\u043a\u0436\u0435 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0434\u0440\u0443\u0433\u043e\u043c a. \u0412 \u044d\u0442\u043e\u0439 \u0436\u0435 \u0441\u0435\u0442\u0438 \u0435\u0441\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0434\u0435\u043c\u043e\u043d\u0441\u0442\u0440\u0438\u0440\u0443\u0435\u0442 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u043b\u044e\u0434\u0435\u0439, \u0438\u043c\u0435\u044e\u0449\u0438\u0445 \u0432\u044b\u0441\u043e\u043a\u0443\u044e \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u044c \u0431\u044b\u0442\u044c \u0437\u043d\u0430\u043a\u043e\u043c\u044b\u043c\u0438 \u0434\u043b\u044f \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f. \u042d\u0442\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c. \u0417\u0430\u0444\u0438\u043a\u0441\u0438\u0440\u0443\u0435\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f x. \u041f\u0443\u0441\u0442\u044c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0434\u0440\u0443\u0433\u043e\u0439 \u0447\u0435\u043b\u043e\u0432\u0435\u043a y, \u043d\u0435 \u044f\u0432\u043b\u044f\u044e\u0449\u0438\u0439\u0441\u044f \u0434\u0440\u0443\u0433\u043e\u043c x \u043d\u0430 \u0442\u0435\u043a\u0443\u0449\u0438\u0439 \u043c\u043e\u043c\u0435\u043d\u0442, \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0434\u0440\u0443\u0433\u043e\u043c \u043d\u0435 \u043c\u0435\u043d\u0435\u0435, \u0447\u0435\u043c \u0434\u043b\u044f k% \u0434\u0440\u0443\u0437\u0435\u0439 x. \u0422\u043e\u0433\u0434\u0430 \u043e\u043d \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u043c\u044b\u043c \u0434\u0440\u0443\u0433\u043e\u043c \u0434\u043b\u044f x.\u0423 \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0447\u0435\u043b\u043e\u0432\u0435\u043a\u0430 \u0432 \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0441\u0435\u0442\u0438 \u0435\u0441\u0442\u044c \u0441\u0432\u043e\u0439 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u2014 \u044d\u0442\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u043e\u0442 1 \u0434\u043e 109. \u0412\u0430\u043c \u0434\u0430\u043d \u0441\u043f\u0438\u0441\u043e\u043a \u043f\u0430\u0440 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u0439, \u044f\u0432\u043b\u044f\u044e\u0449\u0438\u0445\u0441\u044f \u0434\u0440\u0443\u0437\u044c\u044f\u043c\u0438. \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435 \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0443\u043f\u043e\u043c\u044f\u043d\u0443\u0442\u043e\u0433\u043e \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0435\u0433\u043e \u043f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u043c\u044b\u0445 \u0434\u0440\u0443\u0437\u0435\u0439.", "input_spec": "\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043b\u0435\u0434\u0443\u044e\u0442 \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 m \u0438 k (1\u2009\u2264\u2009m\u2009\u2264\u2009100, 0\u2009\u2264\u2009k\u2009\u2264\u2009100) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0440 \u0434\u0440\u0443\u0437\u0435\u0439 \u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u044b\u0439 \u043f\u0440\u043e\u0446\u0435\u043d\u0442 \u043e\u0431\u0449\u0438\u0445 \u0434\u0440\u0443\u0437\u0435\u0439 \u0434\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u0441\u0447\u0438\u0442\u0430\u0442\u044c\u0441\u044f \u043f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u043c\u044b\u043c \u0434\u0440\u0443\u0433\u043e\u043c. \u0412 \u043f\u043e\u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 m \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u043f\u043e \u0434\u0432\u0430 \u0447\u0438\u0441\u043b\u0430 ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009109, ai\u2009\u2260\u2009bi), \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u044e\u0449\u0438\u0445 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u0439, \u044f\u0432\u043b\u044f\u044e\u0449\u0438\u0445\u0441\u044f \u0434\u0440\u0443\u0437\u044c\u044f\u043c\u0438. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043a\u0430\u0436\u0434\u0430\u044f \u043f\u0430\u0440\u0430 \u043b\u044e\u0434\u0435\u0439 \u0444\u0438\u0433\u0443\u0440\u0438\u0440\u0443\u0435\u0442 \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u043e\u0434\u043d\u043e\u0433\u043e \u0440\u0430\u0437\u0430.", "output_spec": "\u0414\u043b\u044f \u0432\u0441\u0435\u0445 \u0443\u043f\u043e\u043c\u044f\u043d\u0443\u0442\u044b\u0445 \u043b\u044e\u0434\u0435\u0439 \u0432 \u043f\u043e\u0440\u044f\u0434\u043a\u0435 \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430\u043d\u0438\u044f id \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u043e \u043f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u043c\u044b\u0445 \u0434\u0440\u0443\u0437\u044c\u044f\u0445. \u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u0434\u043e\u043b\u0436\u043d\u0430 \u0438\u043c\u0435\u0442\u044c \u0432\u0438\u0434 \"id:\u2009\u00a0k\u00a0id1\u00a0id2\u00a0...\u00a0idk\", \u0433\u0434\u0435 id \u2014 \u044d\u0442\u043e id \u0441\u0430\u043c\u043e\u0433\u043e \u0447\u0435\u043b\u043e\u0432\u0435\u043a\u0430, k \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0435\u0433\u043e \u043f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u043c\u044b\u0445 \u0434\u0440\u0443\u0437\u0435\u0439, \u0430 id1, id2, ..., idk \u2014 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u0435\u0433\u043e \u043f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u043c\u044b\u0445 \u0434\u0440\u0443\u0437\u0435\u0439 \u0432 \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430\u044e\u0449\u0435\u043c \u043f\u043e\u0440\u044f\u0434\u043a\u0435. ", "sample_inputs": ["5 51\n10 23\n23 42\n39 42\n10 39\n39 58", "5 100\n1 2\n1 3\n1 4\n2 3\n2 4"], "sample_outputs": ["10: 1 42\n23: 1 39\n39: 1 23\n42: 1 10\n58: 2 10 42", "1: 0\n2: 0\n3: 1 4\n4: 1 3"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi \u2014 the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.", "output_spec": "Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.", "sample_inputs": ["4\n2 3 4 1", "3\n1 3 2", "2\n1 2"], "sample_outputs": ["4 1 2 3", "1 3 2", "1 2"], "notes": null}, "positive_code": [{"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}"}, {"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": "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}"}, {"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"}], "negative_code": [], "src_uid": "48bb148e2c4d003cad9d57e7b1ab78fb"} {"nl": {"description": "Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.In return, the fleas made a bigger ukulele for her: it has $$$n$$$ strings, and each string has $$$(10^{18} + 1)$$$ frets numerated from $$$0$$$ to $$$10^{18}$$$. The fleas use the array $$$s_1, s_2, \\ldots, s_n$$$ to describe the ukulele's tuning, that is, the pitch of the $$$j$$$-th fret on the $$$i$$$-th string is the integer $$$s_i + j$$$.Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.Each question is in the form of: \"How many different pitches are there, if we consider frets between $$$l$$$ and $$$r$$$ (inclusive) on all strings?\"Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!Formally, you are given a matrix with $$$n$$$ rows and $$$(10^{18}+1)$$$ columns, where the cell in the $$$i$$$-th row and $$$j$$$-th column ($$$0 \\le j \\le 10^{18}$$$) contains the integer $$$s_i + j$$$. You are to answer $$$q$$$ queries, in the $$$k$$$-th query you have to answer the number of distinct integers in the matrix from the $$$l_k$$$-th to the $$$r_k$$$-th columns, inclusive.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\leq n \\leq 100\\,000$$$)\u00a0\u2014 the number of strings. The second line contains $$$n$$$ integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$0 \\leq s_i \\leq 10^{18}$$$)\u00a0\u2014 the tuning of the ukulele. The third line contains an integer $$$q$$$ ($$$1 \\leq q \\leq 100\\,000$$$)\u00a0\u2014 the number of questions. The $$$k$$$-th among the following $$$q$$$ lines contains two integers $$$l_k$$$\uff0c$$$r_k$$$ ($$$0 \\leq l_k \\leq r_k \\leq 10^{18}$$$)\u00a0\u2014 a question from the fleas.", "output_spec": "Output one number for each question, separated by spaces\u00a0\u2014 the number of different pitches.", "sample_inputs": ["6\n3 1 4 1 5 9\n3\n7 7\n0 2\n8 17", "2\n1 500000000000000000\n2\n1000000000000000000 1000000000000000000\n0 1000000000000000000"], "sample_outputs": ["5 10 18", "2 1500000000000000000"], "notes": "NoteFor the first example, the pitches on the $$$6$$$ strings are as follows.$$$$$$ \\begin{matrix} \\textbf{Fret} & \\textbf{0} & \\textbf{1} & \\textbf{2} & \\textbf{3} & \\textbf{4} & \\textbf{5} & \\textbf{6} & \\textbf{7} & \\ldots \\\\ s_1: & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & \\dots \\\\ s_2: & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & \\dots \\\\ s_3: & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & \\dots \\\\ s_4: & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & \\dots \\\\ s_5: & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & \\dots \\\\ s_6: & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & \\dots \\end{matrix} $$$$$$There are $$$5$$$ different pitches on fret $$$7$$$\u00a0\u2014 $$$8, 10, 11, 12, 16$$$.There are $$$10$$$ different pitches on frets $$$0, 1, 2$$$\u00a0\u2014 $$$1, 2, 3, 4, 5, 6, 7, 9, 10, 11$$$."}, "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 S = nal(N)\n sort(S)\n debug(\"S\")\n debug(S)\n val D = Array.ofDim[Long](N - 1)\n REP(N - 1) { i =>\n D(i) = max(0, S(i + 1) - S(i) - 1)\n }\n sort(D)\n val cum = cumSum(D)\n debug(\"D\")\n debug(D)\n debug(cum)\n\n val distinct = S.distinct.length\n\n val ans = ArrayBuffer[Long]()\n REP(ni()) { _ =>\n val l, r = nl()\n val d = r - l\n val cntL = lowerBound(D, d)\n debug(s\"cntL:$cntL\")\n ans += cum(cntL) + (r - l) * (N - cntL) + distinct\n }\n\n out.println(ans.mkString(\" \"))\n }\n\n def sort(a: Array[Long]): Array[Long] = {\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 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 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[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"}], "negative_code": [], "src_uid": "536a582f3620a733d09cf80662488590"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations with it: Choose some positions $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n, i \\ne j$$$), write the value of $$$a_i \\cdot a_j$$$ into the $$$j$$$-th cell and remove the number from the $$$i$$$-th cell; Choose some position $$$i$$$ and remove the number from the $$$i$$$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly $$$n - 1$$$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$) \u2014 the elements of the array.", "output_spec": "Print $$$n - 1$$$ lines. The $$$k$$$-th line should contain one of the two possible operations. The operation of the first type should look like this: $$$1~ i_k~ j_k$$$, where $$$1$$$ is the type of operation, $$$i_k$$$ and $$$j_k$$$ are the positions of the chosen elements. The operation of the second type should look like this: $$$2~ i_k$$$, where $$$2$$$ is the type of operation, $$$i_k$$$ is the position of the chosen element. Note that there should be no more than one such operation. If there are multiple possible sequences of operations leading to the maximum number \u2014 print any of them.", "sample_inputs": ["5\n5 -2 0 1 -3", "5\n5 2 0 4 0", "2\n2 -1", "4\n0 -10 0 0", "4\n0 0 0 0"], "sample_outputs": ["2 3\n1 1 2\n1 2 4\n1 4 5", "1 3 5\n2 5\n1 1 2\n1 2 4", "2 2", "1 1 2\n1 2 3\n1 3 4", "1 1 2\n1 2 3\n1 3 4"], "notes": "NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: $$$[5, -2, 0, 1, -3] \\to [5, -2, X, 1, -3] \\to [X, -10, X, 1, -3] \\to$$$ $$$[X, X, X, -10, -3] \\to [X, X, X, X, 30]$$$. Thus, the maximum answer is $$$30$$$. Note, that other sequences that lead to the answer $$$30$$$ are also correct.The second example has, for example, the following sequence of transformations of the array: $$$[5, 2, 0, 4, 0] \\to [5, 2, X, 4, 0] \\to [5, 2, X, 4, X] \\to [X, 10, X, 4, X] \\to$$$ $$$[X, X, X, 40, X]$$$. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: $$$[5, 2, 0, 4, 0] \\to [5, 2, 0, 4, X] \\to [5, 8, 0, X, X] \\to [40, X, 0, X, X] \\to$$$ $$$[40, X, X, X, X]$$$.The third example can have the following sequence of transformations of the array: $$$[2, -1] \\to [2, X]$$$.The fourth example can have the following sequence of transformations of the array: $$$[0, -10, 0, 0] \\to [X, 0, 0, 0] \\to [X, X, 0, 0] \\to [X, X, X, 0]$$$.The fifth example can have the following sequence of transformations of the array: $$$[0, 0, 0, 0] \\to [X, 0, 0, 0] \\to [X, X, 0, 0] \\to [X, X, X, 0]$$$."}, "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 cntNeg = A count(_ < 0)\n val cntZero = A count(_ == 0)\n\n val mulVs = ArrayBuffer[Int]()\n val mulDels = ArrayBuffer[Int]()\n\n if (cntZero == N || cntNeg == 1 && cntZero == N - 1) {\n rep(N, 1) { i =>\n mulVs += i\n }\n } else if (cntNeg == 1 && cntZero == N - 1) {\n// val neg = A indexWhere (_ < 0)\n// rep(N - 1, 1) { i =>\n// if (i != neg) mulVs += (i , i + 1)\n// else mulDels += i + 1\n// }\n } else {\n\n val delNeg = if (cntNeg % 2 == 0) -1\n else {\n var mxNeg = Integer.MIN_VALUE\n rep(N) { i =>\n if (A(i) < 0) mxNeg = max(mxNeg, A(i))\n }\n A.indexWhere(_ == mxNeg)\n }\n rep(N) { i =>\n if (i == delNeg || A(i) == 0) mulDels += i + 1\n else mulVs += i + 1\n }\n }\n\n val dels = ArrayBuffer[Int]()\n val muls = ArrayBuffer[(Int, Int)]()\n rep(mulVs.length - 1) { i =>\n muls += ((mulVs(i), mulVs(i + 1)))\n }\n\n if (mulDels.nonEmpty) {\n rep(mulDels.length - 1) { i =>\n muls += ((mulDels(i), mulDels(i + 1)))\n }\n dels += mulDels.last\n }\n\n muls foreach { case (i, j) =>\n out.println(s\"1 $i $j\")\n }\n\n dels foreach { i =>\n out.println(s\"2 $i\")\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 = ni()\n val A = na(N)\n\n val cntNeg = A count(_ < 0)\n val cntZero = A count(_ == 0)\n\n val dels = ArrayBuffer[Int]()\n val muls = ArrayBuffer[(Int, Int)]()\n if (cntZero == N) {\n rep(N - 1, 1) { i =>\n dels += i + 1\n }\n } else if (cntNeg == 1 && cntZero == N - 1) {\n val last = A.indexWhere(_ == 0)\n rep(N) { i =>\n if (i != last) dels += i + 1\n }\n } else {\n val delNeg = if (cntNeg % 2 == 0) -1\n else {\n var mxNeg = Integer.MIN_VALUE\n rep(N) { i =>\n if (A(i) < 0) mxNeg = max(mxNeg, A(i))\n }\n A.indexWhere(_ == mxNeg)\n }\n val mulVs = ArrayBuffer[Int]()\n rep(N) { i =>\n if (i == delNeg || A(i) == 0) dels += i + 1\n else mulVs += i + 1\n }\n rep(mulVs.length - 1) { i =>\n muls += ((mulVs(i), mulVs(i + 1)))\n }\n }\n\n dels foreach { i =>\n out.println(s\"2 $i\")\n }\n\n muls foreach { case (i, j) =>\n out.println(s\"1 $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): 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 = na(N)\n\n val cntNeg = A count(_ < 0)\n val cntZero = A count(_ == 0)\n\n val dels = ArrayBuffer[Int]()\n val muls = ArrayBuffer[(Int, Int)]()\n if (cntZero == N) {\n rep(N - 1, 1) { i =>\n dels += i + 1\n }\n } else if (cntNeg == 1 && cntZero == N - 1) {\n val last = A.indexWhere(_ == 0)\n rep(N) { i =>\n if (i != last) dels += i + 1\n }\n } else {\n val delNeg = if (cntNeg % 2 == 1) A.indexWhere(_ < 0) else -1\n val mulVs = ArrayBuffer[Int]()\n rep(N) { i =>\n if (i == delNeg || A(i) == 0) dels += i + 1\n else mulVs += i + 1\n }\n rep(mulVs.length - 1) { i =>\n muls += ((mulVs(i), mulVs(i + 1)))\n }\n }\n\n dels foreach { i =>\n out.println(s\"2 $i\")\n }\n\n muls foreach { case (i, j) =>\n out.println(s\"1 $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): 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": "f09b435a20a415d65803a80d57152832"} {"nl": {"description": "You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other. The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \\le a \\le r_1$$$, $$$l_2 \\le b \\le r_2$$$ and $$$a \\ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 500$$$) \u2014 the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \\le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \\le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) \u2014 the ends of the segments in the $$$i$$$-th query.", "output_spec": "Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ \u2014 such numbers that $$$l_{1_i} \\le a_i \\le r_{1_i}$$$, $$$l_{2_i} \\le b_i \\le r_{2_i}$$$ and $$$a_i \\ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.", "sample_inputs": ["5\n1 2 1 2\n2 6 3 4\n2 4 1 3\n1 2 1 3\n1 4 5 8"], "sample_outputs": ["2 1\n3 4\n3 2\n1 2\n3 7"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.", "input_spec": "The first line contains one even integer $$$n$$$ $$$(2 \\le n \\le 2 \\cdot 10^{5})$$$ \u2014 the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and \"?\" characters \u2014 the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is \"?\", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of \"?\" characters is even.", "output_spec": "If Monocarp wins, print \"Monocarp\" (without quotes). Otherwise print \"Bicarp\" (without quotes).", "sample_inputs": ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"], "sample_outputs": ["Bicarp", "Bicarp", "Bicarp", "Monocarp"], "notes": "NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy."}, "positive_code": [{"source_code": "\nobject Main extends App {\n import scala.io.StdIn._\n val n = readInt()\n val str = readLine.trim\n val left = str.take(n / 2)\n val right = str.drop(n / 2)\n val leftSum = left.map(c \u21d2 if (c.isDigit) c.asDigit else 0).sum\n val rightSum = right.map(c \u21d2 if (c.isDigit) c.asDigit else 0).sum\n val leftFree = left.count(_ == '?')\n val rightFree = right.count(_ == '?')\n if (leftSum < rightSum) {\n val diff = rightSum - leftSum\n val freeDiff = (leftFree - rightFree) / 2\n if (freeDiff >= 0 && diff == freeDiff * 9) {\n println(\"Bicarp\")\n }else {\n println(\"Monocarp\")\n }\n }else {\n val diff = leftSum - rightSum\n val freeDiff = (rightFree - leftFree) / 2\n if (freeDiff >= 0 && diff == freeDiff * 9) {\n println(\"Bicarp\")\n }else {\n println(\"Monocarp\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "028882706ed58b61b4672fc3e76852c4"} {"nl": {"description": "The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \\le l_i \\le r_i \\le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.", "input_spec": "The first line contains two space-separated integers $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) and $$$q$$$ ($$$1 \\le q \\le 2\\cdot10^5$$$) \u2014 the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \\le a_i \\le 2\\cdot10^5$$$) \u2014 the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) \u2014 the $$$i$$$-th query.", "output_spec": "In a single line print, a single integer \u2014 the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3 3\n5 3 2\n1 2\n2 3\n1 3", "5 3\n5 2 4 1 3\n1 5\n2 3\n2 3"], "sample_outputs": ["25", "33"], "notes": null}, "positive_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[Long](0)((r: Long, t) => r + t._1.toLong * 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[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"}, {"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"}], "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"} {"nl": {"description": "In a strategic computer game \"Settlers II\" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank \u2014 some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1\u2009\u2264\u2009i\u2009\u2264\u2009n, 1\u2009\u2264\u2009ai\u2009\u2264\u2009k).", "output_spec": "Print a single integer \u2014 the number of golden coins needed to raise all the soldiers to the maximal rank.", "sample_inputs": ["4 4\n1 2 2 3", "4 3\n1 1 1 1"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 \u2009\u2192\u2009 2 2 3 4 \u2009\u2192\u2009 2 3 4 4 \u2009\u2192\u2009 3 4 4 4 \u2009\u2192\u2009 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins."}, "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 answer = Array.ofDim[Int](k)\n in.next().split(' ').map(_.toInt - 1).foreach {i => answer(i) += 1}\n var r = 0\n\n while (answer(k - 1) != n) {\n (k - 1 to 1 by - 1).foreach { i =>\n if (answer(i - 1) > 0) {\n answer(i) += 1\n answer(i - 1) -= 1\n }\n }\n r += 1\n }\n println(r)\n}"}], "negative_code": [], "src_uid": "3d6411d67c85f6293f1999ccff2cd8ba"} {"nl": {"description": "Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9, a_i \\ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$.", "sample_inputs": ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"], "sample_outputs": ["2\n-1\n6\n-2999999997"], "notes": "NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \\underline{3}, \\underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \\underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\\underline{-2}, 8, 3, \\underline{8}, \\underline{-4}, -15, \\underline{5}, \\underline{-2}, -3, \\underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\\underline{1}, \\underline{-1000000000}, \\underline{1}, \\underline{-1000000000}, \\underline{1}, \\underline{-1000000000}]$$$."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "39480cdf697fc9743dc9665f989077d7"} {"nl": {"description": "Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x\u2009>\u20091, such that n is divisible by x and replacing n with n\u2009/\u2009x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a!\u2009/\u2009b! for some positive integer a and b (a\u2009\u2265\u2009b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?", "input_spec": "First line of input consists of single integer t (1\u2009\u2264\u2009t\u2009\u2264\u20091\u2009000\u2009000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1\u2009\u2264\u2009b\u2009\u2264\u2009a\u2009\u2264\u20095\u2009000\u2009000) defining the value of n for a game.", "output_spec": "For each game output a maximum score that the second soldier can get.", "sample_inputs": ["2\n3 1\n6 3"], "sample_outputs": ["2\n5"], "notes": null}, "positive_code": [{"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 t=nextInt\n val nmax=5000002\n\n val prime=Array.fill(nmax)(true)\n for(i<-2 until 2333){\n if(prime(i)){\n for(j<-i to (nmax-1)/i){\n prime(j*i)=false\n }\n }\n }\n\n for(i<-2 until nmax){\n if(prime(i)){\n var j=i\n while(j 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3055\u308c\u308b\u5074\u304b\u3089\u306e\u6709\u5411\u30b0\u30e9\u30d5\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3055\u308c\u308b\u5074\u304b\u3089\u306e\u6709\u5411\u30b0\u30e9\u30d5\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3055\u308c\u308b\u5074\u304b\u3089\u306e\u6709\u5411\u30b0\u30e9\u30d5\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\u5bfe\u7b56\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"} {"nl": {"description": "Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0,\u20091}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: where is equal to 1 if some ai\u2009=\u20091, otherwise it is equal to 0.Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1\u2009\u2264\u2009i\u2009\u2264\u2009m) and column j (1\u2009\u2264\u2009j\u2009\u2264\u2009n) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:.(Bij is OR of all elements in row i and column j of matrix A)Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.", "input_spec": "The first line contains two integer m and n (1\u2009\u2264\u2009m,\u2009n\u2009\u2264\u2009100), number of rows and number of columns of matrices respectively. The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).", "output_spec": "In the first line, print \"NO\" if Nam has made a mistake when calculating B, otherwise print \"YES\". If the first line is \"YES\", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.", "sample_inputs": ["2 2\n1 0\n0 0", "2 3\n1 1 1\n1 1 1", "2 3\n0 1 0\n1 1 1"], "sample_outputs": ["NO", "YES\n1 1 1\n1 1 1", "YES\n0 0 0\n0 1 0"], "notes": null}, "positive_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 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"}, {"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 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}"}], "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"} {"nl": {"description": "Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows.A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a basic polygon. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the basic polygon. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer?During the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the basic polygon. Let's assume that there are k versions of the polygons. Then the Randomizer chooses each of them with probability .", "input_spec": "The first line of the input contains a single integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the number of vertices of the basic polygon. Next n lines contain the coordinates of the vertices of the basic polygon. The i-th of these lines contain two integers xi and yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109) \u2014 the coordinates of the i-th vertex of the polygon. The vertices are given in the counter-clockwise order.", "output_spec": "Print the sought expected value with absolute or relative error at most 10\u2009-\u20099.", "sample_inputs": ["4\n0 0\n2 0\n2 2\n0 2", "5\n0 0\n2 0\n2 2\n1 3\n0 2"], "sample_outputs": ["0.2", "0.8125"], "notes": "NoteA polygon is called strictly convex if it is convex and no its vertices lie on the same line.Let's assume that a random variable takes values x1,\u2009...,\u2009xn with probabilities p1,\u2009...,\u2009pn, correspondingly. Then the expected value of this variable equals to ."}, "positive_code": [{"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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n val xD=Array.ofDim[Double](n)\n val yD=Array.ofDim[Double](n)\n val po=for(i<-0 until n+1) yield pow(2,-i)\n for(i<- 0 until n){\n x(i)=nextInt\n y(i)=nextInt\n \n }\n for(i<-0 until n){\n xD(i)=x(i)\n yD(i)=y(i)\n }\n var A=0.0\n var b=0.0\n \n val p0:Double=(1-(1+n*(n+1)/2)*pow(2,-n))\n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(po(k+1)-po(n))/p0\n val j=(i+k)%n\n A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=abs(A)-b/2+1\n \n out.println(\"%10.9f\".format(ans))\n \n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n val xD=Array.ofDim[Double](n)\n val yD=Array.ofDim[Double](n)\n for(i<- 0 until n){\n x(i)=nextInt\n y(i)=nextInt\n \n }\n for(i<-0 until n){\n xD(i)=x(i)\n yD(i)=y(i)\n }\n var A=0.0\n var b=0.0\n if(n==100000){\n return\n }else{\n \n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))\n val j=(i+k)%n\n A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=abs(A)-b/2+1\n \n out.println(\"%10.9f\".format(ans))\n }\n //code ends here\n out.flush\n out.close\n }\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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n val xD=Array.ofDim[Double](n)\n val yD=Array.ofDim[Double](n)\n val timeStart=java.lang.System.currentTimeMillis()\n for(i<- 0 until n){\n x(i)=nextInt\n y(i)=nextInt\n \n }\n for(i<-0 until n){\n xD(i)=x(i)\n yD(i)=y(i)\n }\n var A=0.0\n var b=0.0\n if(n==100000){\n out.println(java.lang.System.currentTimeMillis()-timeStart)\n return\n }else{\n \n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))\n val j=(i+k)%n\n A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=abs(A)-b/2+1\n \n out.println(\"%10.9f\".format(ans))\n }\n //code ends here\n out.flush\n out.close\n }\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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n val xD=Array.ofDim[Double](n)\n val yD=Array.ofDim[Double](n)\n val timeStart=java.lang.System.currentTimeMillis()\n for(i<- 0 until n){\n x(i)=nextInt\n y(i)=nextInt\n \n }\n for(i<-0 until n){\n xD(i)=x(i)\n yD(i)=y(i)\n }\n var A=0.0\n var b=0.0\n if(n==100000){\n out.println(java.lang.System.currentTimeMillis()-timeStart)\n \n }else{\n \n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))\n val j=(i+k)%n\n A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=abs(A)-b/2+1\n \n out.println(\"%10.9f\".format(ans))\n }\n //code ends here\n out.flush\n out.close\n }\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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n val xD=Array.ofDim[Double](n)\n val yD=Array.ofDim[Double](n)\n for(i<- 0 until n){\n x(i)=nextInt\n y(i)=nextInt\n \n }\n var A=0.0\n var b=0.0\n if(n==100000){\n return\n }else{\n for(i<-0 until n){\n xD(i)=x(i)\n yD(i)=y(i)\n }\n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))\n val j=(i+k)%n\n A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=abs(A)-b/2+1\n \n out.println(\"%10.9f\".format(ans))\n }\n //code ends here\n out.flush\n out.close\n }\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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n val xD=Array.ofDim[Double](n)\n val yD=Array.ofDim[Double](n)\n val timeStart=java.lang.System.currentTimeMillis()\n for(i<- 0 until n){\n x(i)=nextInt\n y(i)=nextInt\n \n }\n for(i<-0 until n){\n xD(i)=x(i)\n yD(i)=y(i)\n }\n var A=0.0\n var b=0.0\n if(n==100000){\n \n \n }else{\n val p0:Double=(1-(1+n*(n+1)/2)*pow(2,-n))\n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(pow(2,-k-1)-pow(2,-n))/p0\n val j=(i+k)%n\n A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=abs(A)-b/2+1\n \n out.println(\"%10.9f\".format(ans))\n }\n //code ends here\n out.flush\n out.close\n }\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 import math.{pow,abs,min}\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 gcd(a:Int,b:Int):Int={\n if(b==0||a==0){\n a+b\n }else{\n gcd(b,a%b)\n }\n }\n val n=nextInt\n val x=Array.ofDim[Int](n)\n val y=Array.ofDim[Int](n)\n for(i<- 0 until n){\n x(i)=nextInt;\n y(i)=nextInt;\n }\n var A=0.0\n var b=0.0\n for(i<-0 until n;k<-1 until min(61,n)){\n val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))\n val j=(i+k)%n\n A+=p*(x(i)*y(j)-x(j)*y(i))/2\n b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))\n }\n val ans=A-b/2+1\n\n out.println(\"%10.9f\".format(ans))\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "26506591fc15f23b0436473cd2712166"} {"nl": {"description": "This problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $$$s$$$ of length $$$n$$$, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of $$$s[l..r]$$$. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than $$$3$$$ queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed $$$\\left\\lceil 0.777(n+1)^2 \\right\\rceil$$$ ($$$\\lceil x \\rceil$$$ is $$$x$$$ rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.", "input_spec": "First line contains number $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the length of the picked string.", "output_spec": null, "sample_inputs": ["4\n\na\naa\na\n\ncb\nb\nc\n\nc"], "sample_outputs": ["? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\nimport scala.collection.mutable.StringBuilder\n\nobject Main {\n\n def query(n: Int) = {\n println(f\"? 1 $n\"); Console.flush\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim.sorted)\n }\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) {\n s(0)\n } else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB.tail)\n }\n }\n\n def hackPart(n: Int): String = {\n val ssButOne = collection.mutable.Map[String, Int]()\n\n query(n).foreach(s => {\n ssButOne(s) = ssButOne.getOrElse(s, 0) + 1\n })\n\n query(n - 1).foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n ssButOne.keySet.toList\n .sortBy(_.length)\n .foldLeft(List[Char]())((z, s) => extraChar(z, s) :: z)\n .mkString\n }\n\n def genWeight(arr: Array[Int], i: Int): List[Array[Int]] = {\n if (i == arr.length - 1) List()\n else {\n val nArr =\n arr.zipWithIndex.map({ case (x, j) => if (j > i) x + 1 else x })\n nArr :: genWeight(nArr, i + 1)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n\n if (n < 2) {\n val c = query(1).head\n println(f\"! $c\")\n\n } else if (n <= 4) {\n val substrs = hackPart(n)\n println(f\"! $substrs\")\n\n } else {\n\n val half = hackPart((n + 1) / 2)\n\n /* println(half) */\n\n val allSubstrs = query(n)\n val allLetters = allSubstrs.filter(_.length == n)(0)\n val substrs = allSubstrs\n .filter(x => x.length <= (n + 1) / 2 && x.length > 1)\n\n val freqLeft = (1 to (n - 1) / 2)\n .zip(genWeight(Array.fill((n + 1) / 2) { 1 }, 0))\n .map {\n case (i, weights) => {\n val cFreq = Array.fill(26) { 0 }\n\n substrs\n .filter(_.length == i + 1)\n .foreach(x => x.foreach(c => cFreq(c - 97) += 1))\n\n /* cFreq.foreach(x => if (x > 0) print(x + \"\\t\"))\n println() */\n\n half.zip(weights).foreach {\n case (c, w) => {\n /* print(f\"($c: $w) \") */\n cFreq(c - 97) -= w\n }\n }\n /* println */\n\n cFreq\n }\n }\n\n /* freqLeft.foreach(arr => {\n arr.zipWithIndex.foreach(x =>\n if (x._1 > 0) print(f\"(${(x._2 + 97).toChar}: ${x._1})\\t\")\n )\n println\n }) */\n\n val accumFreq = Array.fill(26) { 0 }\n var lastHalf = \"\"\n\n val x = (2 to (n + 1) / 2).zip(freqLeft).foreach {\n case (i, x) => {\n for (j <- 0 until 26) x(j) -= accumFreq(j)\n x.zipWithIndex.foreach(pair =>\n if (pair._1 % i != 0 && (pair._1 - i + 1) % i == 0) {\n lastHalf = (pair._2 + 97).toChar + lastHalf\n accumFreq(pair._2) += i - 1\n }\n )\n }\n }\n\n /* println(lastHalf) */\n\n var middle = \"\"\n if (half.length + lastHalf.length < n)\n middle = extraChar((half + lastHalf).toList, allLetters).toString\n\n println(f\"! ${half ++ middle ++ lastHalf}\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\n\nobject Main extends App {\n val n = readInt()\n\n if (n < 2) {\n println(\"? 1 1\"); Console.flush\n val c = readLine.trim.head\n println(f\"! $c\")\n\n } else {\n\n println(f\"? 1 $n\"); Console.flush\n val ssButOne = collection.mutable.Map[String, Int]()\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim.sorted)\n .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)\n\n println(f\"? 1 ${n - 1}\"); Console.flush\n (1 to (n * (n - 1) / 2))\n .map(_ => readLine.trim.sorted)\n .foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n val remains = ssButOne.keySet.toList.sortBy(_.length)\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) {\n s(0)\n } else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB.tail)\n }\n }\n\n val hack = remains\n .foldLeft(List[Char]())((z, s) => {\n extraChar(z, s) :: z\n })\n .mkString\n println(f\"! $hack\")\n }\n}\n\n/* aabc */\n/*\nxyz\nyz\nxy\nz\nx\ny\nzy\nz\ny\n */\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\nimport scala.collection.mutable.StringBuilder\n\nobject Main {\n\n def query(n: Int) = {\n println(f\"? 1 $n\"); Console.flush\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim.sorted)\n }\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) {\n s(0)\n } else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB.tail)\n }\n }\n\n def hackPart(n: Int): String = {\n val ssButOne = collection.mutable.Map[String, Int]()\n\n query(n).foreach(s => {\n ssButOne(s) = ssButOne.getOrElse(s, 0) + 1\n })\n\n query(n - 1).foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n ssButOne.keySet.toList\n .sortBy(_.length)\n .foldLeft(List[Char]())((z, s) => extraChar(z, s) :: z)\n .mkString\n }\n\n def genWeight(arr: Array[Int], i: Int): List[Array[Int]] = {\n if (i == arr.length - 1) List()\n else {\n val nArr =\n arr.zipWithIndex.map({ case (x, j) => if (j > i) x + 1 else x })\n nArr :: genWeight(nArr, i + 1)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n\n if (n < 2) {\n val c = query(1).head\n println(f\"! $c\")\n\n } else {\n\n val half = hackPart((n + 1) / 2)\n\n /* println(half) */\n\n val allSubstrs = query(n)\n val allLetters = allSubstrs.filter(_.length == n)(0)\n val substrs = allSubstrs\n .filter(x => x.length <= (n + 1) / 2 && x.length > 1)\n\n val freqLeft = (1 to (n - 1) / 2)\n .zip(genWeight(Array.fill((n + 1) / 2) { 1 }, 0))\n .map {\n case (i, weights) => {\n val cFreq = Array.fill(26) { 0 }\n\n substrs\n .filter(_.length == i + 1)\n .foreach(x => x.foreach(c => cFreq(c - 97) += 1))\n\n /* cFreq.foreach(x => if (x > 0) print(x + \"\\t\"))\n println() */\n\n half.zip(weights).foreach {\n case (c, w) => {\n /* print(f\"($c: $w) \") */\n cFreq(c - 97) -= w\n }\n }\n /* println */\n\n cFreq\n }\n }\n\n /* freqLeft.foreach(arr => {\n arr.zipWithIndex.foreach(x =>\n if (x._1 > 0) print(f\"(${(x._2 + 97).toChar}: ${x._1})\\t\")\n )\n println\n }) */\n\n val accumFreq = Array.fill(26) { 0 }\n var lastHalf = \"\"\n\n val x = (2 to (n + 1) / 2).zip(freqLeft).foreach {\n case (i, x) => {\n for (j <- 0 until 26) x(j) -= accumFreq(j)\n x.zipWithIndex.foreach(pair =>\n if (pair._1 % i != 0 && (pair._1 - i + 1) % i == 0) {\n lastHalf = (pair._2 + 97).toChar + lastHalf\n accumFreq(pair._2) += i - 1\n }\n )\n }\n }\n\n /* println(lastHalf) */\n\n var middle = \"\"\n if (half.length + lastHalf.length < n)\n middle = extraChar((half + lastHalf).toList, allLetters).toString\n\n println(f\"! ${half ++ middle ++ lastHalf}\")\n }\n }\n}\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\nimport scala.collection.mutable.StringBuilder\n\nobject Main {\n\n def query(n: Int) = {\n println(f\"? 1 $n\"); Console.flush\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim.sorted)\n }\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) {\n s(0)\n } else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB.tail)\n }\n }\n\n def hackPart(n: Int): String = {\n val ssButOne = collection.mutable.Map[String, Int]()\n\n query(n).foreach(s => {\n ssButOne(s) = ssButOne.getOrElse(s, 0) + 1\n })\n\n query(n - 1).foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n ssButOne.keySet.toList\n .sortBy(_.length)\n .foldLeft(List[Char]())((z, s) => extraChar(z, s) :: z)\n .mkString\n }\n\n def genWeight(arr: Array[Int], i: Int): List[Array[Int]] = {\n if (i == arr.length - 1) List()\n else {\n val nArr =\n arr.zipWithIndex.map({ case (x, j) => if (j > i) x + 1 else x })\n nArr :: genWeight(nArr, i + 1)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n\n if (n < 2) {\n val c = query(1).head\n println(f\"! $c\")\n\n } else {\n\n val half = hackPart((n + 1) / 2)\n val substrs = query(n)\n .filter(x => x.length <= (n + 1) / 2 && x.length > 1)\n\n val freqLeft = (1 to (n - 1) / 2)\n .zip(genWeight(Array.fill((n + 1) / 2) { 1 }, 0))\n .map {\n case (i, weights) => {\n val cFreq = Array.fill(26) { 0 }\n\n substrs\n .filter(_.length == i + 1)\n .foreach(x => x.foreach(c => cFreq(c - 97) += 1))\n\n /* cFreq.foreach(x => if (x > 0) print(x + \"\\t\"))\n println() */\n\n half.zip(weights).foreach {\n case (c, w) => {\n /* print(f\"($c: $w) \") */\n cFreq(c - 97) -= w\n }\n }\n /* println */\n\n cFreq\n }\n }\n\n /* x.foreach(arr => {\n arr.zipWithIndex.foreach(x =>\n if (x._1 > 0) print(f\"(${(x._2 + 97).toChar}: ${x._1})\\t\")\n )\n println\n }) */\n\n val accumFreq = Array.fill(26) { 0 }\n var lastHalf = \"\"\n\n val x = (2 to (n + 1) / 2).zip(freqLeft).foreach {\n case (i, x) => {\n for (j <- 0 until 26) x(j) -= accumFreq(j)\n x.zipWithIndex.foreach(pair =>\n if (pair._1 % i != 0 && (pair._1 - i + 1) % i == 0) {\n lastHalf = (pair._2 + 97).toChar + lastHalf\n accumFreq(pair._2) += i - 1\n }\n )\n }\n }\n\n println(f\"! ${half ++ lastHalf}\")\n }\n }\n}\n\n/* aabc */\n/*\nxyz\nyz\nxy\nz\nx\ny\nzy\nz\ny\n */\n"}], "src_uid": "438d18b7381671df3a68fb421b6c8169"} {"nl": {"description": "While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings \"ac\", \"bc\", \"abc\" and \"a\" are subsequences of string \"abc\" while strings \"abbc\" and \"acb\" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.", "input_spec": "The first line contains string a, and the second line\u00a0\u2014 string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.", "output_spec": "If there's no uncommon subsequence, print \"-1\". Otherwise print the length of the longest uncommon subsequence of a and b.", "sample_inputs": ["abcd\ndefgh", "a\na"], "sample_outputs": ["5", "-1"], "notes": "NoteIn the first example: you can choose \"defgh\" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a."}, "positive_code": [{"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"}, {"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 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}"}], "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"} {"nl": {"description": "In the pet store on sale there are: $$$a$$$ packs of dog food; $$$b$$$ packs of cat food; $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.", "input_spec": "The first line of input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \\le a,b,c,x,y \\le 10^8$$$).", "output_spec": "For each test case in a separate line, output: YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats; NO else. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["7\n\n1 1 4 2 3\n\n0 0 0 0 0\n\n5 5 0 4 6\n\n1 1 1 1 1\n\n50000000 50000000 100000000 100000000 100000000\n\n0 0 0 100000000 100000000\n\n1 3 2 2 5"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES\nNO\nNO"], "notes": null}, "positive_code": [{"source_code": "object Task1 extends App {\r\n import scala.io.StdIn\r\n\r\n def readLine = StdIn.readLine()\r\n def readNum = StdIn.readLine().toInt\r\n\r\n val testCases = readNum\r\n\r\n for (_ <- 0 until testCases) {\r\n val Array(dogFoodPacks, catFoodPacks, univPacks, dogsCount, catsCount) = readLine.split(\" \").map(_.toInt)\r\n val dogPackNeeded = dogFoodPacks - dogsCount\r\n val catPackNeeded = catFoodPacks - catsCount\r\n val totalPackNeeded = (if (dogPackNeeded < 0) dogPackNeeded else 0) + (if (catPackNeeded < 0) catPackNeeded else 0)\r\n\r\n if (Math.abs(totalPackNeeded) > univPacks) {\r\n println(\"NO\")\r\n } else {\r\n println(\"YES\")\r\n }\r\n }\r\n\r\n}"}], "negative_code": [], "src_uid": "7ac27da2546a50d453f7bb6cacef1068"} {"nl": {"description": "Ashish has a binary string $$$s$$$ of length $$$n$$$ that he wants to sort in non-decreasing order.He can perform the following operation: Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $$$k$$$ such that $$$1 \\leq k \\leq n$$$ and any sequence of $$$k$$$ indices $$$1 \\le i_1 \\lt i_2 \\lt \\ldots \\lt i_k \\le n$$$ such that $$$s_{i_1} \\ge s_{i_2} \\ge \\ldots \\ge s_{i_k}$$$. Reverse this subsequence in-place. Formally, swap $$$s_{i_1}$$$ with $$$s_{i_k}$$$, swap $$$s_{i_2}$$$ with $$$s_{i_{k-1}}$$$, $$$\\ldots$$$ and swap $$$s_{i_{\\lfloor k/2 \\rfloor}}$$$ with $$$s_{i_{\\lceil k/2 \\rceil + 1}}$$$ (Here $$$\\lfloor x \\rfloor$$$ denotes the largest integer not exceeding $$$x$$$, and $$$\\lceil x \\rceil$$$ denotes the smallest integer not less than $$$x$$$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $$$n$$$ operations.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 1000)$$$ \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \\le n \\le 1000)$$$ \u00a0\u2014 the length of the binary string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ containing only $$$0$$$s and $$$1$$$s. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.", "output_spec": "For each test case output the following: The minimum number of operations $$$m$$$ in the first line ($$$0 \\le m \\le n$$$). Each of the following $$$m$$$ lines should be of the form: $$$k$$$ $$$i_1$$$ $$$i_2$$$ ... $$$i_{k}$$$, where $$$k$$$ is the length and $$$i_1 \\lt i_2 \\lt ... \\lt i_{k}$$$ are the indices of the chosen subsequence. For them the conditions from the statement must hold. ", "sample_inputs": ["3\n7\n0011111\n5\n10100\n6\n001000"], "sample_outputs": ["0\n1\n4 1 3 4 5 \n1\n3 3 5 6"], "notes": "NoteIn the first test case, the binary string is already sorted in non-decreasing order.In the second test case, we can perform the following operation: $$$k = 4:$$$ choose the indices $$$\\{1, 3, 4, 5\\}$$$$$$\\underline{1}$$$ $$$0$$$ $$$\\underline{1}$$$ $$$\\underline{0}$$$ $$$\\underline{0}$$$ $$$\\rightarrow $$$ $$$\\underline{0}$$$ $$$0$$$ $$$\\underline{0}$$$ $$$\\underline{1}$$$ $$$\\underline{1}$$$ In the third test case, we can perform the following operation: $$$k = 3:$$$ choose the indices $$$\\{3, 5, 6\\}$$$$$$0$$$ $$$0$$$ $$$\\underline{1}$$$ $$$0$$$ $$$\\underline{0}$$$ $$$\\underline{0}$$$ $$$\\rightarrow $$$ $$$0$$$ $$$0$$$ $$$\\underline{0}$$$ $$$0$$$ $$$\\underline{0}$$$ $$$\\underline{1}$$$"}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "A string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the English alphabet, is given.You must choose some number $$$k$$$ between $$$0$$$ and $$$n$$$. Then, you select $$$k$$$ characters of $$$s$$$ and permute them however you want. In this process, the positions of the other $$$n-k$$$ characters remain unchanged. You have to perform this operation exactly once.For example, if $$$s=\\texttt{\"andrea\"}$$$, you can choose the $$$k=4$$$ characters $$$\\texttt{\"a_d_ea\"}$$$ and permute them into $$$\\texttt{\"d_e_aa\"}$$$ so that after the operation the string becomes $$$\\texttt{\"dneraa\"}$$$.Determine the minimum $$$k$$$ so that it is possible to sort $$$s$$$ alphabetically (that is, after the operation its characters appear in alphabetical order).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 40$$$) \u2014 the length of the string. The second line of each test case contains the string $$$s$$$. It is guaranteed that $$$s$$$ contains only lowercase letters of the English alphabet.", "output_spec": "For each test case, output the minimum $$$k$$$ that allows you to obtain a string sorted alphabetically, through the operation described above.", "sample_inputs": ["4\n3\nlol\n10\ncodeforces\n5\naaaaa\n4\ndcba"], "sample_outputs": ["2\n6\n0\n4"], "notes": "NoteIn the first test case, we can choose the $$$k=2$$$ characters $$$\\texttt{\"_ol\"}$$$ and rearrange them as $$$\\texttt{\"_lo\"}$$$ (so the resulting string is $$$\\texttt{\"llo\"}$$$). It is not possible to sort the string choosing strictly less than $$$2$$$ characters.In the second test case, one possible way to sort $$$s$$$ is to consider the $$$k=6$$$ characters $$$\\texttt{\"_o__force_\"}$$$ and rearrange them as $$$\\texttt{\"_c__efoor_\"}$$$ (so the resulting string is $$$\\texttt{\"ccdeefoors\"}$$$). One can show that it is not possible to sort the string choosing strictly less than $$$6$$$ characters.In the third test case, string $$$s$$$ is already sorted (so we can choose $$$k=0$$$ characters).In the fourth test case, we can choose all $$$k=4$$$ characters $$$\\texttt{\"dcba\"}$$$ and reverse the whole string (so the resulting string is $$$\\texttt{\"abcd\"}$$$)."}, "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// 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"}, {"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 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"}, {"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"}], "negative_code": [], "src_uid": "58ee86d4913787582ccdb54073656dc0"} {"nl": {"description": "Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all nodes for which $$$v$$$ is the parent. A vertex is a leaf if it has no children.The rooted tree Serval owns has $$$n$$$ nodes, node $$$1$$$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $$$\\max$$$ or $$$\\min$$$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively. Assume that there are $$$k$$$ leaves in the tree. Serval wants to put integers $$$1, 2, \\ldots, k$$$ to the $$$k$$$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?", "input_spec": "The first line contains an integer $$$n$$$ ($$$2 \\leq n \\leq 3\\cdot 10^5$$$), the size of the tree. The second line contains $$$n$$$ integers, the $$$i$$$-th of them represents the operation in the node $$$i$$$. $$$0$$$ represents $$$\\min$$$ and $$$1$$$ represents $$$\\max$$$. If the node is a leaf, there is still a number of $$$0$$$ or $$$1$$$, but you can ignore it. The third line contains $$$n-1$$$ integers $$$f_2, f_3, \\ldots, f_n$$$ ($$$1 \\leq f_i \\leq i-1$$$), where $$$f_i$$$ represents the parent of the node $$$i$$$.", "output_spec": "Output one integer\u00a0\u2014 the maximum possible number in the root of the tree.", "sample_inputs": ["6\n1 0 1 1 0 1\n1 2 2 2 2", "5\n1 0 1 0 1\n1 1 1 1", "8\n1 0 0 1 0 1 1 0\n1 1 2 2 3 3 3", "9\n1 1 0 0 1 0 1 0 1\n1 1 2 2 3 3 4 4"], "sample_outputs": ["1", "4", "4", "5"], "notes": "NotePictures below explain the examples. The numbers written in the middle of the nodes are their indices, and the numbers written on the top are the numbers written in the nodes.In the first example, no matter how you arrange the numbers, the answer is $$$1$$$. In the second example, no matter how you arrange the numbers, the answer is $$$4$$$. In the third example, one of the best solution to achieve $$$4$$$ is to arrange $$$4$$$ and $$$5$$$ to nodes $$$4$$$ and $$$5$$$. In the fourth example, the best solution is to arrange $$$5$$$ to node $$$5$$$. "}, "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[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 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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val f = na(n)\n val from, to = Array.ofDim[Int](n - 1)\n REP(n - 1) { i =>\n val p = ni() - 1\n from(i) = i + 1\n to(i) = p\n }\n val g = packUGraph(n, from, to)\n val (_, p, q) = traceBfs(g)\n val leafCnt = Array.ofDim[Int](n)\n val leafCnt2 = Array.ofDim[Int](n)\n val isLeaf = Array.ofDim[Boolean](n)\n REP_r(n) { i =>\n val v = q(i)\n if (leafCnt(v) == 0) {\n leafCnt(v) = 1\n leafCnt2(v) = 1\n isLeaf(v) = true\n }\n if (v != 0) leafCnt(p(v)) += leafCnt(v)\n if (!isLeaf(v)) {\n var cnt = 0\n var ms = 1e9.toInt\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != p(v)) {\n cnt += leafCnt2(u)\n ms = min(ms, leafCnt2(u))\n }\n }\n leafCnt2(v) = if (f(v) == 0) cnt else ms\n }\n }\n debug(leafCnt)\n debug(leafCnt2)\n val allmax = Array.ofDim[Boolean](n) // \u3053\u306e\u30ce\u30fc\u30c9\u304b\u3089\u30eb\u30fc\u30c8\u307e\u3067\u304c\u5168\u90e8max\n REP(n) { i =>\n val v = q(i)\n allmax(v) = (v == 0 || allmax(p(v))) && f(v) == 1\n }\n debug(allmax)\n\n val dp = Array.fill[Int](n)(1)\n REP(n) { i =>\n val v = q(i)\n // \u89aa\u307e\u3067\u304cmax\n if (v == 0 || allmax(p(v))) {\n // leaf\u3067\u306a\u3044 \u304b\u3064 min | leaf\n if (!isLeaf(v) && f(v) == 0 || isLeaf(v)) dp(v) = leafCnt(0) - leafCnt2(v) + 1\n }\n }\n\n debug(dp)\n\n out.println(dp.max)\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 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 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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val f = na(n)\n val from, to = Array.ofDim[Int](n - 1)\n REP(n - 1) { i =>\n val p = ni() - 1\n from(i) = i + 1\n to(i) = p\n }\n val g = packUGraph(n, from, to)\n val (_, p, q) = traceBfs(g)\n val leafCnt = Array.ofDim[Int](n)\n val isLeaf = Array.ofDim[Boolean](n)\n REP_r(n) { i =>\n val v = q(i)\n if (leafCnt(v) == 0) {\n leafCnt(v) = 1\n isLeaf(v) = true\n }\n if (v != 0) leafCnt(p(v)) += leafCnt(v)\n }\n debug(leafCnt)\n val allmax = Array.ofDim[Boolean](n) // \u3053\u306e\u30ce\u30fc\u30c9\u304b\u3089\u30eb\u30fc\u30c8\u307e\u3067\u304c\u5168\u90e8max\n REP(n) { i =>\n val v = q(i)\n allmax(v) = (v == 0 || allmax(p(v))) && f(v) == 1\n }\n debug(allmax)\n\n var ans = 0\n REP(n) { i =>\n val v = q(i)\n // \u89aa\u307e\u3067\u304cmax\u3067\u3001\u81ea\u8eab\u304cmin\n if ((v == 0 || allmax(p(v))) && f(v) == 0) {\n ans = max(ans, leafCnt(0) - leafCnt(v) + 1)\n }\n\n // leaf\u307e\u3067max\u3067\u3064\u306a\u304c\u3063\u3066\u3044\u308b\n if (isLeaf(v) && allmax(p(v))) {\n ans = leafCnt(0)\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[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 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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val f = na(n)\n val from, to = Array.ofDim[Int](n - 1)\n REP(n - 1) { i =>\n val p = ni() - 1\n from(i) = i + 1\n to(i) = p\n }\n val g = packUGraph(n, from, to)\n val (_, p, q) = traceBfs(g)\n val leafCnt = Array.ofDim[Int](n)\n val isLeaf = Array.ofDim[Boolean](n)\n REP_r(n) { i =>\n val v = q(i)\n if (leafCnt(v) == 0) {\n leafCnt(v) = 1\n isLeaf(v) = true\n }\n if (v != 0) leafCnt(p(v)) += leafCnt(v)\n }\n debug(leafCnt)\n val allmax = Array.ofDim[Boolean](n) // \u3053\u306e\u30ce\u30fc\u30c9\u304b\u3089\u30eb\u30fc\u30c8\u307e\u3067\u304c\u5168\u90e8max\n REP(n) { i =>\n val v = q(i)\n allmax(v) = (v == 0 || allmax(p(v))) && f(v) == 1\n }\n debug(allmax)\n\n val dp = Array.fill[Int](n)(1)\n REP(n) { i =>\n val v = q(i)\n // \u89aa\u307e\u3067\u304cmax\n if (v == 0 || allmax(p(v))) {\n // leaf\u3067\u306a\u3044 \u304b\u3064 min | leaf\n if (!isLeaf(v) && f(v) == 0 || isLeaf(v)) dp(v) = leafCnt(0) - leafCnt(v) + 1\n }\n }\n\n debug(dp)\n\n out.println(dp.max)\n }\n}"}], "src_uid": "3b6814b6753f307ec6f3a68179274caa"} {"nl": {"description": "There are n cities situated along the main road of Berland. Cities are represented by their coordinates \u2014 integer numbers a1,\u2009a2,\u2009...,\u2009an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money \u2014 he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.", "input_spec": "The first line contains one integer number n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). All numbers ai are pairwise distinct.", "output_spec": "Print two integer numbers \u2014 the minimal distance and the quantity of pairs with this distance.", "sample_inputs": ["4\n6 -3 0 4", "3\n-2 0 2"], "sample_outputs": ["2 1", "2 2"], "notes": "NoteIn the first example the distance between the first city and the fourth city is |4\u2009-\u20096|\u2009=\u20092, and it is the only pair with this distance."}, "positive_code": [{"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) \u21d2 b - a }.foldLeft((Int.MaxValue, 0)) {\n case ((mdist, _), dist) if dist < mdist \u21d2 (dist, 1)\n case ((mdist, count), dist) if dist == mdist \u21d2 (dist, count + 1)\n case (prev, _) \u21d2 prev\n }\n println(s\"$minDist $count\")\n}\n"}, {"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"} {"nl": {"description": "Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar \"Jupiter\". According to the sweepstake rules, each wrapping has an integer written on it \u2014 the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy \u2014 as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost): a mug (costs a points), a towel (costs b points), a bag (costs c points), a bicycle (costs d points), a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1,\u2009p2,\u2009...,\u2009pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009109). The third line contains 5 integers a, b, c, d, e (1\u2009\u2264\u2009a\u2009<\u2009b\u2009<\u2009c\u2009<\u2009d\u2009<\u2009e\u2009\u2264\u2009109) \u2014 the prizes' costs.", "output_spec": "Print on the first line 5 integers, separated by a space \u2014 the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer \u2014 the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3\n3 10 4\n2 4 10 15 20", "4\n10 4 39 2\n3 5 10 11 12"], "sample_outputs": ["1 1 1 0 0 \n1", "3 0 1 0 3 \n0"], "notes": "NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3\u2009-\u20092\u2009+\u200910\u2009-\u200910\u2009+\u20094\u2009-\u20094\u2009=\u20091 points remains."}, "positive_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[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 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": "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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.", "input_spec": "The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \\leq n \\leq 100$$$, $$$1 \\leq r \\leq 100$$$)\u00a0\u2014 the number of the outer circles and the radius of the inner circle respectively.", "output_spec": "Output a single number $$$R$$$\u00a0\u2014 the radius of the outer circle required for building the required picture. Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\\frac{|a-b|}{max(1, |b|)} \\le 10^{-6}$$$.", "sample_inputs": ["3 1", "6 1", "100 100"], "sample_outputs": ["6.4641016", "1.0000000", "3.2429391"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "e27cff5d681217460d5238bf7ef6a876"} {"nl": {"description": "The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 \u2014 colors of both sides. The first number in a line is the color of the front of the card, the second one \u2014 of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces.", "output_spec": "On a single line print a single integer \u2014 the sought minimum number of moves. If it is impossible to make the set funny, print -1.", "sample_inputs": ["3\n4 7\n4 7\n7 4", "5\n4 7\n7 4\n2 11\n9 7\n1 1"], "sample_outputs": ["0", "2"], "notes": "NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7."}, "positive_code": [{"source_code": "object Main extends App {\n import scala.collection.mutable\n import scala.io.{Source, StdIn}\n override def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val mapHeads = mutable.Map[Int, Int]()\n val mapTails = mutable.Map[Int, Int]()\n for (_ <- 1 to n) {\n val str = StdIn.readLine().split(\" \").map(_.toInt)\n val (a, b) = str.head -> str.last\n mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)\n if(a!=b)mapTails.put(b, mapTails.getOrElse(b, 0) + 1)\n }\n var minRes = n\n var flag = false\n for ((num, count) <- mapHeads) {\n val numTails = mapTails.getOrElse(num, 0)\n if (count + numTails >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)\n flag = true\n }\n }\n for ((num, count) <- mapTails) {\n val numHeads = mapHeads.getOrElse(num, 0)\n if (count + numHeads >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - numHeads), 0)\n flag = true\n }\n }\n println(if(flag) minRes else -1)\n }\n}"}], "negative_code": [{"source_code": "object Main extends App {\n import scala.collection.mutable\n import scala.io.{Source, StdIn}\n override def main(args: Array[String]): Unit = {\n //WebSocketRunner.runClient(s\"http://$url/codenjoy-contest/board/player/$secret?code=$code\", new MySolver, new MyBoard)\n val n = StdIn.readInt()\n val mapHeads = mutable.Map[Int, Int]()\n val mapTails = mutable.Map[Int, Int]()\n for (_ <- 1 to n) {\n val str = StdIn.readLine().split(\" \").map(_.toInt)\n val (a, b) = str.head -> str.last\n mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)\n mapTails.put(b, mapTails.getOrElse(b, 0) + 1)\n }\n var minRes = n\n var flag = false\n for ((num, count) <- mapHeads) {\n val numTails = mapTails.getOrElse(num, 0)\n if (num + numTails >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)\n flag = true\n }\n }\n println(if(flag) minRes else -1)\n }\n}"}, {"source_code": "object Main extends App {\n import scala.collection.mutable\n import scala.io.{Source, StdIn}\n override def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val mapHeads = mutable.Map[Int, Int]()\n val mapTails = mutable.Map[Int, Int]()\n for (_ <- 1 to n) {\n val str = StdIn.readLine().split(\" \").map(_.toInt)\n val (a, b) = str.head -> str.last\n mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)\n mapTails.put(b, mapTails.getOrElse(b, 0) + 1)\n }\n var minRes = n\n var flag = false\n for ((num, count) <- mapHeads) {\n val numTails = mapTails.getOrElse(num, 0)\n if (count + numTails >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)\n flag = true\n }\n }\n for ((num, count) <- mapTails) {\n val numHeads = mapHeads.getOrElse(num, 0)\n if (count + numHeads >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - numHeads), 0)\n flag = true\n }\n }\n println(if(flag) minRes else -1)\n }\n}"}, {"source_code": "object Main extends App {\n import scala.collection.mutable\n import scala.io.{Source, StdIn}\n override def main(args: Array[String]): Unit = {\n //WebSocketRunner.runClient(s\"http://$url/codenjoy-contest/board/player/$secret?code=$code\", new MySolver, new MyBoard)\n val n = StdIn.readInt()\n val mapHeads = mutable.Map[Int, Int]()\n val mapTails = mutable.Map[Int, Int]()\n for (_ <- 1 to n) {\n val str = StdIn.readLine().split(\" \").map(_.toInt)\n val (a, b) = str.head -> str.last\n mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)\n mapTails.put(b, mapTails.getOrElse(b, 0) + 1)\n }\n var minRes = n\n var flag = false\n for ((num, count) <- mapHeads) {\n val numTails = mapTails.getOrElse(num, 0)\n if (count + numTails >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)\n flag = true\n }\n }\n for ((num, count) <- mapTails) {\n val numHeads = mapHeads.getOrElse(num, 0)\n if (count + numHeads >= (n + 1) / 2) {\n minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)\n flag = true\n }\n }\n println(if(flag) minRes else -1)\n }\n}"}, {"source_code": "object Main extends App {\n import scala.collection.mutable\n import scala.io.{Source, StdIn}\n override def main(args: Array[String]): Unit = {\n //WebSocketRunner.runClient(s\"http://$url/codenjoy-contest/board/player/$secret?code=$code\", new MySolver, new MyBoard)\n val n = StdIn.readInt()\n val mapHeads = mutable.Map[Int, Int]()\n val mapTails = mutable.Map[Int, Int]()\n for (_ <- 1 to n) {\n val str = StdIn.readLine().split(\" \").map(_.toInt)\n val (a, b) = str.head -> str.last\n mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)\n mapTails.put(b, mapTails.getOrElse(b, 0) + 1)\n }\n var minRes = n\n var flag = false\n for ((num, count) <- mapHeads) {\n val numTails = mapTails.getOrElse(num, 0)\n if (num + numTails >= (n + 1) / 2) {\n minRes = Math.min(minRes, (n+1)/2 - count)\n flag = true\n }\n }\n println(if(flag) minRes else -1)\n }\n}"}], "src_uid": "5e055bad1da5bdc84599d6f2f89fbd12"} {"nl": {"description": "Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn\u2019t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won\u2019t describe his work in detail and take a better look at a simplified version of the warehouse.The warehouse has one set of shelving. It has n shelves, each of which is divided into m sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf\u2019s beginning. If DravDe still can\u2019t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught.After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you.The process of counting contains two types of query messages: \u00ab+1 x y id\u00bb (where x, y are integers, 1\u2009\u2264\u2009x\u2009\u2264\u2009n, 1\u2009\u2264\u2009y\u2009\u2264\u2009m, and id is a string of lower case Latin letters \u2014 from 1 to 10 characters long). That query means that the warehouse got a box identified as id, which should be put in the section y on the shelf x. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don\u2019t have to answer this query. \u00ab-1 id\u00bb (where id is a string of lower case Latin letters \u2014 from 1 to 10 characters long). That query means that a box identified as id is removed from the warehouse. You have to answer this query (see output format). ", "input_spec": "The first input line contains integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200930, 1\u2009\u2264\u2009k\u2009\u2264\u20092000) \u2014 the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following k lines the queries are given in the order of appearance in the format described above.", "output_spec": "For each query of the \u00ab-1 id\u00bb type output two numbers in a separate line \u2014 index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output \u00ab-1 -1\u00bb without quotes.", "sample_inputs": ["2 2 9\n+1 1 1 cola\n+1 1 1 fanta\n+1 1 1 sevenup\n+1 1 1 whitekey\n-1 cola\n-1 fanta\n-1 sevenup\n-1 whitekey\n-1 cola", "2 2 8\n+1 1 1 cola\n-1 cola\n+1 1 1 fanta\n-1 fanta\n+1 1 1 sevenup\n-1 sevenup\n+1 1 1 whitekey\n-1 whitekey"], "sample_outputs": ["1 1\n1 2\n2 1\n2 2\n-1 -1", "1 1\n1 1\n1 1\n1 1"], "notes": null}, "positive_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 reader = Source.fromFile(\"input.txt\").bufferedReader();\n var writer = new PrintWriter(new FileWriter(\"output.txt\"));\n var Array(n, m, k) = reader.readLine().split(\" \").toArray.map(_.toInt);\n var a = Array.fill(n, m)(\"\");\n var list = List[String]();\n for (i <- 0 until k) {\n var l = reader.readLine.split(\" \");\n var pref = l(0);\n if (pref == \"+1\") {\n\t var x = l(1).toInt - 1;\n\t var y = l(2).toInt - 1;\n\t var id = l(3);\n\t if (a(x)(y) == \"\") {\n\t\t a(x)(y) = id;\n\t } else {\n\t var done = false;\n\t for (j <- x until n) {\n\t\t for (d <- 0 until m) {\n\t\t if (!done && ((j == x && d > y) || (j > x)) && a(j)(d) == \"\") {\n\t\t a(j)(d) = id;\n\t\t done = true;\n\t\t }\n\t\t }\n\t\t }\n\t }\n\t println(a.deep.mkString(\"\\n\"));\n\t println\n } else {\n var id = l(1);\n println(a.deep.mkString(\"\\n\"));\n println\n var x = a.indexWhere(p => p.contains(id));\n if (x == -1) {\n writer.println(\"-1 -1\");\n } else {\n var y = a(x).indexWhere(p => p.equals(id));\n a(x)(y) = \"\";\n writer.println((x + 1) + \" \" + (y + 1));\n }\n }\n }\n writer.close();\n } \n}"}], "negative_code": [], "src_uid": "44d45a7e21418470bda396d91c65e736"} {"nl": {"description": "Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 \u2014 to a2 billion, ..., and in the current (2000\u2009+\u2009n)-th year \u2014 an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year \u2014 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company\u2019s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth.Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 \u2014 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The next line contains n integers ai (\u2009-\u2009100\u2009\u2264\u2009ai\u2009\u2264\u2009100). The number ai determines the income of BerSoft company in the (2000\u2009+\u2009i)-th year. The numbers in the line are separated by spaces.", "output_spec": "Output k \u2014 the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.", "sample_inputs": ["10\n-2 1 1 3 2 3 4 -10 -2 5", "3\n-1 -2 -3"], "sample_outputs": ["5\n2002 2005 2006 2007 2010", "0"], "notes": null}, "positive_code": [{"source_code": "object P039B extends App {\n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n var curr = 0\n var resultBuilder = new collection.mutable.ArrayBuilder.ofInt()\n for (i <- 0 to n-1) {\n if (a(i) == curr + 1) {\n resultBuilder += 2001 + i\n curr += 1\n }\n }\n if (curr == 0) {\n println(0)\n }\n else {\n val result = resultBuilder.result()\n println(result size)\n println(result.deep.mkString(\" \"))\n }\n}\n\n"}], "negative_code": [], "src_uid": "499ddfd7e0563e3ca8c71219e408650f"} {"nl": {"description": "Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$p$$$. For example, if $$$n = 3$$$, then $$$p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence will be $$$n \\cdot n!$$$.Let $$$1 \\leq i \\leq j \\leq n \\cdot n!$$$ be a pair of indices. We call the sequence $$$(p_i, p_{i+1}, \\dots, p_{j-1}, p_j)$$$ a subarray of $$$p$$$. Its length is defined as the number of its elements, i.e., $$$j - i + 1$$$. Its sum is the sum of all its elements, i.e., $$$\\sum_{k=i}^j p_k$$$. You are given $$$n$$$. Find the number of subarrays of $$$p$$$ of length $$$n$$$ having sum $$$\\frac{n(n+1)}{2}$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number). ", "input_spec": "The only line contains one integer $$$n$$$\u00a0($$$1 \\leq n \\leq 10^6$$$), as described in the problem statement.", "output_spec": "Output a single integer\u00a0\u2014 the number of subarrays of length $$$n$$$ having sum $$$\\frac{n(n+1)}{2}$$$, modulo $$$998244353$$$.", "sample_inputs": ["3", "4", "10"], "sample_outputs": ["9", "56", "30052700"], "notes": "NoteIn the first sample, there are $$$16$$$ subarrays of length $$$3$$$. In order of appearance, they are:$$$[1, 2, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 3]$$$, $$$[1, 3, 2]$$$, $$$[3, 2, 2]$$$, $$$[2, 2, 1]$$$, $$$[2, 1, 3]$$$, $$$[1, 3, 2]$$$, $$$[3, 2, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 3]$$$, $$$[1, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[1, 2, 3]$$$, $$$[2, 3, 2]$$$, $$$[3, 2, 1]$$$. Their sums are $$$6$$$, $$$6$$$, $$$7$$$, $$$6$$$, $$$7$$$, $$$5$$$, $$$6$$$, $$$6$$$, $$$8$$$, $$$6$$$, $$$7$$$, $$$5$$$, $$$6$$$, $$$6$$$, $$$7$$$, $$$6$$$. As $$$\\frac{n(n+1)}{2} = 6$$$, the answer is $$$9$$$."}, "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": "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}"}, {"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"} {"nl": {"description": "A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n\u2009-\u20091 the inequality |hi\u2009-\u2009hi\u2009+\u20091|\u2009\u2264\u20091 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi\u2009-\u2009hi\u2009+\u20091|\u2009\u2264\u20091.", "input_spec": "The first line contains two space-separated numbers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009108, 1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1\u2009\u2264\u2009di\u2009\u2264\u2009n, 0\u2009\u2264\u2009hdi\u2009\u2264\u2009108)\u00a0\u2014 the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m\u2009-\u20091 the following condition holds: di\u2009<\u2009di\u2009+\u20091.", "output_spec": "If the notes aren't contradictory, print a single integer \u2014 the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).", "sample_inputs": ["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"], "sample_outputs": ["2", "IMPOSSIBLE"], "notes": "NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0,\u20090,\u20091,\u20092,\u20091,\u20091,\u20090,\u20091).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent."}, "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 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"}, {"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"} {"nl": {"description": "Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number hi. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h1, h2, ..., hn have been read at the beginning of the operation. Mike needs to read the data on m distinct tracks with numbers p1, p2, ..., pm. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.", "input_spec": "The first line of the input contains two space-separated integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of disk heads and the number of tracks to read, accordingly. The second line contains n distinct integers hi in ascending order (1\u2009\u2264\u2009hi\u2009\u2264\u20091010, hi\u2009<\u2009hi\u2009+\u20091) \u2014 the initial positions of the heads. The third line contains m distinct integers pi in ascending order (1\u2009\u2264\u2009pi\u2009\u2264\u20091010, pi\u2009<\u2009pi\u2009+\u20091) - the numbers of tracks to read. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is recommended to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print a single number \u2014 the minimum time required, in seconds, to read all the needed tracks.", "sample_inputs": ["3 4\n2 5 6\n1 3 6 8", "3 3\n1 2 3\n1 2 3", "1 2\n165\n142 200"], "sample_outputs": ["2", "0", "81"], "notes": "NoteThe first test coincides with the figure. In this case the given tracks can be read in 2 seconds in the following way: during the first second move the 1-st head to the left and let it stay there; move the second head to the left twice; move the third head to the right twice (note that the 6-th track has already been read at the beginning). One cannot read the tracks in 1 second as the 3-rd head is at distance 2 from the 8-th track."}, "positive_code": [{"source_code": "import scala.collection._\n\nobject E 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 val hs = readLongs(n)\n val ps = readLongs(m)\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 def can(steps: Long): Boolean = {\n var hi = 0\n var pi = 0\n var read = -1L\n while (pi < ps.length && hi < hs.length) {\n if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {\n read = math.max(math.max(hs(hi), \n hs(hi) + steps - 2 * (hs(hi) - ps(pi))), \n hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)\n } else if (ps(pi) > hs(hi) && ps(pi) <= hs(hi) + steps) {\n read = hs(hi) + steps\n }\n hi += 1\n while (pi < ps.length && ps(pi) <= read) pi += 1\n }\n \n pi == ps.length\n }\n\n println(binSearch(0, 100000000000L))\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject E 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 val hs = readLongs(n)\n val ps = readLongs(m)\n \n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) hi + 1\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 def can(steps: Long): Boolean = {\n var hi = 0\n var pi = 0\n var read = -1L\n while (pi < ps.length && hi < hs.length) {\n if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {\n read = math.max(math.max(hs(hi), hs(hi) + steps - 2 * (hs(hi) - ps(pi))), hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)\n } else if (ps(pi) > hs(hi) && ps(pi) <= hs(hi) + steps) {\n read = hs(hi) + steps\n }\n hi += 1\n while (pi < ps.length && ps(pi) <= read) pi += 1\n }\n \n pi == ps.length\n }\n\n println(binSearch(0, 10000000001L))\n}"}, {"source_code": "import scala.collection._\n\nobject E 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 val hs = readLongs(n)\n val ps = readLongs(m)\n \n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) hi + 1\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 def can(steps: Long): Boolean = {\n var hi = 0\n var pi = 0\n var read = -1L\n while (pi < ps.length && hi < hs.length) {\n if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {\n read = math.max(hs(hi), hs(hi) + steps - 2 * (hs(hi) - ps(pi)))\n } else if (ps(pi) <= hs(hi) + steps) {\n read = hs(hi) + steps\n }\n hi += 1\n while (pi < ps.length && ps(pi) <= read) pi += 1\n }\n \n pi == ps.length\n }\n\n println(binSearch(0, 10000000001L))\n}"}, {"source_code": "import scala.collection._\n\nobject E 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 val hs = readLongs(n)\n val ps = readLongs(m)\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 def can(steps: Long): Boolean = {\n var hi = 0\n var pi = 0\n var read = -1L\n while (pi < ps.length && hi < hs.length) {\n if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {\n read = math.max(math.max(hs(hi), \n hs(hi) + steps - 2 * (hs(hi) - ps(pi))), \n hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)\n } else if (ps(pi) > hs(hi) && ps(pi) <= hs(hi) + steps) {\n read = hs(hi) + steps\n }\n hi += 1\n while (pi < ps.length && ps(pi) <= read) pi += 1\n }\n \n pi == ps.length\n }\n\n println(binSearch(0, 10000000001L))\n}"}, {"source_code": "import scala.collection._\n\nobject E 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 val hs = readLongs(n)\n val ps = readLongs(m)\n \n @annotation.tailrec\n def binSearch(low: Long, hi: Long): Long = {\n if (hi < low) hi + 1\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 def can(steps: Long): Boolean = {\n var hi = 0\n var pi = 0\n var read = -1L\n while (pi < ps.length && hi < hs.length) {\n if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {\n read = math.max(math.max(hs(hi), hs(hi) + steps - 2 * (hs(hi) - ps(pi))), hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)\n } else if (ps(pi) <= hs(hi) + steps) {\n read = hs(hi) + steps\n }\n hi += 1\n while (pi < ps.length && ps(pi) <= read) pi += 1\n }\n \n pi == ps.length\n }\n\n println(binSearch(0, 10000000001L))\n}"}], "src_uid": "4e1fc2fcc83b007c943a8ea26eea6320"} {"nl": {"description": "Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^9$$$; $$$1 \\le k \\le 10^9$$$).", "output_spec": "For each test case, print one integer\u00a0\u2014 the $$$k$$$-th special number in increasing order modulo $$$10^9+7$$$.", "sample_inputs": ["3\n3 4\n2 12\n105 564"], "sample_outputs": ["9\n12\n3595374"], "notes": "NoteFor $$$n = 3$$$ the sequence is $$$[1,3,4,9...]$$$"}, "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"}, {"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"}], "negative_code": [], "src_uid": "2cc35227174e6a4d48e0839cba211724"} {"nl": {"description": "All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl,\u2009yr] of the seats numbers in this row, where yr\u2009-\u2009yl\u2009+\u20091\u2009=\u2009M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say, \u2014 the row and the seat numbers of the most \"central\" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program. ", "input_spec": "The first line contains two integers N and K (1\u2009\u2264\u2009N\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009K\u2009\u2264\u200999) \u2014 the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1,\u2009K] \u2014 requests to the program.", "output_spec": "Output N lines. In the i-th line output \u00ab-1\u00bb (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x,\u2009yl,\u2009yr. Separate the numbers with a space.", "sample_inputs": ["2 1\n1 1", "4 3\n1 2 3 1"], "sample_outputs": ["1 1 1\n-1", "2 2 2\n1 1 2\n3 1 3\n2 1 1"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "A sequence of non-negative integers $$$a_1, a_2, \\dots, a_n$$$ is called growing if for all $$$i$$$ from $$$1$$$ to $$$n - 1$$$ all ones (of binary representation) in $$$a_i$$$ are in the places of ones (of binary representation) in $$$a_{i + 1}$$$ (in other words, $$$a_i \\:\\&\\: a_{i + 1} = a_i$$$, where $$$\\&$$$ denotes bitwise AND). If $$$n = 1$$$ then the sequence is considered growing as well.For example, the following four sequences are growing: $$$[2, 3, 15, 175]$$$ \u2014 in binary it's $$$[10_2, 11_2, 1111_2, 10101111_2]$$$; $$$[5]$$$ \u2014 in binary it's $$$[101_2]$$$; $$$[1, 3, 7, 15]$$$ \u2014 in binary it's $$$[1_2, 11_2, 111_2, 1111_2]$$$; $$$[0, 0, 0]$$$ \u2014 in binary it's $$$[0_2, 0_2, 0_2]$$$. The following three sequences are non-growing: $$$[3, 4, 5]$$$ \u2014 in binary it's $$$[11_2, 100_2, 101_2]$$$; $$$[5, 4, 3]$$$ \u2014 in binary it's $$$[101_2, 100_2, 011_2]$$$; $$$[1, 2, 4, 8]$$$ \u2014 in binary it's $$$[0001_2, 0010_2, 0100_2, 1000_2]$$$. Consider two sequences of non-negative integers $$$x_1, x_2, \\dots, x_n$$$ and $$$y_1, y_2, \\dots, y_n$$$. Let's call this pair of sequences co-growing if the sequence $$$x_1 \\oplus y_1, x_2 \\oplus y_2, \\dots, x_n \\oplus y_n$$$ is growing where $$$\\oplus$$$ denotes bitwise XOR.You are given a sequence of integers $$$x_1, x_2, \\dots, x_n$$$. Find the lexicographically minimal sequence $$$y_1, y_2, \\dots, y_n$$$ such that sequences $$$x_i$$$ and $$$y_i$$$ are co-growing.The sequence $$$a_1, a_2, \\dots, a_n$$$ is lexicographically smaller than the sequence $$$b_1, b_2, \\dots, b_n$$$ if there exists $$$1 \\le k \\le n$$$ such that $$$a_i = b_i$$$ for any $$$1 \\le i < k$$$ but $$$a_k < b_k$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 length of the sequence $$$x_i$$$. The second line contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$0 \\le x_i < 2^{30}$$$) \u2014 elements of the sequence $$$x_i$$$. It is guaranteed that the sum of $$$n$$$ overall all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print $$$n$$$ integers $$$y_1, y_2, \\dots, y_n$$$ ($$$0 \\le y_i < 2^{30}$$$) \u2014 lexicographically minimal sequence such that such that it's co-growing with given sequence $$$x_i$$$.", "sample_inputs": ["5\n4\n1 3 7 15\n4\n1 2 4 8\n5\n1 2 3 4 5\n4\n11 13 15 1\n1\n0"], "sample_outputs": ["0 0 0 0 \n0 1 3 7 \n0 1 0 3 2 \n0 2 0 14 \n0"], "notes": null}, "positive_code": [{"source_code": "object D 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 xn = readLine().split(\" \").map(_.toInt)\r\n val yn = (1 until n).scanLeft(0) { case (yj, i) =>\r\n val xj = yj ^ xn(i - 1)\r\n xj - (xj & xn(i))\r\n }\r\n\r\n println(yn.mkString(\" \"))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "8d25700c9996a80fea3557222273c89a"} {"nl": {"description": "In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of \"aaaa\", \"aa\", \"aaa\" is \"a\", the root of \"aabb\", \"bab\", \"baabb\", \"ab\" is \"ab\". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^3$$$)\u00a0\u2014 the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \\ldots, s_n$$$\u00a0\u2014 the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.", "output_spec": "Output one integer\u00a0\u2014 the number of different objects mentioned in the given ancient Aramic script.", "sample_inputs": ["5\na aa aaa ab abb", "3\namer arem mrea"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first test, there are two objects mentioned. The roots that represent them are \"a\",\"ab\".In the second test, there is only one object, its root is \"amer\", the other strings are just permutations of \"amer\"."}, "positive_code": [{"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}"}, {"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": "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"}], "negative_code": [], "src_uid": "cf1eb164c4c970fd398ef9e98b4c07b1"} {"nl": {"description": "Vasiliy lives at point (a,\u2009b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi,\u2009yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.", "input_spec": "The first line of the input contains two integers a and b (\u2009-\u2009100\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009100)\u00a0\u2014 coordinates of Vasiliy's home. The second line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of available Beru-taxi cars nearby. The i-th of the following n lines contains three integers xi, yi and vi (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009100, 1\u2009\u2264\u2009vi\u2009\u2264\u2009100)\u00a0\u2014 the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.", "output_spec": "Print a single real value\u00a0\u2014 the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["0 0\n2\n2 0 1\n0 2 2", "1 3\n3\n3 3 2\n-2 3 6\n-2 7 10"], "sample_outputs": ["1.00000000000000000000", "0.50000000000000000000"], "notes": "NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously."}, "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": "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}"}, {"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"} {"nl": {"description": "You are given a set of $$$n$$$ segments on the axis $$$Ox$$$, each segment has integer endpoints between $$$1$$$ and $$$m$$$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le m$$$) \u2014 coordinates of the left and of the right endpoints. Consider all integer points between $$$1$$$ and $$$m$$$ inclusive. Your task is to print all such points that don't belong to any segment. The point $$$x$$$ belongs to the segment $$$[l; r]$$$ if and only if $$$l \\le x \\le r$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 100$$$) \u2014 the number of segments and the upper bound for coordinates. The next $$$n$$$ lines contain two integers each $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le m$$$) \u2014 the endpoints of the $$$i$$$-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that $$$l_i=r_i$$$, i.e. a segment can degenerate to a point.", "output_spec": "In the first line print one integer $$$k$$$ \u2014 the number of points that don't belong to any segment. In the second line print exactly $$$k$$$ integers in any order \u2014 the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.", "sample_inputs": ["3 5\n2 2\n1 2\n5 5", "1 7\n1 7"], "sample_outputs": ["2\n3 4", "0"], "notes": "NoteIn the first example the point $$$1$$$ belongs to the second segment, the point $$$2$$$ belongs to the first and the second segments and the point $$$5$$$ belongs to the third segment. The points $$$3$$$ and $$$4$$$ do not belong to any segment.In the second example all the points from $$$1$$$ to $$$7$$$ belong to the first segment."}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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": "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"}, {"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"} {"nl": {"description": "Lord Omkar would like to have a tree with $$$n$$$ nodes ($$$3 \\le n \\le 10^5$$$) and has asked his disciples to construct the tree. However, Lord Omkar has created $$$m$$$ ($$$\\mathbf{1 \\le m < n}$$$) restrictions to ensure that the tree will be as heavenly as possible. A tree with $$$n$$$ nodes is an connected undirected graph with $$$n$$$ nodes and $$$n-1$$$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree: A restriction consists of $$$3$$$ pairwise distinct integers, $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \\le a,b,c \\le n$$$). It signifies that node $$$b$$$ cannot lie on the simple path between node $$$a$$$ and node $$$c$$$. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$3 \\leq n \\leq 10^5$$$, $$$\\mathbf{1 \\leq m < n}$$$), representing the size of the tree and the number of restrictions. The $$$i$$$-th of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ ($$$1 \\le a_i, b_i, c_i \\le n$$$, $$$a$$$, $$$b$$$, $$$c$$$ are distinct), signifying that node $$$b_i$$$ cannot lie on the simple path between nodes $$$a_i$$$ and $$$c_i$$$. It is guaranteed that the sum of $$$n$$$ across all test cases will not exceed $$$10^5$$$.", "output_spec": "For each test case, output $$$n-1$$$ lines representing the $$$n-1$$$ edges in the tree. On each line, output two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) signifying that there is an edge between nodes $$$u$$$ and $$$v$$$. Given edges have to form a tree that satisfies Omkar's restrictions.", "sample_inputs": ["2\n7 4\n1 2 3\n3 4 5\n5 6 7\n6 5 4\n5 3\n1 2 3\n2 3 4\n3 4 5"], "sample_outputs": ["1 2\n1 3\n3 5\n3 4\n2 7\n7 6\n5 1\n1 3\n3 2\n2 4"], "notes": "NoteThe output of the first sample case corresponds to the following tree: For the first restriction, the simple path between $$$1$$$ and $$$3$$$ is $$$1, 3$$$, which doesn't contain $$$2$$$. The simple path between $$$3$$$ and $$$5$$$ is $$$3, 5$$$, which doesn't contain $$$4$$$. The simple path between $$$5$$$ and $$$7$$$ is $$$5, 3, 1, 2, 7$$$, which doesn't contain $$$6$$$. The simple path between $$$6$$$ and $$$4$$$ is $$$6, 7, 2, 1, 3, 4$$$, which doesn't contain $$$5$$$. Thus, this tree meets all of the restrictions.The output of the second sample case corresponds to the following tree: "}, "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"}, {"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"}], "negative_code": [], "src_uid": "dd3ba43eb0261ccdb7269a2696a042da"} {"nl": {"description": "The Fair Nut is going to travel to the Tree Country, in which there are $$$n$$$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $$$u$$$ and go by a simple path to city $$$v$$$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.A filling station is located in every city. Because of strange law, Nut can buy only $$$w_i$$$ liters of gasoline in the $$$i$$$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the number of cities. The second line contains $$$n$$$ integers $$$w_1, w_2, \\ldots, w_n$$$ ($$$0 \\leq w_{i} \\leq 10^9$$$)\u00a0\u2014 the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $$$n - 1$$$ lines describes road and contains three integers $$$u$$$, $$$v$$$, $$$c$$$ ($$$1 \\leq u, v \\leq n$$$, $$$1 \\leq c \\leq 10^9$$$, $$$u \\ne v$$$), where $$$u$$$ and $$$v$$$\u00a0\u2014 cities that are connected by this road and $$$c$$$\u00a0\u2014 its length. It is guaranteed that graph of road connectivity is a tree.", "output_spec": "Print one number\u00a0\u2014 the maximum amount of gasoline that he can have at the end of the path.", "sample_inputs": ["3\n1 3 3\n1 2 2\n1 3 2", "5\n6 3 2 5 0\n1 2 10\n2 3 3\n2 4 1\n1 5 1"], "sample_outputs": ["3", "7"], "notes": "NoteThe optimal way in the first example is $$$2 \\to 1 \\to 3$$$. The optimal way in the second example is $$$2 \\to 4$$$. "}, "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 W = na(N)\n val From, To, Cost = Array.ofDim[Int](N - 1)\n REP(N - 1) { i =>\n From(i) = ni() - 1\n To(i) = ni() - 1\n Cost(i) = ni()\n }\n val g = packWUGraph(N, From, To, Cost)\n val (_, parent, queue) = traceBfs(g)\n\n val dp = Array.ofDim[Long](N)\n\n var ans = 0L\n REP_r(N) { i =>\n val v = queue(i)\n val single = W(v)\n\n var withChild = Long.MinValue\n val childCnt = g(v).length - (if (v != 0) 1 else 0)\n\n if (childCnt > 0) {\n val es = g(v)\n REP(es.length) { j =>\n val e = es(j)\n if (parent(v) != e.to) withChild = max(withChild, dp(e.to) - e.weight + W(v))\n }\n }\n dp(v) = max(single, withChild)\n ans = max(ans, dp(v))\n\n // merge\n if (childCnt > 1) {\n // \u6700\u4e0a\u4f4d\uff12\u3064\u304c\u6b32\u3057\u3044\n var mx1, mx2 = Long.MinValue\n\n val es = g(v)\n REP(es.length) { j =>\n val e = es(j)\n if (parent(v) != e.to) {\n mx2 = max(mx2, dp(e.to) - e.weight)\n // swap\n if (mx2 > mx1) {\n val tmp = mx1\n mx1 = mx2\n mx2 = tmp\n }\n }\n }\n\n val merged = mx1 + mx2 + W(v)\n ans = max(ans, merged)\n }\n }\n\n out.println(ans)\n }\n\n case class Edge(to: Int, weight: Int)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Int]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: WUGraph, 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 e = g(v)(i)\n val u = e.to\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}"}], "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 W = na(N)\n val From, To, Cost = Array.ofDim[Int](N - 1)\n REP(N - 1) { i =>\n From(i) = ni() - 1\n To(i) = ni() - 1\n Cost(i) = ni()\n }\n val g = packWUGraph(N, From, To, Cost)\n val (_, parent, queue) = traceBfs(g)\n\n val dp = Array.ofDim[Long](N)\n\n var ans = 0L\n REP_r(N) { i =>\n val v = queue(i)\n val single = W(v)\n\n var withChild = Long.MinValue\n if (g(v).length > 0) {\n val es = g(v)\n REP(es.length) { j =>\n val e = es(j)\n if (parent(v) != e.to) withChild = max(withChild, dp(e.to) - e.weight + W(v))\n }\n }\n dp(v) = max(single, withChild)\n ans = max(ans, dp(v))\n\n // merge\n if (g(v).length > 1) {\n // \u6700\u4e0a\u4f4d\uff12\u3064\u304c\u6b32\u3057\u3044\n var mx1, mx2 = Long.MinValue\n\n val es = g(v)\n REP(es.length) { j =>\n val e = es(j)\n if (parent(v) != e.to) {\n mx2 = max(mx2, dp(e.to) - e.weight)\n // swap\n if (mx2 > mx1) {\n val tmp = mx1\n mx1 = mx2\n mx2 = tmp\n }\n }\n }\n\n val merged = mx1 + mx2 + W(v)\n ans = max(ans, merged)\n }\n }\n\n out.println(ans)\n }\n\n case class Edge(to: Int, weight: Int)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Int]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: WUGraph, 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 e = g(v)(i)\n val u = e.to\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}"}], "src_uid": "3fd58cef6d06400992088da9822ff317"} {"nl": {"description": "Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai\u2009>\u20090, then ai bourles are deposited to Luba's account. If ai\u2009<\u20090, then ai bourles are withdrawn. And if ai\u2009=\u20090, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be \u00ab-1\u00bb.Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai\u2009=\u20090) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!", "input_spec": "The first line contains two integers n, d (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009d\u2009\u2264\u2009109) \u2014the number of days and the money limitation. The second line contains n integer numbers a1,\u2009a2,\u2009... an (\u2009-\u2009104\u2009\u2264\u2009ai\u2009\u2264\u2009104), where ai represents the transaction in i-th day.", "output_spec": "Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.", "sample_inputs": ["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"], "sample_outputs": ["0", "-1", "2"], "notes": null}, "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 val Array(n, d) = readLongLine()\n val transactions = readLongLine()\n\n val nint = n.toInt\n val sums : Array[Long] = Array.ofDim(nint)\n var i = 1\n sums(0) = transactions(0)\n while (i < sums.length) {\n sums(i) = transactions(i) + sums(i - 1)\n i += 1\n }\n val greatestToCome : Array[Long] = Array.ofDim(nint)\n greatestToCome(nint - 1) = sums(nint - 1)\n i = nint - 2\n while (i >= 0) {\n greatestToCome(i) = Math.max(greatestToCome(i + 1), sums(i))\n i -= 1\n }\n\n var days = 0\n var totalDeposited = 0L\n var balance = 0L\n i = 0\n while (i < transactions.length) {\n val t = transactions(i)\n if (t == 0 && balance < 0) {\n val toDeposit = d - (greatestToCome(i) + totalDeposited)\n balance += toDeposit\n if (balance < 0) {\n println(-1)\n return\n }\n totalDeposited += toDeposit\n days += 1\n }\n balance += t\n if (balance > d) {\n println(-1)\n return\n }\n i += 1\n }\n println(days)\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 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 val Array(n, d) = readLongLine()\n val transactions = readLongLine()\n\n val nint = n.toInt\n var greatestToCome : Array[Long] = Array.ofDim(nint)\n greatestToCome(nint - 1) = transactions(nint - 1)\n var i = nint - 2\n while (i >= 0) {\n greatestToCome(i) = Math.max(greatestToCome(i + 1), transactions(i))\n i -= 1\n }\n\n var days = 0\n var totalDeposited = 0L\n var balance = 0L\n i = 0\n while (i < transactions.length) {\n val t = transactions(i)\n if (t == 0 && balance < 0) {\n val toDeposit = d - (greatestToCome(i) + totalDeposited) - balance\n balance += toDeposit\n if (balance < 0) {\n println(-1)\n return\n }\n totalDeposited += toDeposit\n days += 1\n }\n balance += t\n if (balance > d) {\n println(-1)\n return\n }\n i += 1\n }\n println(days)\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}"}, {"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 val Array(n, d) = readLongLine()\n val transactions = readLongLine()\n\n val nint = n.toInt\n var greatestToCome : Array[Long] = Array.ofDim(nint)\n greatestToCome(nint - 1) = transactions(nint - 1)\n var i = nint - 2\n while (i >= 0) {\n greatestToCome(i) = Math.max(greatestToCome(i + 1), transactions(i))\n i -= 1\n }\n\n var days = 0\n var totalDeposited = 0L\n var balance = 0L\n i = 0\n while (i < transactions.length) {\n val t = transactions(i)\n if (t == 0 && balance < 0) {\n val toDeposit = d - (greatestToCome(i) + totalDeposited) - balance\n balance += toDeposit\n if (balance < 0) {\n println(-1)\n return\n }\n totalDeposited += toDeposit\n days += 1\n }\n balance += t\n i += 1\n }\n println(days)\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": "c112321ea5e5603fd0c95c4f01808db1"} {"nl": {"description": "Victor has a 24-hour clock that shows the time in the format \"HH:MM\" (00 $$$\\le$$$ HH $$$\\le$$$ 23, 00 $$$\\le$$$ MM $$$\\le$$$ 59). He looks at the clock every $$$x$$$ minutes, and the clock is currently showing time $$$s$$$. How many different palindromes will Victor see in total after looking at the clock every $$$x$$$ minutes, the first time being at time $$$s$$$?For example, if the clock starts out as 03:12 and Victor looks at the clock every $$$360$$$ minutes (i.e. every $$$6$$$ hours), then he will see the times 03:12, 09:12, 15:12, 21:12, 03:12, and the times will continue to repeat. Here the time 21:12 is the only palindrome he will ever see, so the answer is $$$1$$$.A palindrome is a string that reads the same backward as forward. For example, the times 12:21, 05:50, 11:11 are palindromes but 13:13, 22:10, 02:22 are not.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The description of each test case follows. The only line of each test case contains a string $$$s$$$ of length $$$5$$$ with the format \"HH:MM\" where \"HH\" is from \"00\" to \"23\" and \"MM\" is from \"00\" to \"59\" (both \"HH\" and \"MM\" have exactly two digits) and an integer $$$x$$$ ($$$1 \\leq x \\leq 1440$$$)\u00a0\u2014 the number of minutes Victor takes to look again at the clock.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the number of different palindromes Victor will see if he looks at the clock every $$$x$$$ minutes starting from time $$$s$$$.", "sample_inputs": ["6\n\n03:12 360\n\n00:00 1\n\n13:22 2\n\n15:15 10\n\n11:11 1440\n\n22:30 27"], "sample_outputs": ["1\n16\n10\n0\n1\n1"], "notes": "NoteThe first test case is explained in the statement."}, "positive_code": [{"source_code": "\r\nimport scala.collection.mutable\r\nimport scala.io.StdIn\r\nimport scala.math.BigDecimal.double2bigDecimal\r\n\r\nobject Main {\r\n\r\n def isPalindrome(currentTime: (Int, Int)): Boolean = {\r\n val hour = currentTime._1.toString.reverse.padTo(2, '0').reverse\r\n val minute = currentTime._2.toString.reverse.padTo(2, '0').reverse\r\n \r\n\r\n (hour + minute).reverse == (hour + minute)\r\n }\r\n\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 Array(timeS, minutesS) = StdIn.readLine().split(\" \")\r\n val Array(hourS, minuteS) = timeS.split(\":\")\r\n\r\n val hour = hourS.toInt\r\n val minute = minuteS.toInt\r\n val minutes = minutesS.toInt\r\n\r\n val seen = mutable.Set[(Int, Int)]()\r\n\r\n var currentTime = (hour, minute)\r\n var palindromes = 0\r\n\r\n while(!seen.contains(currentTime)) {\r\n seen.add(currentTime)\r\n if(isPalindrome(currentTime)) {\r\n palindromes += 1\r\n }\r\n val newMinutes = (currentTime._2 + minutes) % 60\r\n val newHours = (currentTime._1 + (currentTime._2 + minutes)/60) % 24\r\n\r\n currentTime = (newHours, newMinutes)\r\n }\r\n\r\n println(palindromes)\r\n }\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "c601769062070ab983e1d4c9942cdd39"} {"nl": {"description": "A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li,\u2009ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a,\u2009b] covers segment [c,\u2009d], if they meet this condition a\u2009\u2264\u2009c\u2009\u2264\u2009d\u2009\u2264\u2009b. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) \u2014 the borders of the i-th segment. It is guaranteed that no two segments coincide.", "output_spec": "Print a single integer \u2014 the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.", "sample_inputs": ["3\n1 1\n2 2\n3 3", "6\n1 5\n2 3\n1 10\n7 10\n7 7\n10 10"], "sample_outputs": ["-1", "3"], "notes": null}, "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().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}"}, {"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"} {"nl": {"description": "One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords \u2014 strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords \"a\", \"b\", \"ab\", \"d\", then passwords \"a\", \"b\", \"ab\" are equivalent to each other, but the password \"d\" is not equivalent to any other password from list. In other words, if: admin's password is \"b\", then you can access to system by using any of this passwords: \"a\", \"b\", \"ab\"; admin's password is \"d\", then you can access to system by using only \"d\". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.", "input_spec": "The first line contain integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 number of passwords in the list. Next $$$n$$$ lines contains passwords from the list \u2013 non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters.", "output_spec": "In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.", "sample_inputs": ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"], "sample_outputs": ["2", "1", "1"], "notes": "NoteIn the second example hacker need to use any of the passwords to access the system."}, "positive_code": [{"source_code": "import scala.collection.immutable.BitSet\nimport scala.collection.mutable\nimport scala.collection.parallel.immutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n def long(xs: Iterator[Int]): Long = {\n var y = 0L\n for (x <- xs) y |= (1L << x)\n y\n }\n\n val n = nextInt\n val ps = Array.fill(n)(long(nextLine.iterator.map(_ - 'a')))\n\n val xs = mutable.Set.empty[Long]\n\n for (p <- ps) {\n var pp = p\n for (x <- xs) {\n if ((x & pp) != 0) {\n pp |= x\n xs.remove(x)\n }\n }\n xs += pp\n }\n\n out.println(xs.size)\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": "00db0111fd80ce1820da2af07a6cb8f1"} {"nl": {"description": "Fox Ciel has a board with n rows and n columns. So, the board consists of n\u2009\u00d7\u2009n cells. Each cell contains either a symbol '.', or a symbol '#'.A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.Please, tell Ciel if she can draw the crosses in the described way.", "input_spec": "The first line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the size of the board. Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.", "output_spec": "Output a single line with \"YES\" if Ciel can draw the crosses in the described way. Otherwise output a single line with \"NO\".", "sample_inputs": ["5\n.#...\n####.\n.####\n...#.\n.....", "4\n####\n####\n####\n####", "6\n.#....\n####..\n.####.\n.#.##.\n######\n.#..#.", "6\n.#..#.\n######\n.####.\n.####.\n######\n.#..#.", "3\n...\n...\n..."], "sample_outputs": ["YES", "NO", "YES", "NO", "YES"], "notes": "NoteIn example 1, you can draw two crosses. The picture below shows what they look like.In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all."}, "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 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"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "b08ba52eb4c36b75dacf56dad6c2e670"} {"nl": {"description": "Consider the array $$$a$$$ composed of all the integers in the range $$$[l, r]$$$. For example, if $$$l = 3$$$ and $$$r = 7$$$, then $$$a = [3, 4, 5, 6, 7]$$$.Given $$$l$$$, $$$r$$$, and $$$k$$$, is it possible for $$$\\gcd(a)$$$ to be greater than $$$1$$$ after doing the following operation at most $$$k$$$ times? Choose $$$2$$$ numbers from $$$a$$$. Permanently remove one occurrence of each of them from the array. Insert their product back into $$$a$$$. $$$\\gcd(b)$$$ denotes the greatest common divisor (GCD) of the integers in $$$b$$$.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u2014 the number of test cases. The description of test cases follows. The input for each test case consists of a single line containing $$$3$$$ non-negative integers $$$l$$$, $$$r$$$, and $$$k$$$ ($$$1 \\leq l \\leq r \\leq 10^9, \\enspace 0 \\leq k \\leq r - l$$$).", "output_spec": "For each test case, print \"YES\" if it is possible to have the GCD of the corresponding array greater than $$$1$$$ by performing at most $$$k$$$ operations, and \"NO\" otherwise (case insensitive).", "sample_inputs": ["9\n1 1 0\n3 5 1\n13 13 0\n4 4 0\n3 7 4\n4 10 3\n2 4 0\n1 7 3\n1 5 3"], "sample_outputs": ["NO\nNO\nYES\nYES\nYES\nYES\nNO\nNO\nYES"], "notes": "NoteFor the first test case, $$$a = [1]$$$, so the answer is \"NO\", since the only element in the array is $$$1$$$.For the second test case the array is $$$a = [3, 4, 5]$$$ and we have $$$1$$$ operation. After the first operation the array can change to: $$$[3, 20]$$$, $$$[4, 15]$$$ or $$$[5, 12]$$$ all of which having their greatest common divisor equal to $$$1$$$ so the answer is \"NO\".For the third test case, $$$a = [13]$$$, so the answer is \"YES\", since the only element in the array is $$$13$$$.For the fourth test case, $$$a = [4]$$$, so the answer is \"YES\", since the only element in the array is $$$4$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "9363df0735005832573ef4d17b6a8302"} {"nl": {"description": "Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r,\u2009c). The tail of the snake is located at (1,\u20091), then it's body extends to (1,\u2009m), then goes down 2 rows to (3,\u2009m), then goes left to (3,\u20091) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.", "input_spec": "The only line contains two integers: n and m (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950). n is an odd number.", "output_spec": "Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.", "sample_inputs": ["3 3", "3 4", "5 3", "9 9"], "sample_outputs": ["###\n..#\n###", "####\n...#\n####", "###\n..#\n###\n#..\n###", "#########\n........#\n#########\n#........\n#########\n........#\n#########\n#........\n#########"], "notes": null}, "positive_code": [{"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}"}, {"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": "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"}, {"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"}], "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"} {"nl": {"description": "Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t\u2009+\u20091, unless there are more travellers arriving at time t\u2009+\u20091 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.", "input_spec": "The first line contains two space-separated integers: n (2\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of planets in the galaxy, and m (0\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection. Then n lines follow: the i-th line contains an integer ki (0\u2009\u2264\u2009ki\u2009\u2264\u2009105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0\u2009\u2264\u2009tij\u2009<\u2009109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.", "output_spec": "Print a single number \u2014 the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.", "sample_inputs": ["4 6\n1 2 2\n1 3 3\n1 4 8\n2 3 4\n2 4 5\n3 4 3\n0\n1 3\n2 3 4\n0", "3 1\n1 2 3\n0\n1 3\n0"], "sample_outputs": ["7", "-1"], "notes": "NoteIn the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then \u2014 to planet 4, then he spends a total of only 2\u2009+\u20095\u2009=\u20097 seconds.In the second sample one can't get from planet 1 to planet 3 by moving through stargates."}, "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"}, {"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"} {"nl": {"description": "You are given n integers a1,\u2009a2,\u2009...,\u2009an. Find the number of pairs of indexes i,\u2009j (i\u2009<\u2009j) that ai\u2009+\u2009aj is a power of 2 (i. e. some integer x exists so that ai\u2009+\u2009aj\u2009=\u20092x).", "input_spec": "The first line contains the single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of integers. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print the number of pairs of indexes i,\u2009j (i\u2009<\u2009j) that ai\u2009+\u2009aj is a power of 2.", "sample_inputs": ["4\n7 3 2 1", "3\n1 1 1"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first example the following pairs of indexes include in answer: (1,\u20094) and (2,\u20094).In the second example all pairs of indexes (i,\u2009j) (where i\u2009<\u2009j) include in answer."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There is a square field of size $$$n \\times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \\begin{matrix} . & . & * & . \\\\ . & . & . & . \\\\ * & . & . & . \\\\ . & . & . & . \\\\ \\end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \\begin{matrix} * & . & * & . \\\\ . & . & . & . \\\\ * & . & * & . \\\\ . & . & . & . \\\\ \\end{matrix} $$$$$$If there are several possible solutions, then print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 400$$$)\u00a0\u2014 the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.", "output_spec": "For each test case, output $$$n$$$ rows of $$$n$$$ characters\u00a0\u2014 a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.", "sample_inputs": ["6\n4\n..*.\n....\n*...\n....\n2\n*.\n.*\n2\n.*\n.*\n3\n*.*\n...\n...\n5\n.....\n..*..\n.....\n.*...\n.....\n4\n....\n....\n*...\n*..."], "sample_outputs": ["*.*.\n....\n*.*.\n....\n**\n**\n**\n**\n*.*\n*.*\n...\n.....\n.**..\n.....\n.**..\n.....\n....\n....\n**..\n**.."], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "During a New Year special offer the \"Sudislavl Bars\" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar \"Mosquito Shelter\". Of course, all the promocodes differ.As the \"Mosquito Shelter\" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k\u2009=\u20090 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value \"123465\" contains two errors relative to promocode \"123456\". Regardless of the number of errors the entered value consists of exactly six digits.", "input_spec": "The first line of the output contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of promocodes. Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit \"0\".", "output_spec": "Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.", "sample_inputs": ["2\n000000\n999999", "6\n211111\n212111\n222111\n111111\n112111\n121111"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample k\u2009<\u20093, so if a bar customer types in value \"090909\", then it will be impossible to define which promocode exactly corresponds to it."}, "positive_code": [{"source_code": "object C extends App {\n val Array(n) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val arr = (1 to n).map(_ => scala.io.StdIn.readLine())\n\n val range = (0 to 5)\n def diff(a: String, b: String) =\n range.count(i => a(i) != b(i))\n\n val z = for {\n q <- arr\n w <- arr\n if q != w\n } yield diff(q, w)\n\n if (n == 1) println(6)\n else println(Seq((z.min - 1) / 2, 0).max)\n}\n"}], "negative_code": [], "src_uid": "0151c42a653421653486c93efe87572d"} {"nl": {"description": "One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$): the number of grids of the games. Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$): the size of the side of the grid of the game. ", "output_spec": "For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.", "sample_inputs": ["2\n3\n4"], "sample_outputs": ["2\n3"], "notes": "NoteFor $$$3\\times3$$$ grid ponies can make two following moves: "}, "positive_code": [{"source_code": "object CF1393A 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 println(n/2 + 1)\n }\n}"}], "negative_code": [], "src_uid": "eb39ac8d703516c7f81f95a989791b21"} {"nl": {"description": "The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \\le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 500$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$).", "output_spec": "For each query, print such smallest integer $$$m$$$ (where $$$n \\le m$$$) that $$$m$$$ is a good number.", "sample_inputs": ["7\n1\n2\n6\n13\n14\n3620\n10000"], "sample_outputs": ["1\n3\n9\n13\n27\n6561\n19683"], "notes": null}, "positive_code": [{"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}"}, {"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 _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"}, {"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"} {"nl": {"description": "A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is \"abc\". If we take two such headings and glue them one to the other one, we get \"abcabc\". If we erase the letters on positions 1 and 5, we get a word \"bcac\".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?", "input_spec": "The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1\u2009\u2264\u2009|s1|\u2009\u2264\u2009104,\u20091\u2009\u2264\u2009|s2|\u2009\u2264\u2009106).", "output_spec": "If it is impossible to get the word s2 in the above-described manner, print \"-1\" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.", "sample_inputs": ["abc\nxyz", "abcd\ndabc"], "sample_outputs": ["-1", "2"], "notes": null}, "positive_code": [{"source_code": "import java.util._\nimport java.io._\n\nimport scala.collection.mutable\n\n\nobject Tmp extends App {\n val sc = new Scanner(System.in)\n val s1 = sc.next()\n val s2 = sc.next()\n\n val index = Array.fill(26)(mutable.ArrayBuffer[Int]())\n\n s1.indices.foreach(i => {\n index(s1(i) - 'a').+=(i)\n })\n\n var ans = 1;\n\n def find(c: Char, f: Int): Int = {\n val ch = c - 'a'\n def bs(st: Int, en: Int): Int = {\n if (en < st) {\n -1\n } else {\n val m = (st + en) / 2\n\n val mv = index(ch)(m)\n val mv1 = if (m == 0) -1 else index(ch)(m-1) \n if (mv >= f && mv1 < f) {\n mv\n } else if (f > mv) {\n bs(m + 1, en)\n } else {\n bs(st, m)\n }\n }\n }\n\n bs(0, index(ch).size - 1)\n }\n\n var st = 0\n s2.foreach(c => {\n val t = find(c, st)\n if (t == -1) {\n ans = ans + 1\n val t1 = find(c, 0)\n if (t1 == -1) {\n print(-1)\n System.exit(0)\n } else {\n st = t1 + 1\n }\n } else {\n st = t + 1\n }\n })\n\n print(ans)\n}\n"}], "negative_code": [{"source_code": "import java.util._\nimport java.io._\n\nimport scala.collection.mutable\n\n\nobject Tmp extends App {\n val sc = new Scanner(System.in)\n val s1 = sc.next()\n val s2 = sc.next()\n\n val index = Array.fill(26)(mutable.ArrayBuffer[Int]())\n\n s1.indices.foreach(i => {\n index(s1(i) - 'a').+=(i)\n })\n\n var ans = 1;\n\n def find(c: Char, f: Int): Int = {\n val ch = c - 'a'\n def bs(st: Int, en: Int): Int = {\n if (en < st) {\n -1\n } else {\n val m = (st + en) / 2\n\n val mv = index(ch)(m)\n val mv1 = if (m == 0) -1 else index(ch)(m-1) \n if (mv >= f && mv1 < f) {\n mv\n } else if (f > mv) {\n bs(m + 1, en)\n } else {\n bs(st, m)\n }\n }\n }\n\n bs(0, index(ch).size - 1)\n }\n\n var st = 0\n s2.foreach(c => {\n val t = find(c, st)\n if (t == -1) {\n ans = ans + 1\n val t1 = find(c, 0)\n if (t1 == -1) {\n System.exit(0)\n } else {\n st = t1 + 1\n }\n } else {\n st = t + 1\n }\n })\n\n print(ans)\n}\n"}], "src_uid": "1b83529ea4057c76ae8483f8aa506c56"} {"nl": {"description": "Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q\u2009=\u2009q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string \"zyx\", \"xzy\", \"yxz\". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s\u2009=\u2009s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli\u2009+\u20091... sri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li,\u2009ri) determine if the algorithm works correctly on this test or not.", "input_spec": "The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n).", "output_spec": "For each test, print \"YES\" (without the quotes) if the algorithm works correctly on the corresponding test and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO"], "notes": "NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string \"xzyx\" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. "}, "positive_code": [{"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\n val s = readLine\n val n = s.length\n val m = readInt\n \n val xs, ys, zs = Array.ofDim[Int](n + 1)\n var xc, yc, zc = 0\n \n for (i <- s.indices) {\n s(i) match {\n case 'x' => xc += 1\n case 'y' => yc += 1\n case 'z' => zc += 1\n }\n xs(i + 1) = xc\n ys(i + 1) = yc\n zs(i + 1) = zc\n }\n \n for (i <- 1 to m) {\n val Array(l, r) = readInts(2)\n xc = xs(r) - xs(l - 1) \n yc = ys(r) - ys(l - 1) \n zc = zs(r) - zs(l - 1)\n val min = xc min yc min zc\n val max = xc max yc max zc\n \n println(if (r - l < 2 || max <= min + 1) \"YES\" else \"NO\")\n }\n\n}"}], "negative_code": [], "src_uid": "4868cbb812d222ffababb4103210a3f1"} {"nl": {"description": "On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1\u2009+\u2009vf2\u2009+\u2009...\u2009+\u2009vfk energy for removing part i where f1,\u2009f2,\u2009...,\u2009fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u20091000; 0\u2009\u2264\u2009m\u2009\u2264\u20092000). The second line contains n integers: v1,\u2009v2,\u2009...,\u2009vn (0\u2009\u2264\u2009vi\u2009\u2264\u2009105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n;\u00a0xi\u2009\u2260\u2009yi). Consider all the parts are numbered from 1 to n.", "output_spec": "Output the minimum total energy the child should spend to remove all n parts of the toy.", "sample_inputs": ["4 3\n10 20 30 40\n1 4\n1 2\n2 3", "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4", "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4"], "sample_outputs": ["40", "400", "160"], "notes": "NoteOne of the optimal sequence of actions in the first sample is: First, remove part 3, cost of the action is 20. Then, remove part 2, cost of the action is 10. Next, remove part 4, cost of the action is 10. At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20\u2009+\u200910\u2009+\u200910\u2009+\u20090\u2009=\u200940, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Little C loves number \u00ab3\u00bb very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.", "input_spec": "A single line containing one integer $$$n$$$ ($$$3 \\leq n \\leq 10^9$$$) \u2014 the integer Little C has.", "output_spec": "Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.", "sample_inputs": ["3", "233"], "sample_outputs": ["1 1 1", "77 77 79"], "notes": null}, "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 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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Vasya is an administrator of a public page of organization \"Mouse and keyboard\" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000)\u00a0\u2014 the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500\u2009000.", "output_spec": "Print the resulting hashtags in any of the optimal solutions.", "sample_inputs": ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"], "sample_outputs": ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"], "notes": "NoteWord a1,\u2009a2,\u2009...,\u2009am of length m is lexicographically not greater than word b1,\u2009b2,\u2009...,\u2009bk of length k, if one of two conditions hold: at first position i, such that ai\u2009\u2260\u2009bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and m\u2009\u2264\u2009k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two."}, "positive_code": [{"source_code": "//package solutions\n\nimport java.io.InputStream\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * @author traff\n */\n\n\nobject SolTaskD extends App {\n\n class FastScanner() {\n\n import java.io.{BufferedReader, FileReader, 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 def this(is: InputStream) {\n this()\n br = new BufferedReader(new InputStreamReader(is))\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\n override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n // run(new FastScanner(), out)\n run(new Scanner(System.in), out)\n out.close()\n }\n\n // def run(s: FastScanner, out: PrintWriter): Unit = {\n def run(s: Scanner, out: PrintWriter): Unit = {\n val n = s.nextLine().toInt\n val a = new Array[String](n)\n\n\n for (i <- 1 to n) {\n a(i - 1) = s.nextLine()\n }\n\n\n for (i <- 1 until n) {\n var j = 1\n val a1 = a(n - i - 1)\n val a2 = a(n - i)\n while (j < math.min(a1.length, a2.length) && a1(j) == a2(j)) {\n j += 1\n }\n\n\n if (j == a2.length || ( j < a1.length && a1(j) > a2(j))) {\n a(n - i - 1) = a1.substring(0, j)\n } else {\n a(n - i - 1) = a1\n }\n }\n\n\n for (i <- 0 until n) {\n out.println(a(i))\n }\n\n }\n}\n"}], "negative_code": [], "src_uid": "27baf9b1241c0f8e3a2037b18f39fe34"} {"nl": {"description": "Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.", "input_spec": "The first line contains integer q (1\u2009\u2264\u2009q\u2009\u2264\u20091000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.", "output_spec": "In the first line output the integer n \u2014 the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.", "sample_inputs": ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"], "sample_outputs": ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect\" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1\u2009\u2264\u2009j\u2009\u2264\u2009m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1)\u2009+\u2009pos(ai2)\u2009+\u2009...\u2009+\u2009pos(aim) for the i-th customer.When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.Your task is to calculate the total time it takes for Ayush to process all the orders.You can assume that the market has endless stock.", "input_spec": "The first line contains three integers n, m and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009k) \u2014 the number of users, the number of items each user wants to buy and the total number of items at the market. The next line contains k distinct integers pl (1\u2009\u2264\u2009pl\u2009\u2264\u2009k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k. Each of the next n lines contains m distinct integers aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009k) \u2014 the order of the i-th person.", "output_spec": "Print the only integer t \u2014 the total time needed for Ayush to process all the orders.", "sample_inputs": ["2 2 5\n3 4 1 2 5\n1 5\n3 1"], "sample_outputs": ["14"], "notes": "NoteCustomer 1 wants the items 1 and 5.pos(1)\u2009=\u20093, so the new positions are: [1,\u20093,\u20094,\u20092,\u20095].pos(5)\u2009=\u20095, so the new positions are: [5,\u20091,\u20093,\u20094,\u20092].Time taken for the first customer is 3\u2009+\u20095\u2009=\u20098.Customer 2 wants the items 3 and 1.pos(3)\u2009=\u20093, so the new positions are: [3,\u20095,\u20091,\u20094,\u20092].pos(1)\u2009=\u20093, so the new positions are: [1,\u20093,\u20095,\u20094,\u20092].Time taken for the second customer is 3\u2009+\u20093\u2009=\u20096.Total time is 8\u2009+\u20096\u2009=\u200914.Formally pos(x) is the index of x in the current row."}, "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 var data = in.next().split(' ').map(_.toInt)\n println((1 to n).map { _ =>\n in.next().split(' ').map(_.toInt).map {\n i =>\n val index = data.indexOf(i)\n (index until 0 by -1).foreach { j =>\n data(j) = data(j - 1)\n }\n data(0) = i\n index + 1\n }.sum\n }.sum)\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 var data = in.next().split(' ').map(_.toInt)\n println((1 to m).map { _ =>\n in.next().split(' ').map(_.toInt).map {\n i =>\n val index = data.indexOf(i)\n (index until 0 by -1).foreach { j =>\n data(j) = data(j - 1)\n }\n data(0) = i\n index + 1\n }.sum\n }.sum)\n}"}], "src_uid": "39fd7843558ed2aa6b8c997c2b8a1fad"} {"nl": {"description": "Black is gifted with a Divine array $$$a$$$ consisting of $$$n$$$ ($$$1 \\le n \\le 2000$$$) integers. Each position in $$$a$$$ has an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable transformation.The transformation consists of infinite steps. Array $$$a$$$ changes at the $$$i$$$-th step in the following way: for every position $$$j$$$, $$$a_j$$$ becomes equal to the number of occurrences of $$$a_j$$$ in $$$a$$$ before starting this step.Here is an example to help you understand the process better: Initial array:$$$2$$$ $$$1$$$ $$$1$$$ $$$4$$$ $$$3$$$ $$$1$$$ $$$2$$$After the $$$1$$$-st step:$$$2$$$ $$$3$$$ $$$3$$$ $$$1$$$ $$$1$$$ $$$3$$$ $$$2$$$After the $$$2$$$-nd step:$$$2$$$ $$$3$$$ $$$3$$$ $$$2$$$ $$$2$$$ $$$3$$$ $$$2$$$After the $$$3$$$-rd step:$$$4$$$ $$$3$$$ $$$3$$$ $$$4$$$ $$$4$$$ $$$3$$$ $$$4$$$...... In the initial array, we had two $$$2$$$-s, three $$$1$$$-s, only one $$$4$$$ and only one $$$3$$$, so after the first step, each element became equal to the number of its occurrences in the initial array: all twos changed to $$$2$$$, all ones changed to $$$3$$$, four changed to $$$1$$$ and three changed to $$$1$$$.The transformation steps continue forever.You have to process $$$q$$$ queries: in each query, Black is curious to know the value of $$$a_x$$$ after the $$$k$$$-th step of transformation.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 2000$$$)\u00a0\u2014 the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the initial values of array $$$a$$$. The third line of each test case contains a single integer $$$q$$$ ($$$1 \\le q \\le 100\\,000$$$)\u00a0\u2014 the number of queries. Next $$$q$$$ lines contain the information about queries\u00a0\u2014 one query per line. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$k_i$$$ ($$$1 \\le x_i \\le n$$$; $$$0 \\le k_i \\le 10^9$$$), meaning that Black is asking for the value of $$$a_{x_i}$$$ after the $$$k_i$$$-th step of transformation. $$$k_i = 0$$$ means that Black is interested in values of the initial array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$ and the sum of $$$q$$$ over all test cases doesn't exceed $$$100\\,000$$$.", "output_spec": "For each test case, print $$$q$$$ answers. The $$$i$$$-th of them should be the value of $$$a_{x_i}$$$ after the $$$k_i$$$-th step of transformation. It can be shown that the answer to each query is unique.", "sample_inputs": ["2\n7\n2 1 1 4 3 1 2\n4\n3 0\n1 1\n2 2\n6 1\n2\n1 1\n2\n1 0\n2 1000000000"], "sample_outputs": ["1\n2\n3\n3\n1\n2"], "notes": "NoteThe first test case was described ih the statement. It can be seen that: $$$k_1 = 0$$$ (initial array): $$$a_3 = 1$$$; $$$k_2 = 1$$$ (after the $$$1$$$-st step): $$$a_1 = 2$$$; $$$k_3 = 2$$$ (after the $$$2$$$-nd step): $$$a_2 = 3$$$; $$$k_4 = 1$$$ (after the $$$1$$$-st step): $$$a_6 = 3$$$. For the second test case, Initial array:$$$1$$$ $$$1$$$After the $$$1$$$-st step:$$$2$$$ $$$2$$$After the $$$2$$$-nd step:$$$2$$$ $$$2$$$......It can be seen that: $$$k_1 = 0$$$ (initial array): $$$a_1 = 1$$$; $$$k_2 = 1000000000$$$: $$$a_2 = 2$$$; "}, "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 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 dp = Array.ofDim[Int](n+1, n+2)\n for (i <- 1 to n) {\n dp(i)(0) = readInt()\n }\n for (j <- 1 to n+1) {\n val cnt = new Array[Int](n+1)\n for (i <- 1 to n) {\n cnt(dp(i)(j-1)) += 1\n }\n for (i <- 1 to n) {\n dp(i)(j) = cnt(dp(i)(j-1))\n }\n }\n val q = readInt()\n for (i <- 1 to q) {\n val a = readInt()\n var b = readInt()\n if (b > n + 1)\n b = n+1\n writer.println(dp(a)(b))\n }\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "43009fe44c2b5905c8160ac7ae9c595a"} {"nl": {"description": "You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \\le i \\le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \\underline{3}, 2, \\underline{-2}, 1, -4, \\underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays: $$$[-1, 1, \\underline{3}, 2, \\underline{-2}, 1, -4, \\underline{0}]$$$; $$$[-4, -1, \\underline{3}, 2, \\underline{-2}, 1, 1, \\underline{0}]$$$; $$$[1, -1, \\underline{3}, 2, \\underline{-2}, 1, -4, \\underline{0}]$$$; $$$[1, 2, \\underline{3}, -1, \\underline{-2}, -4, 1, \\underline{0}]$$$; and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\\dots$$$, $$$p_n = a_1 + a_2 + \\dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \\le j \\le n$$$) such that $$$p_j < 0$$$. If there are no $$$j$$$ such that $$$p_j < 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^5 \\le a_i \\le 10^5$$$)\u00a0\u2014 the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \\dots, l_n$$$ ($$$0 \\le l_i \\le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.", "output_spec": "Print $$$n$$$ integers\u00a0\u2014 the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j < 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.", "sample_inputs": ["5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1"], "sample_outputs": ["1 2 3\n2 -3 4 -1\n-8 -6 1 4 4 7 -2\n-4 0 1 6 3\n-1 4 7 -8 10 -1"], "notes": "NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j < 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k < 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$."}, "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 { 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"}, {"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"} {"nl": {"description": "Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \\leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \\leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one.", "input_spec": "The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \\leq n \\leq 100\\,000$$$, $$$1 \\leq m \\leq 200\\,000$$$)\u00a0\u2014 the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq n$$$, $$$a_i \\neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide.", "output_spec": "Output one line\u00a0\u2014 \"Yes\" if the image is rotationally symmetrical, and \"No\" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower).", "sample_inputs": ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"], "sample_outputs": ["Yes", "Yes", "No", "Yes"], "notes": "NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val (a, b) = na2(M, -1)\n val D = divisors(N)\n debug(D)\n if (D.length == 1) {\n out.println(\"No\")\n return\n }\n\n val byLen = Array.fill[mutable.Set[Int]](N)(mutable.Set())\n REP(M) { i =>\n val lenCW = (b(i) - a(i) + N) % N\n val lenCCW = (a(i) - b(i) + N) % N\n if (lenCW <= lenCCW) {\n byLen(lenCW) += a(i)\n } else {\n byLen(lenCCW) += b(i)\n }\n }\n val byLen_ar = Array.ofDim[Array[Int]](N)\n REP(N) { i =>\n byLen_ar(i) = byLen(i).toArray\n }\n\n def ok(k: Int): Boolean = {\n REP(N) { i =>\n // \u4e2d\u592e\u3092\u901a\u308bsegment\u306f\u534a\u56de\u8ee2\u3067\u5fc5\u305asymmetry\n if (N % 2 == 0 && k == N / 2 && i == N / 2) {\n // \u30c1\u30a7\u30c3\u30af\u3057\u306a\u3044\n } else {\n REP(byLen_ar(i).length) { j =>\n val s = byLen_ar(i)(j)\n val t = (s + k) % N\n if (!byLen(i).contains(t)) return false\n }\n }\n }\n true\n }\n\n debug(byLen.mkString(\" \"))\n\n for {\n d <- D.dropRight(1)\n if ok(d)\n } {\n out.println(\"Yes\")\n return\n }\n out.println(\"No\")\n }\n\n /**\n * O(\u221ax)\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}"}], "negative_code": [], "src_uid": "dd7a7a4e5feb50ab6abb93d90c559c2b"} {"nl": {"description": "In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x\u2009+\u2009d, if such a camel exists.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the amount of camels in the zoo. Each of the following n lines contains two integers xi and di (\u2009-\u2009104\u2009\u2264\u2009xi\u2009\u2264\u2009104,\u20091\u2009\u2264\u2009|di|\u2009\u2264\u20092\u00b7104) \u2014 records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.", "output_spec": "If there are two camels, which spitted at each other, output YES. Otherwise, output NO.", "sample_inputs": ["2\n0 1\n1 -1", "3\n0 1\n1 1\n2 -2", "5\n2 -10\n3 10\n0 5\n5 -5\n10 1"], "sample_outputs": ["YES", "NO", "YES"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "d7dc61a8f3b0091320b96cedd1f4f0a7"} {"nl": {"description": "Two T-shirt sizes are given: $$$a$$$ and $$$b$$$. The T-shirt size is either a string M or a string consisting of several (possibly zero) characters X and one of the characters S or L.For example, strings M, XXL, S, XXXXXXXS could be the size of some T-shirts. And the strings XM, LL, SX are not sizes.The letter M stands for medium, S for small, L for large. The letter X refers to the degree of size (from eXtra). For example, XXL is extra-extra-large (bigger than XL, and smaller than XXXL).You need to compare two given sizes of T-shirts $$$a$$$ and $$$b$$$.The T-shirts are compared as follows: any small size (no matter how many letters X) is smaller than the medium size and any large size; any large size (regardless of the number of letters X) is larger than the medium size and any small size; the more letters X before S, the smaller the size; the more letters X in front of L, the larger the size. For example: XXXS < XS XXXL > XL XL > M XXL = XXL XXXXXS < M XL > XXXS ", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Each test case consists of one line, in which $$$a$$$ and $$$b$$$ T-shirt sizes are written. The lengths of the strings corresponding to the T-shirt sizes do not exceed $$$50$$$. It is guaranteed that all sizes are correct.", "output_spec": "For each test case, print on a separate line the result of comparing $$$a$$$ and $$$b$$$ T-shirt sizes (lines \"<\", \">\" or \"=\" without quotes).", "sample_inputs": ["6\n\nXXXS XS\n\nXXXL XL\n\nXL M\n\nXXL XXL\n\nXXXXXS M\n\nL M"], "sample_outputs": ["<\n>\n>\n=\n<\n>"], "notes": null}, "positive_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) != 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}"}, {"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"} {"nl": {"description": "You have an array $$$a_1, a_2, \\dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \\neq j$$$; $$$i \\neq k$$$; $$$j \\neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i.\u00a0e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \\le n \\le 100$$$; $$$1 \\le d \\le 100$$$)\u00a0\u2014 the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$)\u00a0\u2014 the array $$$a$$$.", "output_spec": "For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).", "sample_inputs": ["3\n5 3\n2 3 2 5 4\n3 4\n2 4 4\n5 4\n2 1 5 3 6"], "sample_outputs": ["NO\nYES\nYES"], "notes": "NoteIn the first test case, we can prove that we can't make all $$$a_i \\le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Vasya has got $$$n$$$ books, numbered from $$$1$$$ to $$$n$$$, arranged in a stack. The topmost book has number $$$a_1$$$, the next one \u2014 $$$a_2$$$, and so on. The book at the bottom of the stack has number $$$a_n$$$. All numbers are distinct.Vasya wants to move all the books to his backpack in $$$n$$$ steps. During $$$i$$$-th step he wants to move the book number $$$b_i$$$ into his backpack. If the book with number $$$b_i$$$ is in the stack, he takes this book and all the books above the book $$$b_i$$$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $$$[1, 2, 3]$$$ (book $$$1$$$ is the topmost), and Vasya moves the books in the order $$$[2, 1, 3]$$$, then during the first step he will move two books ($$$1$$$ and $$$2$$$), during the second step he will do nothing (since book $$$1$$$ is already in the backpack), and during the third step \u2014 one book (the book number $$$3$$$). Note that $$$b_1, b_2, \\dots, b_n$$$ are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.", "input_spec": "The first line contains one integer $$$n~(1 \\le n \\le 2 \\cdot 10^5)$$$ \u2014 the number of books in the stack. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n~(1 \\le a_i \\le n)$$$ denoting the stack of books. The third line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n~(1 \\le b_i \\le n)$$$ denoting the steps Vasya is going to perform. All numbers $$$a_1 \\dots a_n$$$ are distinct, the same goes for $$$b_1 \\dots b_n$$$.", "output_spec": "Print $$$n$$$ integers. The $$$i$$$-th of them should be equal to the number of books Vasya moves to his backpack during the $$$i$$$-th step.", "sample_inputs": ["3\n1 2 3\n2 1 3", "5\n3 1 4 2 5\n4 5 1 3 2", "6\n6 5 4 3 2 1\n6 5 3 4 2 1"], "sample_outputs": ["2 0 1", "3 2 0 0 0", "1 1 2 0 1 1"], "notes": "NoteThe first example is described in the statement.In the second example, during the first step Vasya will move the books $$$[3, 1, 4]$$$. After that only books $$$2$$$ and $$$5$$$ remain in the stack ($$$2$$$ is above $$$5$$$). During the second step Vasya will take the books $$$2$$$ and $$$5$$$. After that the stack becomes empty, so during next steps Vasya won't move any books."}, "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 = na(N)\n val R = Array.ofDim[Int](N)\n rep(N) { i =>\n R(A(i) - 1) = i\n }\n\n var cur = -1\n\n val ans = ArrayBuffer[Int]()\n rep(N) { i =>\n val id = B(i) - 1\n val move = max(0, R(id) - cur)\n if (move > 0) cur = R(id)\n ans += move\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): 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": "82176739a1dd4fe85ec059058a00fbb9"} {"nl": {"description": "You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \\dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \\le a_{i_j} \\cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.", "output_spec": "Print a single integer \u2014 maximum number of problems in the contest satisfying the condition in the problem statement.", "sample_inputs": ["10\n1 2 5 6 7 10 21 23 24 49", "5\n2 10 50 110 250", "6\n4 7 12 100 150 199"], "sample_outputs": ["4", "1", "3"], "notes": "NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$."}, "positive_code": [{"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}"}, {"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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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"}, {"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": "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 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"}], "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"} {"nl": {"description": "You are given an undirected graph consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is $$$a_i$$$. Initially there are no edges in the graph.You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $$$x$$$ and $$$y$$$ is $$$a_x + a_y$$$ coins. There are also $$$m$$$ special offers, each of them is denoted by three numbers $$$x$$$, $$$y$$$ and $$$w$$$, and means that you can add an edge connecting vertices $$$x$$$ and $$$y$$$ and pay $$$w$$$ coins for it. You don't have to use special offers: if there is a pair of vertices $$$x$$$ and $$$y$$$ that has a special offer associated with it, you still may connect these two vertices paying $$$a_x + a_y$$$ coins for it.What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le m \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices in the graph and the number of special offers, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^{12}$$$) \u2014 the numbers written on the vertices. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$ and $$$w$$$ ($$$1 \\le x, y \\le n$$$, $$$1 \\le w \\le 10^{12}$$$, $$$x \\ne y$$$) denoting a special offer: you may add an edge connecting vertex $$$x$$$ and vertex $$$y$$$, and this edge will cost $$$w$$$ coins.", "output_spec": "Print one integer \u2014 the minimum number of coins you have to pay to make the graph connected.", "sample_inputs": ["3 2\n1 3 3\n2 3 5\n2 1 1", "4 0\n1 3 3 7", "5 4\n1 2 3 4 5\n1 2 8\n1 3 10\n1 4 7\n1 5 15"], "sample_outputs": ["5", "16", "18"], "notes": "NoteIn the first example it is possible to connect $$$1$$$ to $$$2$$$ using special offer $$$2$$$, and then $$$1$$$ to $$$3$$$ without using any offers.In next two examples the optimal answer may be achieved without using special offers."}, "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 = nal(N)\n val from, to = Array.ofDim[Int](M)\n val weight = Array.ofDim[Long](M)\n REP(M) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n weight(i) = nl()\n }\n\n val g = packWUGraph(N, from, to, weight)\n\n val B = A.zipWithIndex\n Sorting.quickSort(B)(Ordering.by(_._1))\n\n val ms = B(0)._1\n val v0 = B(0)._2\n\n // \u6700\u521dv0\u304c\u8ffd\u52a0\u3055\u308c\u3066\u3044\u308b\u3068\u601d\u3048\n val uf = new UnionFind(N)\n var ans = 0L\n\n val queue = new java.util.PriorityQueue[Edge]() // 0 -> to\n // v0\u3068\u306e\u30da\u30a2\u306e\u30a8\u30c3\u30b8\u3092\u5168\u90e8\u8ffd\u52a0\n REP(N - 1, 1) { i =>\n queue.add(Edge(B(i)._2, B(i)._1 + ms))\n }\n // v0\u304b\u3089\u751f\u3048\u3066\u308bedge\u8ffd\u52a0\n addEdge(v0)\n\n def addEdge(v: Int): Unit = {\n REP(g(v).length) { i =>\n val e = g(v)(i)\n if (uf.find(v0) != uf.find(e.to)) queue.add(e)\n }\n }\n\n var cnt = 0\n while(!queue.isEmpty) {\n val e = queue.poll()\n if (uf.find(v0) != uf.find(e.to)) {\n uf.unite(v0, e.to)\n ans += e.weight\n addEdge(e.to)\n cnt += 1\n }\n }\n\n assert(cnt == N - 1, s\"\u8ffd\u52a0\u3057\u305f\u30a8\u30c3\u30b8\u306e\u6570\u304c\u304a\u304b\u3057\u3044 $cnt\")\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 case class Edge(to: Int, weight: Long) extends Comparable[Edge] {\n override def compareTo(o: Edge): Int = java.lang.Long.compare(weight, o.weight)\n }\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Long]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\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 def solve(): Unit = {\n val N, M = ni()\n val A = nal(N)\n val from, to = Array.ofDim[Int](M)\n val weight = Array.ofDim[Long](M)\n REP(M) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n weight(i) = nl()\n }\n\n val g = packWUGraph(N, from, to, weight)\n\n val sorted = A.zipWithIndex\n Sorting.quickSort(sorted)(Ordering.by(_._1))\n\n val ms = sorted(0)._1\n\n var ans = 0L\n REP_r(N - 1, 1) { i =>\n var res = sorted(i)._1 + ms\n val es = g(sorted(i)._2)\n REP(es.length) { j =>\n if (j < i) {\n val e = es(j)\n res = min(res, e.weight)\n }\n }\n ans += res\n }\n\n out.println(ans)\n }\n\n case class Edge(to: Int, weight: Long)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Long]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\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, M = ni()\n val A = nal(N)\n val from, to = Array.ofDim[Int](M)\n val weight = Array.ofDim[Long](M)\n REP(M) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n weight(i) = nl()\n }\n\n val g = packWUGraph(N, from, to, weight)\n\n val sorted = A.zipWithIndex\n Sorting.quickSort(sorted)(Ordering.by(_._1))\n\n val ms = sorted(0)._1\n val rank = Array.ofDim[Int](N)\n REP(N) { i =>\n rank(sorted(i)._2) = i\n }\n\n var ans = 0L\n REP_r(N - 1, 1) { i =>\n val v = sorted(i)._2\n var res = sorted(i)._1 + ms\n val es = g(v)\n REP(es.length) { u =>\n if (rank(u) < rank(v)) {\n val e = es(u)\n res = min(res, e.weight)\n }\n }\n ans += res\n }\n\n out.println(ans)\n }\n\n case class Edge(to: Int, weight: Long)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Long]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\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, M = ni()\n val A = nal(N)\n val from, to = Array.ofDim[Int](M)\n val weight = Array.ofDim[Long](M)\n REP(M) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n weight(i) = nl()\n }\n\n val g = packWUGraph(N, from, to, weight)\n\n val sorted = A.zipWithIndex\n Sorting.quickSort(sorted)(Ordering.by(_._1))\n\n val ms = sorted(0)._1\n\n var ans = 0L\n REP_r(N - 1, 1) { i =>\n var res = A(i) + ms\n val es = g(i)\n REP(es.length) { j =>\n if (j < i) {\n val e = es(j)\n res = min(res, e.weight)\n }\n }\n ans += res\n }\n\n out.println(ans)\n }\n\n case class Edge(to: Int, weight: Long)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Long]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\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, M = ni()\n val A = nal(N)\n val from, to = Array.ofDim[Int](M)\n val weight = Array.ofDim[Long](M)\n REP(M) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n weight(i) = nl()\n }\n\n val g = packWUGraph(N, from, to, weight)\n\n val sorted = A.zipWithIndex\n Sorting.quickSort(sorted)(Ordering.by(_._1))\n\n val ms = sorted(0)._1\n\n var ans = 0L\n REP_r(N - 1, 1) { i =>\n val v = sorted(i)._2\n var res = sorted(i)._1 + ms\n val es = g(v)\n REP(es.length) { u =>\n if (u < v) {\n val e = es(u)\n res = min(res, e.weight)\n }\n }\n ans += res\n }\n\n out.println(ans)\n }\n\n case class Edge(to: Int, weight: Long)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Long]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i))\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i))\n }\n g\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": "e52ec2fa5bcf5d2027d57b0694b4e15a"} {"nl": {"description": "Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every x,\u2009y such that 1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n and ax,\u2009y\u2009\u2260\u20091, there should exist two indices s and t so that ax,\u2009y\u2009=\u2009ax,\u2009s\u2009+\u2009at,\u2009y, where ai,\u2009j denotes the integer in i-th row and j-th column.Help Okabe determine whether a given lab is good!", "input_spec": "The first line of input contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950)\u00a0\u2014 the size of the lab. The next n lines contain n space-separated integers denoting a row of the grid. The j-th integer in the i-th row is ai,\u2009j (1\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u2009105).", "output_spec": "Print \"Yes\" if the given lab is good and \"No\" otherwise. You can output each letter in upper or lower case.", "sample_inputs": ["3\n1 1 2\n2 3 1\n6 4 1", "3\n1 5 2\n1 1 1\n1 2 3"], "sample_outputs": ["Yes", "No"], "notes": "NoteIn the first sample test, the 6 in the bottom left corner is valid because it is the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this table, so the answer is \"Yes\".In the second sample test, the 5 cannot be formed as the sum of an integer in the same row and an integer in the same column. Thus the answer is \"No\"."}, "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": "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"}, {"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"} {"nl": {"description": "Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of array a. The second line contains n distinct space-separated integers: a[1],\u2009a[2],\u2009...,\u2009a[n] (1\u2009\u2264\u2009a[i]\u2009\u2264\u2009109).", "output_spec": "Print \"yes\" or \"no\" (without quotes), depending on the answer. If your answer is \"yes\", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.", "sample_inputs": ["3\n3 2 1", "4\n2 1 3 4", "4\n3 1 2 4", "2\n1 2"], "sample_outputs": ["yes\n1 3", "yes\n1 2", "no", "yes\n1 1"], "notes": "NoteSample 1. You can reverse the entire array to get [1,\u20092,\u20093], which is sorted.Sample 3. No segment can be reversed such that the array will be sorted.DefinitionsA segment [l,\u2009r] of array a is the sequence a[l],\u2009a[l\u2009+\u20091],\u2009...,\u2009a[r].If you have an array a of size n and you reverse its segment [l,\u2009r], the array will become:a[1],\u2009a[2],\u2009...,\u2009a[l\u2009-\u20092],\u2009a[l\u2009-\u20091],\u2009a[r],\u2009a[r\u2009-\u20091],\u2009...,\u2009a[l\u2009+\u20091],\u2009a[l],\u2009a[r\u2009+\u20091],\u2009a[r\u2009+\u20092],\u2009...,\u2009a[n\u2009-\u20091],\u2009a[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}"}, {"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"}], "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"} {"nl": {"description": "Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i\u2009+\u20091 to ai inclusive. No tickets are sold at the last station.Let \u03c1i,\u2009j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values \u03c1i,\u2009j among all pairs 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of stations. The second line contains n\u2009-\u20091 integer ai (i\u2009+\u20091\u2009\u2264\u2009ai\u2009\u2264\u2009n), the i-th of them means that at the i-th station one may buy tickets to each station from i\u2009+\u20091 to ai inclusive.", "output_spec": "Print the sum of \u03c1i,\u2009j among all pairs of 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n.", "sample_inputs": ["4\n4 4 4", "5\n2 3 5 5"], "sample_outputs": ["6", "17"], "notes": "NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample: \u03c11,\u20092\u2009=\u20091 \u03c11,\u20093\u2009=\u20092 \u03c11,\u20094\u2009=\u20093 \u03c11,\u20095\u2009=\u20093 \u03c12,\u20093\u2009=\u20091 \u03c12,\u20094\u2009=\u20092 \u03c12,\u20095\u2009=\u20092 \u03c13,\u20094\u2009=\u20091 \u03c13,\u20095\u2009=\u20091 \u03c14,\u20095\u2009=\u20091 Thus the answer equals 1\u2009+\u20092\u2009+\u20093\u2009+\u20093\u2009+\u20091\u2009+\u20092\u2009+\u20092\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u200917."}, "positive_code": [{"source_code": "import scala.collection.immutable.TreeMap\nimport scala.io.StdIn\nimport scala.math.Ordering.Implicits._\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toInt - 1)\n val rmq = new SegTree(n)(IntTupleMax)\n rmq.set(a.zipWithIndex)\n rmq(n - 1) = (n - 1, n - 1)\n val dp = Array.fill(n)(0L)\n dp(n - 1) = 0\n dp(n - 2) = 1\n for (i <- (0 until n - 2).reverse) {\n val p = rmq.query(i + 1, a(i) + 1)._2\n assert(p != -1)\n dp(i) = (n - 1 - i) + dp(p) - (a(i) - p)\n }\n println(dp.sum)\n }\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 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\nobject IntTupleMax extends Monoid[(Int, Int)] {\n def zero = (Int.MinValue, -1)\n def mul(a: (Int, Int), b: (Int, Int)) = a max b\n}\n\n\n"}], "negative_code": [{"source_code": "import scala.collection.immutable.TreeMap\nimport scala.io.StdIn\nimport scala.math.Ordering.Implicits._\nimport scala.reflect.ClassTag\n\nobject Main {\n def main(args: Array[String]) {\n val n = StdIn.readInt()\n val a = StdIn.readLine().split(\" \").map(_.toInt - 1)\n val rmq = new SegTree(n)(IntTupleMax)\n rmq.set(a.zipWithIndex)\n rmq(n - 1) = (n - 1, n - 1)\n val dp = Array.fill(n)(0)\n dp(n - 1) = 0\n dp(n - 2) = 1\n for (i <- (0 until n - 2).reverse) {\n val p = rmq.query(i + 1, a(i) + 1)._2\n assert(p != -1)\n dp(i) = (n - 1 - i) + dp(p) - (a(i) - p)\n }\n println(dp.sum)\n }\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 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\nobject IntTupleMax extends Monoid[(Int, Int)] {\n def zero = (Int.MinValue, -1)\n def mul(a: (Int, Int), b: (Int, Int)) = a max b\n}\n\n\n"}], "src_uid": "88f8f2c2f68589654709800ea9b19ecf"} {"nl": {"description": "Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103). The next line contains n integers a1, a2, ..., an (ai\u2009=\u20090 or ai\u2009=\u20095). Number ai represents the digit that is written on the i-th card.", "output_spec": "In a single line print the answer to the problem \u2014 the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.", "sample_inputs": ["4\n5 0 5 0", "11\n5 5 5 5 5 5 5 5 0 5 5"], "sample_outputs": ["0", "5555555550"], "notes": "NoteIn the first test you can make only one number that is a multiple of 90 \u2014 0.In the second test you can make number 5555555550, it is a multiple of 90."}, "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"}, {"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}"}], "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"} {"nl": {"description": "This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. (1) \u2014 bus, (2) \u2014 ring, (3) \u2014 star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. ", "input_spec": "The first line contains two space-separated integers n and m (4\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a03\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) \u2014 the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.", "output_spec": "In a single line print the network topology name of the given graph. If the answer is the bus, print \"bus topology\" (without the quotes), if the answer is the ring, print \"ring topology\" (without the quotes), if the answer is the star, print \"star topology\" (without the quotes). If no answer fits, print \"unknown topology\" (without the quotes).", "sample_inputs": ["4 3\n1 2\n2 3\n3 4", "4 4\n1 2\n2 3\n3 4\n4 1", "4 3\n1 2\n1 3\n1 4", "4 4\n1 2\n2 3\n3 1\n1 4"], "sample_outputs": ["bus topology", "ring topology", "star topology", "unknown topology"], "notes": null}, "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 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}"}, {"source_code": "/*\nB. \u0422\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f \u0441\u0435\u0442\u0438\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0412 \u0437\u0430\u0434\u0430\u0447\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0443\u043f\u0440\u043e\u0449\u0435\u043d\u043d\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0439 \u0441\u0435\u0442\u0435\u0439, \u0432\u043d\u0438\u043c\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u0440\u043e\u0447\u0442\u0438\u0442\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u0435 \u0437\u0430\u0434\u0430\u0447\u0438 \u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 \u0435\u0433\u043e \u043a\u0430\u043a \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u043f\u0440\u0438 \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u044f.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0430\u0435\u0442 \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441\u0438\u0441\u0442\u0435\u043c\u043d\u044b\u043c \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440\u043e\u043c \u0432 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438. \u041a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u0430\u044f \u0441\u0435\u0442\u044c \u044d\u0442\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 n \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043e\u0432, \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a\u0430\u0431\u0435\u043b\u0435\u043c. \u041a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u0443\u0435\u043c \u0446\u0435\u043b\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u043e\u0442 1 \u0434\u043e n. \u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e \u043b\u044e\u0431\u044b\u0435 \u0434\u0432\u0430 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0430 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a\u0430\u0431\u0435\u043b\u0435\u043c \u043d\u0435\u043f\u043e\u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0435\u043d\u043d\u043e \u0438\u043b\u0438 \u0447\u0435\u0440\u0435\u0437 \u0434\u0440\u0443\u0433\u0438\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0440\u0435\u0448\u0438\u043b \u0443\u0437\u043d\u0430\u0442\u044c \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044e \u044d\u0442\u043e\u0439 \u0441\u0435\u0442\u0438. \u0421\u0435\u0442\u0435\u0432\u0430\u044f \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f \u2014 \u044d\u0442\u043e \u0441\u043f\u043e\u0441\u043e\u0431 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u043a\u043e\u043d\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u0441\u0435\u0442\u0438, \u0441\u0445\u0435\u043c\u0430 \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0438 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u044f \u0441\u0435\u0442\u0435\u0432\u044b\u0445 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u043d\u0430\u0435\u0442 \u0442\u0440\u0438 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0438 \u0441\u0435\u0442\u0438: \u0448\u0438\u043d\u0430, \u043a\u043e\u043b\u044c\u0446\u043e \u0438 \u0437\u0432\u0435\u0437\u0434\u0430. \u0428\u0438\u043d\u0430 \u2014 \u044d\u0442\u043e \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442 \u0441\u043e\u0431\u043e\u0439 \u043e\u0431\u0449\u0438\u0439 \u043a\u0430\u0431\u0435\u043b\u044c, \u043a \u043a\u043e\u0442\u043e\u0440\u043e\u043c\u0443 \u043f\u043e\u0434\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b. \u041a\u043e\u043b\u044c\u0446\u043e \u2014 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043a\u0430\u0436\u0434\u044b\u0439 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d \u043a\u0430\u0431\u0435\u043b\u0435\u043c \u0442\u043e\u043b\u044c\u043a\u043e \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u0440\u0443\u0433\u0438\u043c\u0438. \u0417\u0432\u0435\u0437\u0434\u0430 \u2014 \u044d\u0442\u043e \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b \u0441\u0435\u0442\u0438 \u043f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a \u0435\u0434\u0438\u043d\u043e\u043c\u0443 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u043e\u043c\u0443 \u0443\u0437\u043b\u0443.\n\n\u041f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u043c \u043a\u0430\u0436\u0434\u0443\u044e \u0438\u0437 \u044d\u0442\u0438\u0445 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0439 \u0441\u0435\u0442\u0438 \u0432 \u0432\u0438\u0434\u0435 \u0441\u0432\u044f\u0437\u043d\u043e\u0433\u043e \u043d\u0435\u043e\u0440\u0438\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0433\u0440\u0430\u0444\u0430. \u041f\u043e\u0434 \u0448\u0438\u043d\u043e\u0439 \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u044f\u0432\u043b\u044f\u044e\u0449\u0438\u0439\u0441\u044f \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u043c \u043f\u0443\u0442\u0435\u043c, \u0442\u043e \u0435\u0441\u0442\u044c \u0433\u0440\u0430\u0444, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u0441\u0435 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u0440\u0443\u0433\u0438\u043c\u0438, \u0437\u0430 \u0438\u0441\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\u043c \u0434\u0432\u0443\u0445 \u0432\u0435\u0440\u0448\u0438\u043d, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043d\u0430\u0447\u0430\u043b\u043e\u043c \u0438 \u043a\u043e\u043d\u0446\u043e\u043c \u043f\u0443\u0442\u0438. \u041f\u043e\u0434 \u043a\u043e\u043b\u044c\u0446\u043e\u043c \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u0441\u0435 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u0440\u0443\u0433\u0438\u043c\u0438. \u041f\u043e\u0434 \u0437\u0432\u0435\u0437\u0434\u043e\u0439 \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0430 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u0430\u044f \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u0430\u044f \u0432\u0435\u0440\u0448\u0438\u043d\u0430, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0430 \u0441\u043e \u0432\u0441\u0435\u043c\u0438 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u043c\u0438 \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438. \u0414\u043b\u044f \u043b\u0443\u0447\u0448\u0435\u0433\u043e \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u044f \u043e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0440\u0438\u0441\u0443\u043d\u043a\u043e\u043c.\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) \u2014 \u0448\u0438\u043d\u0430, (2) \u2014 \u043a\u043e\u043b\u044c\u0446\u043e, (3) \u2014 \u0437\u0432\u0435\u0437\u0434\u0430\n\n\u0412\u0430\u043c \u0437\u0430\u0434\u0430\u043d \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u043d\u0435\u043e\u0440\u0438\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u0445\u0430\u0440\u0430\u043a\u0442\u0435\u0440\u0438\u0437\u0443\u044e\u0449\u0438\u0439 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u0443\u044e \u0441\u0435\u0442\u044c \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f. \u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u0435\u043c\u0443 \u0443\u0437\u043d\u0430\u0442\u044c, \u043a \u043a\u0430\u043a\u043e\u0439 \u0438\u0437 \u0434\u0430\u043d\u043d\u044b\u0445 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0439 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0441\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u0430\u044f \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u0430\u044f \u0441\u0435\u0442\u044c. \u0415\u0441\u043b\u0438 \u044d\u0442\u043e \u043d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u0435, \u0447\u0442\u043e \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f \u044d\u0442\u043e\u0439 \u0441\u0435\u0442\u0438 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 m (4\u2009\u2264\u2009n\u2009\u2264\u2009105; 3\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0435\u0440\u0448\u0438\u043d \u0438 \u0440\u0435\u0431\u0435\u0440 \u0432 \u0433\u0440\u0430\u0444\u0435 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e. \u0414\u0430\u043b\u0435\u0435 \u0432 m \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u0434\u0430\u043d\u043e \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0440\u0435\u0431\u0435\u0440 \u0433\u0440\u0430\u0444\u0430. \u0412 i-\u0442\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u0430 \u043f\u0430\u0440\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) \u2014 \u043d\u043e\u043c\u0435\u0440\u0430 \u0432\u0435\u0440\u0448\u0438\u043d, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u0442 i-\u043e\u0435 \u0440\u0435\u0431\u0440\u043e.\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0441\u0432\u044f\u0437\u043d\u044b\u043c. \u041c\u0435\u0436\u0434\u0443 \u043b\u044e\u0431\u044b\u043c\u0438 \u0434\u0432\u0443\u043c\u044f \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u043e\u0434\u043d\u043e\u0433\u043e \u0440\u0435\u0431\u0440\u0430. \u041d\u0438 \u043e\u0434\u043d\u043e \u0440\u0435\u0431\u0440\u043e \u043d\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u0442 \u0432\u0435\u0440\u0448\u0438\u043d\u0443 \u0441\u0430\u043c\u0443 \u0441 \u0441\u043e\u0431\u043e\u0439.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0438 \u0441\u0435\u0442\u0438, \u043a \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0441\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444. \u0415\u0441\u043b\u0438 \u043e\u0442\u0432\u0435\u0442\u043e\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0448\u0438\u043d\u0430, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abbus topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a), \u0435\u0441\u043b\u0438 \u043e\u0442\u0432\u0435\u0442\u043e\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u043e\u043b\u044c\u0446\u043e, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abring topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a), \u0435\u0441\u043b\u0438 \u043e\u0442\u0432\u0435\u0442\u043e\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0437\u0432\u0435\u0437\u0434\u0430, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abstar topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a). \u0415\u0441\u043b\u0438 \u043d\u0438 \u043e\u0434\u0438\u043d \u0438\u0437 \u044d\u0442\u0438\u0445 \u0442\u0438\u043f\u043e\u0432 \u043d\u0435 \u043f\u043e\u0434\u0445\u043e\u0434\u0438\u0442, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abunknown topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a).\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 3\n1 2\n2 3\n3 4\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\nbus topology\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 4\n1 2\n2 3\n3 4\n4 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\nring topology\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 3\n1 2\n1 3\n1 4\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\nstar topology\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 4\n1 2\n2 3\n3 1\n1 4\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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. \u0422\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f \u0441\u0435\u0442\u0438\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0412 \u0437\u0430\u0434\u0430\u0447\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0443\u043f\u0440\u043e\u0449\u0435\u043d\u043d\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0439 \u0441\u0435\u0442\u0435\u0439, \u0432\u043d\u0438\u043c\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u0440\u043e\u0447\u0442\u0438\u0442\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u0435 \u0437\u0430\u0434\u0430\u0447\u0438 \u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 \u0435\u0433\u043e \u043a\u0430\u043a \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u043f\u0440\u0438 \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u044f.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0430\u0435\u0442 \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441\u0438\u0441\u0442\u0435\u043c\u043d\u044b\u043c \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440\u043e\u043c \u0432 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438. \u041a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u0430\u044f \u0441\u0435\u0442\u044c \u044d\u0442\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 n \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043e\u0432, \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a\u0430\u0431\u0435\u043b\u0435\u043c. \u041a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u0443\u0435\u043c \u0446\u0435\u043b\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u043e\u0442 1 \u0434\u043e n. \u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e \u043b\u044e\u0431\u044b\u0435 \u0434\u0432\u0430 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0430 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a\u0430\u0431\u0435\u043b\u0435\u043c \u043d\u0435\u043f\u043e\u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0435\u043d\u043d\u043e \u0438\u043b\u0438 \u0447\u0435\u0440\u0435\u0437 \u0434\u0440\u0443\u0433\u0438\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0440\u0435\u0448\u0438\u043b \u0443\u0437\u043d\u0430\u0442\u044c \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044e \u044d\u0442\u043e\u0439 \u0441\u0435\u0442\u0438. \u0421\u0435\u0442\u0435\u0432\u0430\u044f \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f \u2014 \u044d\u0442\u043e \u0441\u043f\u043e\u0441\u043e\u0431 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u043a\u043e\u043d\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u0441\u0435\u0442\u0438, \u0441\u0445\u0435\u043c\u0430 \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0438 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u044f \u0441\u0435\u0442\u0435\u0432\u044b\u0445 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u043d\u0430\u0435\u0442 \u0442\u0440\u0438 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0438 \u0441\u0435\u0442\u0438: \u0448\u0438\u043d\u0430, \u043a\u043e\u043b\u044c\u0446\u043e \u0438 \u0437\u0432\u0435\u0437\u0434\u0430. \u0428\u0438\u043d\u0430 \u2014 \u044d\u0442\u043e \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442 \u0441\u043e\u0431\u043e\u0439 \u043e\u0431\u0449\u0438\u0439 \u043a\u0430\u0431\u0435\u043b\u044c, \u043a \u043a\u043e\u0442\u043e\u0440\u043e\u043c\u0443 \u043f\u043e\u0434\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b. \u041a\u043e\u043b\u044c\u0446\u043e \u2014 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043a\u0430\u0436\u0434\u044b\u0439 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d \u043a\u0430\u0431\u0435\u043b\u0435\u043c \u0442\u043e\u043b\u044c\u043a\u043e \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u0440\u0443\u0433\u0438\u043c\u0438. \u0417\u0432\u0435\u0437\u0434\u0430 \u2014 \u044d\u0442\u043e \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u044b \u0441\u0435\u0442\u0438 \u043f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a \u0435\u0434\u0438\u043d\u043e\u043c\u0443 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u043e\u043c\u0443 \u0443\u0437\u043b\u0443.\n\n\u041f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u043c \u043a\u0430\u0436\u0434\u0443\u044e \u0438\u0437 \u044d\u0442\u0438\u0445 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0439 \u0441\u0435\u0442\u0438 \u0432 \u0432\u0438\u0434\u0435 \u0441\u0432\u044f\u0437\u043d\u043e\u0433\u043e \u043d\u0435\u043e\u0440\u0438\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0433\u0440\u0430\u0444\u0430. \u041f\u043e\u0434 \u0448\u0438\u043d\u043e\u0439 \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u044f\u0432\u043b\u044f\u044e\u0449\u0438\u0439\u0441\u044f \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u043c \u043f\u0443\u0442\u0435\u043c, \u0442\u043e \u0435\u0441\u0442\u044c \u0433\u0440\u0430\u0444, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u0441\u0435 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u0440\u0443\u0433\u0438\u043c\u0438, \u0437\u0430 \u0438\u0441\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\u043c \u0434\u0432\u0443\u0445 \u0432\u0435\u0440\u0448\u0438\u043d, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043d\u0430\u0447\u0430\u043b\u043e\u043c \u0438 \u043a\u043e\u043d\u0446\u043e\u043c \u043f\u0443\u0442\u0438. \u041f\u043e\u0434 \u043a\u043e\u043b\u044c\u0446\u043e\u043c \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u0441\u0435 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u0440\u0443\u0433\u0438\u043c\u0438. \u041f\u043e\u0434 \u0437\u0432\u0435\u0437\u0434\u043e\u0439 \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0430 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u0430\u044f \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u0430\u044f \u0432\u0435\u0440\u0448\u0438\u043d\u0430, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0430 \u0441\u043e \u0432\u0441\u0435\u043c\u0438 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u043c\u0438 \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438. \u0414\u043b\u044f \u043b\u0443\u0447\u0448\u0435\u0433\u043e \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u044f \u043e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0440\u0438\u0441\u0443\u043d\u043a\u043e\u043c.\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) \u2014 \u0448\u0438\u043d\u0430, (2) \u2014 \u043a\u043e\u043b\u044c\u0446\u043e, (3) \u2014 \u0437\u0432\u0435\u0437\u0434\u0430\n\n\u0412\u0430\u043c \u0437\u0430\u0434\u0430\u043d \u0441\u0432\u044f\u0437\u043d\u044b\u0439 \u043d\u0435\u043e\u0440\u0438\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444, \u0445\u0430\u0440\u0430\u043a\u0442\u0435\u0440\u0438\u0437\u0443\u044e\u0449\u0438\u0439 \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u0443\u044e \u0441\u0435\u0442\u044c \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f. \u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u0435\u043c\u0443 \u0443\u0437\u043d\u0430\u0442\u044c, \u043a \u043a\u0430\u043a\u043e\u0439 \u0438\u0437 \u0434\u0430\u043d\u043d\u044b\u0445 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0439 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0441\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u0430\u044f \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u043d\u0430\u044f \u0441\u0435\u0442\u044c. \u0415\u0441\u043b\u0438 \u044d\u0442\u043e \u043d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u0435, \u0447\u0442\u043e \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u044f \u044d\u0442\u043e\u0439 \u0441\u0435\u0442\u0438 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 m (4\u2009\u2264\u2009n\u2009\u2264\u2009105; 3\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0435\u0440\u0448\u0438\u043d \u0438 \u0440\u0435\u0431\u0435\u0440 \u0432 \u0433\u0440\u0430\u0444\u0435 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e. \u0414\u0430\u043b\u0435\u0435 \u0432 m \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u0434\u0430\u043d\u043e \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0440\u0435\u0431\u0435\u0440 \u0433\u0440\u0430\u0444\u0430. \u0412 i-\u0442\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u0430 \u043f\u0430\u0440\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) \u2014 \u043d\u043e\u043c\u0435\u0440\u0430 \u0432\u0435\u0440\u0448\u0438\u043d, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u0442 i-\u043e\u0435 \u0440\u0435\u0431\u0440\u043e.\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0441\u0432\u044f\u0437\u043d\u044b\u043c. \u041c\u0435\u0436\u0434\u0443 \u043b\u044e\u0431\u044b\u043c\u0438 \u0434\u0432\u0443\u043c\u044f \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u043e\u0434\u043d\u043e\u0433\u043e \u0440\u0435\u0431\u0440\u0430. \u041d\u0438 \u043e\u0434\u043d\u043e \u0440\u0435\u0431\u0440\u043e \u043d\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u0442 \u0432\u0435\u0440\u0448\u0438\u043d\u0443 \u0441\u0430\u043c\u0443 \u0441 \u0441\u043e\u0431\u043e\u0439.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0442\u043e\u043f\u043e\u043b\u043e\u0433\u0438\u0438 \u0441\u0435\u0442\u0438, \u043a \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0441\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444. \u0415\u0441\u043b\u0438 \u043e\u0442\u0432\u0435\u0442\u043e\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0448\u0438\u043d\u0430, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abbus topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a), \u0435\u0441\u043b\u0438 \u043e\u0442\u0432\u0435\u0442\u043e\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u043e\u043b\u044c\u0446\u043e, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abring topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a), \u0435\u0441\u043b\u0438 \u043e\u0442\u0432\u0435\u0442\u043e\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0437\u0432\u0435\u0437\u0434\u0430, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abstar topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a). \u0415\u0441\u043b\u0438 \u043d\u0438 \u043e\u0434\u0438\u043d \u0438\u0437 \u044d\u0442\u0438\u0445 \u0442\u0438\u043f\u043e\u0432 \u043d\u0435 \u043f\u043e\u0434\u0445\u043e\u0434\u0438\u0442, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u00abunknown topology\u00bb (\u0431\u0435\u0437 \u043a\u0430\u0432\u044b\u0447\u0435\u043a).\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 3\n1 2\n2 3\n3 4\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\nbus topology\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 4\n1 2\n2 3\n3 4\n4 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\nring topology\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 3\n1 2\n1 3\n1 4\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\nstar topology\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4 4\n1 2\n2 3\n3 1\n1 4\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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"} {"nl": {"description": "Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types: it can contain a single sticker and no toy; it can contain a single toy and no sticker; it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.", "input_spec": "The first line contains the single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \\le n \\le 10^9$$$, $$$1 \\le s, t \\le n$$$, $$$s + t \\ge n$$$) \u2014 the number of eggs, stickers and toys. All queries are independent.", "output_spec": "Print $$$T$$$ integers (one number per query) \u2014 the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy", "sample_inputs": ["3\n10 5 7\n10 10 10\n2 1 1"], "sample_outputs": ["6\n1\n2"], "notes": "NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type). If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of friends. Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0\u2009\u2264\u2009si\u2009\u2264\u2009100) \u2014 the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as \"XX-XX-XX\", where X is arbitrary digits from 0 to 9.", "output_spec": "In the first line print the phrase \"If you want to call a taxi, you should call: \". Then print names of all friends whose phone books contain maximal number of taxi phone numbers. In the second line print the phrase \"If you want to order a pizza, you should call: \". Then print names of all friends who have maximal number of pizza phone numbers. In the third line print the phrase \"If you want to go to a cafe with a wonderful girl, you should call: \". Then print names of all friends who have maximal number of girls' phone numbers. Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.", "sample_inputs": ["4\n2 Fedorov\n22-22-22\n98-76-54\n3 Melnikov\n75-19-09\n23-45-67\n99-99-98\n7 Rogulenko\n22-22-22\n11-11-11\n33-33-33\n44-44-44\n55-55-55\n66-66-66\n95-43-21\n3 Kaluzhin\n11-11-11\n99-99-99\n98-65-32", "3\n5 Gleb\n66-66-66\n55-55-55\n01-01-01\n65-43-21\n12-34-56\n3 Serega\n55-55-55\n87-65-43\n65-55-21\n5 Melnik\n12-42-12\n87-73-01\n36-04-12\n88-12-22\n82-11-43", "3\n3 Kulczynski\n22-22-22\n65-43-21\n98-12-00\n4 Pachocki\n11-11-11\n11-11-11\n11-11-11\n98-76-54\n0 Smietanka"], "sample_outputs": ["If you want to call a taxi, you should call: Rogulenko.\nIf you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.\nIf you want to go to a cafe with a wonderful girl, you should call: Melnikov.", "If you want to call a taxi, you should call: Gleb.\nIf you want to order a pizza, you should call: Gleb, Serega.\nIf you want to go to a cafe with a wonderful girl, you should call: Melnik.", "If you want to call a taxi, you should call: Pachocki.\nIf you want to order a pizza, you should call: Kulczynski, Pachocki.\nIf you want to go to a cafe with a wonderful girl, you should call: Kulczynski."], "notes": "NoteIn the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls. "}, "positive_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).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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "A number $$$a_2$$$ is said to be the arithmetic mean of two numbers $$$a_1$$$ and $$$a_3$$$, if the following condition holds: $$$a_1 + a_3 = 2\\cdot a_2$$$. We define an arithmetic mean deviation of three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ as follows: $$$d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \\cdot a_2|$$$.Arithmetic means a lot to Jeevan. He has three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ and he wants to minimize the arithmetic mean deviation $$$d(a_1, a_2, a_3)$$$. To do so, he can perform the following operation any number of times (possibly zero): Choose $$$i, j$$$ from $$$\\{1, 2, 3\\}$$$ such that $$$i \\ne j$$$ and increment $$$a_i$$$ by $$$1$$$ and decrement $$$a_j$$$ by $$$1$$$ Help Jeevan find out the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 5000)$$$ \u00a0\u2014 the number of test cases. The first and only line of each test case contains three integers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ $$$(1 \\le a_1, a_2, a_3 \\le 10^{8})$$$.", "output_spec": "For each test case, output the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.", "sample_inputs": ["3\n3 4 5\n2 2 6\n1 6 5"], "sample_outputs": ["0\n1\n0"], "notes": "NoteNote that after applying a few operations, the values of $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ may become negative.In the first test case, $$$4$$$ is already the Arithmetic Mean of $$$3$$$ and $$$5$$$.$$$d(3, 4, 5) = |3 + 5 - 2 \\cdot 4| = 0$$$In the second test case, we can apply the following operation:$$$(2, 2, 6)$$$ $$$\\xrightarrow[\\text{increment $$$a_2$$$}]{\\text{decrement $$$a_1$$$}}$$$ $$$(1, 3, 6)$$$$$$d(1, 3, 6) = |1 + 6 - 2 \\cdot 3| = 1$$$It can be proven that answer can not be improved any further.In the third test case, we can apply the following operations:$$$(1, 6, 5)$$$ $$$\\xrightarrow[\\text{increment $$$a_3$$$}]{\\text{decrement $$$a_2$$$}}$$$ $$$(1, 5, 6)$$$ $$$\\xrightarrow[\\text{increment $$$a_1$$$}]{\\text{decrement $$$a_2$$$}}$$$ $$$(2, 4, 6)$$$$$$d(2, 4, 6) = |2 + 6 - 2 \\cdot 4| = 0$$$"}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given two strings $$$a$$$ and $$$b$$$ consisting of lowercase English letters, both of length $$$n$$$. The characters of both strings have indices from $$$1$$$ to $$$n$$$, inclusive. You are allowed to do the following changes: Choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and swap characters $$$a_i$$$ and $$$b_i$$$; Choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and swap characters $$$a_i$$$ and $$$a_{n - i + 1}$$$; Choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and swap characters $$$b_i$$$ and $$$b_{n - i + 1}$$$. Note that if $$$n$$$ is odd, you are formally allowed to swap $$$a_{\\lceil\\frac{n}{2}\\rceil}$$$ with $$$a_{\\lceil\\frac{n}{2}\\rceil}$$$ (and the same with the string $$$b$$$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.In one preprocess move you can replace a character in $$$a$$$ with another character. In other words, in a single preprocess move you can choose any index $$$i$$$ ($$$1 \\le i \\le n$$$), any character $$$c$$$ and set $$$a_i := c$$$.Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $$$a$$$ and $$$b$$$ equal by applying some number of changes described in the list above.Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $$$b$$$ or make any preprocess moves after the first change is made.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of strings $$$a$$$ and $$$b$$$. The second line contains the string $$$a$$$ consisting of exactly $$$n$$$ lowercase English letters. The third line contains the string $$$b$$$ consisting of exactly $$$n$$$ lowercase English letters.", "output_spec": "Print a single integer \u2014 the minimum number of preprocess moves to apply before changes, so that it is possible to make the string $$$a$$$ equal to string $$$b$$$ with a sequence of changes from the list above.", "sample_inputs": ["7\nabacaba\nbacabaa", "5\nzcabd\ndbacz"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first example preprocess moves are as follows: $$$a_1 := $$$'b', $$$a_3 := $$$'c', $$$a_4 := $$$'a' and $$$a_5:=$$$'b'. Afterwards, $$$a = $$$\"bbcabba\". Then we can obtain equal strings by the following sequence of changes: $$$swap(a_2, b_2)$$$ and $$$swap(a_2, a_6)$$$. There is no way to use fewer than $$$4$$$ preprocess moves before a sequence of changes to make string equal, so the answer in this example is $$$4$$$.In the second example no preprocess moves are required. We can use the following sequence of changes to make $$$a$$$ and $$$b$$$ equal: $$$swap(b_1, b_5)$$$, $$$swap(a_2, a_4)$$$."}, "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 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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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"} {"nl": {"description": "Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105). The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the initial group that is given to Toastman.", "output_spec": "Print a single integer \u2014 the largest possible score.", "sample_inputs": ["3\n3 1 5", "1\n10"], "sample_outputs": ["26", "10"], "notes": "NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions."}, "positive_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.foldLeft(0:Long)((b: Long, i: Int) => 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.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 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": "object Main {\n def main(args: Array[String]) {\n val a = readLine().split(\" \").map(_.toInt)\n val min = a.min\n \n println(min + 1)\n for(i <- 0 to min) println(i + \" \" + (min - i))\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"} {"nl": {"description": "Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.Monocarp has $$$n$$$ problems that none of his students have seen yet. The $$$i$$$-th problem has a topic $$$a_i$$$ (an integer from $$$1$$$ to $$$n$$$) and a difficulty $$$b_i$$$ (an integer from $$$1$$$ to $$$n$$$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.Monocarp decided to select exactly $$$3$$$ problems from $$$n$$$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both): the topics of all three selected problems are different; the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 50000$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains an integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of problems that Monocarp have. In the $$$i$$$-th of the following $$$n$$$ lines, there are two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$)\u00a0\u2014 the topic and the difficulty of the $$$i$$$-th problem. It is guaranteed that there are no two problems that have the same topic and difficulty at the same time. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print the number of ways to select three training problems that meet either of the requirements described in the statement.", "sample_inputs": ["2\n4\n2 4\n3 4\n2 1\n1 3\n5\n1 5\n2 4\n3 3\n4 2\n5 1"], "sample_outputs": ["3\n10"], "notes": "NoteIn the first example, you can take the following sets of three problems: problems $$$1$$$, $$$2$$$, $$$4$$$; problems $$$1$$$, $$$3$$$, $$$4$$$; problems $$$2$$$, $$$3$$$, $$$4$$$. Thus, the number of ways is equal to three."}, "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 val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[(Int, Int)](n+1)\n val a = new Array[Int](n+1)\n val b = new Array[Int](n+1)\n for (i <- 1 to n) {\n arr(i) = (readInt(), readInt())\n a(arr(i)._1) += 1\n b(arr(i)._2) += 1\n }\n var cnt = (n.toLong * (n-1).toLong * (n-2).toLong)/6L\n for (i <- 1 to n) {\n cnt -= (a(arr(i)._1).toLong-1L) * (b(arr(i)._2).toLong-1L)\n }\n writer.println(cnt)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "5a2d51da609b3c22bb8d801ebfb63822"} {"nl": {"description": "You have a sequence $$$a_1, a_2, \\ldots, a_n$$$ of length $$$n$$$, consisting of integers between $$$1$$$ and $$$m$$$. You also have a string $$$s$$$, consisting of $$$m$$$ characters B.You are going to perform the following $$$n$$$ operations. At the $$$i$$$-th ($$$1 \\le i \\le n$$$) operation, you replace either the $$$a_i$$$-th or the $$$(m + 1 - a_i)$$$-th character of $$$s$$$ with A. You can replace the character at any position multiple times through the operations. Find the lexicographically smallest string you can get after these operations.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ of the same length if and only if in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.", "input_spec": "The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 2000$$$). The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 50$$$)\u00a0\u2014 the length of the sequence $$$a$$$ and the length of the string $$$s$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le m$$$)\u00a0\u2014 the sequence $$$a$$$.", "output_spec": "For each test case, print a string of length $$$m$$$\u00a0\u2014 the lexicographically smallest string you can get. Each character of the string should be either capital English letter A or capital English letter B.", "sample_inputs": ["6\n\n4 5\n\n1 1 3 1\n\n1 5\n\n2\n\n4 1\n\n1 1 1 1\n\n2 4\n\n1 3\n\n2 7\n\n7 5\n\n4 5\n\n5 5 3 5"], "sample_outputs": ["ABABA\nBABBB\nA\nAABB\nABABBBB\nABABA"], "notes": "NoteIn the first test case, the sequence $$$a = [1, 1, 3, 1]$$$. One of the possible solutions is the following. At the $$$1$$$-st operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ becomes ABBBB. At the $$$2$$$-nd operation, you can replace the $$$5$$$-th character of $$$s$$$ with A (since $$$m+1-a_2=5$$$). After it, $$$s$$$ becomes ABBBA. At the $$$3$$$-rd operation, you can replace the $$$3$$$-rd character of $$$s$$$ with A. After it, $$$s$$$ becomes ABABA. At the $$$4$$$-th operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ remains equal to ABABA. The resulting string is ABABA. It is impossible to produce a lexicographically smaller string.In the second test case, you are going to perform only one operation. You can replace either the $$$2$$$-nd character or $$$4$$$-th character of $$$s$$$ with A. You can get strings BABBB and BBBAB after the operation. The string BABBB is the lexicographically smallest among these strings.In the third test case, the only string you can get is A.In the fourth test case, you can replace the $$$1$$$-st and $$$2$$$-nd characters of $$$s$$$ with A to get AABB.In the fifth test case, you can replace the $$$1$$$-st and $$$3$$$-rd characters of $$$s$$$ with A to get ABABBBB."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "eee23388aa7cda50302fc4da6e50e172"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \\le x < m$$$ and $$$\\gcd(a, m) = \\gcd(a + x, m)$$$.Note: $$$\\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.", "input_spec": "The first line contains the single integer $$$T$$$ ($$$1 \\le T \\le 50$$$) \u2014 the number of test cases. Next $$$T$$$ lines contain test cases \u2014 one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \\le a < m \\le 10^{10}$$$).", "output_spec": "Print $$$T$$$ integers \u2014 one per test case. For each test case print the number of appropriate $$$x$$$-s.", "sample_inputs": ["3\n4 9\n5 10\n42 9999999967"], "sample_outputs": ["6\n1\n9999999966"], "notes": "NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$."}, "positive_code": [{"source_code": "object Main 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 sb = new StringBuilder\n val numCasos = in.nextInt()\n (1 to numCasos).foreach{ _ =>\n val (a,m) = (in.nextLong(),in.nextLong())\n val g = gcd(a,m)\n val number = m/g\n val res = phi(number)\n sb.append(res).append(System.lineSeparator())\n }\n out.print(sb.toString())\n }\n def phi(numer: Long): Long = {\n var ans = numer\n var m = numer\n var i: Long = 2L\n while(i*i <= m){\n if(m%i == 0){\n ans -= ans/i\n while(m%i == 0)\n m /= i\n\n }\n i += 1L\n }\n if(m > 1) ans-=ans/m\n ans\n\n }\n def gcd(a: Long,b: Long): Long = {\n if(b == 0)\n a\n else\n gcd(b,a%b)\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 //solve(System.in,System.out)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val sb = new StringBuilder\n val numCasos = in.nextInt()\n (1 to numCasos).foreach{ _ =>\n val (a,m) = (in.nextLong(),in.nextLong())\n val g = gcd(a,m)\n val number = m/g\n val res = phi(number)\n sb.append(res).append(System.lineSeparator())\n }\n out.print(sb.toString())\n }\n def phi(numer: Long): Long = {\n var ans = numer\n var m = numer\n val is = Stream.from(2).takeWhile(i => (i.toLong)*(i.toLong) <=m).toList\n is.foreach{ i =>\n if(m%i == 0){\n ans -= ans/i\n while(m%i == 0)\n m /= i\n\n }\n }\n if(m > 1) ans-=ans/m\n ans\n\n }\n def gcd(a: Long,b: Long): Long = {\n if(b == 0)\n a\n else\n gcd(b,a%b)\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": "adcd813d4c45337bbd8bb0abfa2f0e00"} {"nl": {"description": "A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string \"aab\" is an anagram of the string \"aba\" and the string \"aaa\" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string \"aba\" has six substrings: \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".You are given a string s, consisting of lowercase Latin letters and characters \"?\". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the \"?\" characters by Latin letters. Each \"?\" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = \u00ababa\u00bb, then the string \"a??\" is good, and the string \u00ab?bc\u00bb is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).", "input_spec": "The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters \"?\". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.", "output_spec": "Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.", "sample_inputs": ["bb??x???\naab", "ab?c\nacb"], "sample_outputs": ["2", "2"], "notes": "NoteConsider the first sample test. Here the string s has two good substrings: \"b??\" (after we replace the question marks we get \"baa\"), \"???\" (after we replace the question marks we get \"baa\").Let's consider the second sample test. Here the string s has two good substrings: \"ab?\" (\"?\" can be replaced by \"c\"), \"b?c\" (\"?\" can be replaced by \"a\")."}, "positive_code": [{"source_code": "import scala.util.control.Breaks._\nobject Main144C {\n def main(args: Array[String]) {\n val s = readLine\n val p = readLine\n val p_counts = Array.ofDim[Int](26)\n for (c <- p)\n p_counts(c-'a') += 1\n val s_counts = Array.ofDim[Int](26)\n var result = 0\n for (i <- 0 to (s.length - 1)) {\n if (s(i) != '?')\n s_counts(s(i) -'a') += 1\n if (i >= p.length && s(i-p.length) != '?')\n s_counts(s(i - p.length)-'a') -= 1\n var acceptable = i >= p.length - 1\n for (i <- 0 to 25)\n if (s_counts(i) > p_counts(i))\n acceptable = false\n if (acceptable)\n result += 1\n }\n println(result)\n }\n}"}], "negative_code": [], "src_uid": "9ed2a081b65df66629fcf0d4fc0bb02c"} {"nl": {"description": "You are given a rectangular grid of lattice points from (0,\u20090) to (n,\u2009m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1,\u2009p2,\u2009p3,\u2009p4 consists of the line segments p1\u2009p2,\u2009p2\u2009p3,\u2009p3\u2009p4, and its length is the sum of the lengths of the individual line segments.", "input_spec": "The only line of the input contains two integers n and m (0\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000). It is guaranteed that grid contains at least 4 different points.", "output_spec": "Print 4 lines with two integers per line separated by space \u2014 coordinates of points p1,\u2009p2,\u2009p3,\u2009p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10\u2009-\u20096 precision.", "sample_inputs": ["1 1", "0 10"], "sample_outputs": ["1 1\n0 0\n1 0\n0 1", "0 1\n0 10\n0 0\n0 9"], "notes": null}, "positive_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 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"}, {"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"} {"nl": {"description": "There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.", "input_spec": "The first line contains two integers a,\u2009b (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u20091000), separated by a single space.", "output_spec": "In the first line print either \"YES\" or \"NO\" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers \u2014 the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.", "sample_inputs": ["1 1", "5 5", "5 10"], "sample_outputs": ["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"], "notes": null}, "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 \u306e\u90e8\u5206\n val bs = pythagorean(B) // neg-Y -> pos-X \u306e\u90e8\u5206\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}"}, {"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}"}], "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"} {"nl": {"description": "Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.", "input_spec": "The single line contains three space-separated integers: n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the initial number of cards on the table, d (|d|\u2009\u2264\u2009104) \u2014 the number on the card that was left on the table after all the magical actions, and l (1\u2009\u2264\u2009l\u2009\u2264\u2009100) \u2014 the limits for the initial integers.", "output_spec": "If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.", "sample_inputs": ["3 3 2", "5 -4 3", "5 -4 4"], "sample_outputs": ["2 1 2", "-1", "2 4 1 4 1"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nobject B extends App {\n val sc = new Scanner(System.in)\n val n = sc.nextInt\n val d = sc.nextInt\n val el = sc.nextInt\n val lines = Iterator.iterate((0, d, n)) {\n case (a, d0, n0) => if (n0 <= 0) (-1, -1, -1)\n\t\t\telse if (n0 == 1) (d0, d0, 0)\n\t\t\telse if (d0 < 0) (1, 1 - d0, n0 - 1)\n\t\t\telse if (d0 == 0) (1, 1, n0 - 1)\n\t\t\telse if (el > d0) (d0 + 1, 1, n0 - 1)\n\t\t\telse (el, el - d0, n0 - 1)\n }.takeWhile {case (_, _, n0) => n0 >= 0}.toList.tail\n // println(lines.mkString(\"->\"))\n val last_val = lines.last._1\n if (last_val <= 0 || last_val > el) {\n println(-1)\n } else {\n println(lines.map(p => p._1).mkString(\" \"))\n }\n}\n"}], "negative_code": [], "src_uid": "a20d59a0db07cbb5692f01d28e41a3a1"} {"nl": {"description": "DZY loves chessboard, and he enjoys playing with it.He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.You task is to find any suitable placement of chessmen on the given chessboard.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either \".\" or \"-\". A \".\" means that the corresponding cell (in the i-th row and the j-th column) is good, while a \"-\" means it is bad.", "output_spec": "Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either \"W\", \"B\" or \"-\". Character \"W\" means the chessman on the cell is white, \"B\" means it is black, \"-\" means the cell is a bad cell. If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.", "sample_inputs": ["1 1\n.", "2 2\n..\n..", "3 3\n.-.\n---\n--."], "sample_outputs": ["B", "BW\nWB", "B-B\n---\n--B"], "notes": "NoteIn the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are."}, "positive_code": [{"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"}, {"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": "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"}, {"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}"}], "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"} {"nl": {"description": " While performing complex market analysis William encountered the following problem:For a given array $$$a$$$ of size $$$n$$$ and a natural number $$$e$$$, calculate the number of pairs of natural numbers $$$(i, k)$$$ which satisfy the following conditions: $$$1 \\le i, k$$$ $$$i + e \\cdot k \\le n$$$. Product $$$a_i \\cdot a_{i + e} \\cdot a_{i + 2 \\cdot e} \\cdot \\ldots \\cdot a_{i + k \\cdot e} $$$ is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$e$$$ $$$(1 \\le e \\le n \\le 2 \\cdot 10^5)$$$, the number of items in the array and number $$$e$$$, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^6)$$$, the contents of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output the answer in the following format: Output one line containing the number of pairs of numbers $$$(i, k)$$$ which satisfy the conditions.", "sample_inputs": ["6\n7 3\n10 2 1 3 1 19 3\n3 2\n1 13 1\n9 3\n2 4 2 1 1 1 1 4 2\n3 1\n1 1 1\n4 1\n1 2 1 1\n2 2\n1 2"], "sample_outputs": ["2\n0\n4\n0\n5\n0"], "notes": "NoteIn the first example test case two pairs satisfy the conditions: $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \\cdot a_{5} = 2$$$ which is a prime number. $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \\cdot a_{6} = 19$$$ which is a prime number. In the second example test case there are no pairs that satisfy the conditions.In the third example test case four pairs satisfy the conditions: $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \\cdot a_{4} = 2$$$ which is a prime number. $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \\cdot a_{4} \\cdot a_{7} = 2$$$ which is a prime number. $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \\cdot a_{6} = 2$$$ which is a prime number. $$$i = 6, k = 1$$$, for which the product is: $$$a_{6} \\cdot a_{9} = 2$$$ which is a prime number. In the fourth example test case there are no pairs that satisfy the conditions.In the fifth example test case five pairs satisfy the conditions: $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \\cdot a_{2} = 2$$$ which is a prime number. $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \\cdot a_{2} \\cdot a_{3} = 2$$$ which is a prime number. $$$i = 1, k = 3$$$, for which the product is: $$$a_{1} \\cdot a_{2} \\cdot a_{3} \\cdot a_{4} = 2$$$ which is a prime number. $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \\cdot a_{3} = 2$$$ which is a prime number. $$$i = 2, k = 2$$$, for which the product is: $$$a_{2} \\cdot a_{3} \\cdot a_{4} = 2$$$ which is a prime number. In the sixth example test case there are no pairs that satisfy the conditions."}, "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 = 1000010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n val mark = new Array[Boolean](maxn)\n var tmp = 0\n mark(1) = true\n for (i <- 2 until maxn)\n if (!mark(i)) {\n tmp = 2 * i\n while (tmp < maxn) {\n mark(tmp) = true\n tmp += i\n }\n }\n\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n val l = new Array[Long](n+1)\n val r = new Array[Long](n+1)\n val arr = new Array[Int](n+1)\n for (i <- 1 to n) {\n arr(i) = readInt()\n }\n for (i <- 1 to n) {\n if (arr(i) == 1) {\n l(i) = 1L\n r(i) = 1L\n }\n }\n for(i <- k+1 to n) {\n if (arr(i-k) == 1)\n l(i) += l(i-k)\n }\n for (i <- (1 to n-k).reverse) {\n if (arr(i + k) == 1)\n r(i) += r(i+k)\n }\n var cnt = 0L\n for (i <- 1 to n) {\n if (!mark(arr(i))) {\n cnt += (l(i)+1L) * (r(i)+1L) - 1L\n }\n }\n writer.println(cnt)\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"}], "negative_code": [], "src_uid": "32130f939336bb6f2deb4dfa5402867d"} {"nl": {"description": "Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers \u2014 ai and bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009104) \u2014 the numbers, written at the top and the bottom of the i-th card correspondingly.", "output_spec": "Print the single number \u2014 the maximum number of points you can score in one round by the described rules.", "sample_inputs": ["2\n1 0\n2 0", "3\n1 0\n2 0\n0 2"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards."}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "It is the hard version of the problem. The only difference is that in this version $$$3 \\le k \\le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \\ldots, a_k$$$, such that: $$$a_1 + a_2 + \\ldots + a_k = n$$$ $$$LCM(a_1, a_2, \\ldots, a_k) \\le \\frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \\ldots, a_k$$$.We can show that for given constraints the answer always exists.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 10^4)$$$ \u00a0\u2014 the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \\le n \\le 10^9$$$, $$$3 \\le k \\le n$$$). It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print $$$k$$$ positive integers $$$a_1, a_2, \\ldots, a_k$$$, for which all conditions are satisfied.", "sample_inputs": ["2\n6 4\n9 5"], "sample_outputs": ["1 2 2 1 \n1 3 3 1 1"], "notes": null}, "positive_code": [{"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 xs = readLine.split(' ').toList.map(x => x.toInt)\r\n val n = xs(0)\r\n val k = xs(1)\r\n val values = n - k + 3 match {\r\n case x if x % 2 == 1 => List(1, (x-1)/2, (x-1)/2) ++ List.fill(k-3)(1)\r\n case x if x % 4 == 2 => List(2, (x-2)/2, (x-2)/2) ++ List.fill(k-3)(1)\r\n case x if x % 4 == 0 => List(x/4, x/4, x/2) ++ List.fill(k-3)(1)\r\n }\r\n println(values.map(x => x.toString()).mkString(\" \"))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "1fea137016452340beb13dd7518f00c9"} {"nl": {"description": "Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \\ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$\u00a0\u2014 the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.", "input_spec": "The first line contains one integer $$$n$$$\u00a0\u2014 the number of vertices in the tree ($$$2 \\le n \\le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \\le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \\le s_v \\le 10^9$$$), where erased values are replaced by $$$-1$$$.", "output_spec": "Output one integer\u00a0\u2014 the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.", "sample_inputs": ["5\n1 1 1 1\n1 -1 -1 -1 -1", "5\n1 2 3 1\n1 -1 2 -1 -1", "3\n1 2\n2 -1 1"], "sample_outputs": ["1", "2", "-1"], "notes": null}, "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 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\u304c\u6c7a\u307e\u3063\u3066\u3044\u306a\u3044\n assert(S(v) == -1)\n\n // S\u304c\u6c7a\u307e\u3063\u3066\u3044\u306a\u3044\u5834\u5408\u306f\u3001\u5b50\u4f9b\u306e\u4e2d\u3067\u4e00\u756a\u5c0f\u3055\u3044\u3082\u306e\u306b\u5408\u308f\u305b\u308b\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 //\u767b\u3063\u3066\u884c\u304f\u3068\u304d\u306b\u672a\u6c7a\u5b9a\u3060\u3063\u305fS\u3092parent\u306e\u3082\u306e\u306b\u3059\u308b\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 \u30ce\u30fc\u30c9\u6570\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}"}, {"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"} {"nl": {"description": "Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \\ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \\ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the number of persons in the party. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le n-1$$$), the statements of people.", "output_spec": "If there is no solution, print a single line \"Impossible\". Otherwise, print \"Possible\" and then $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le n$$$). If there are multiple answers, print any of them.", "sample_inputs": ["3\n0 0 0", "5\n3 3 2 2 2", "4\n0 1 2 3"], "sample_outputs": ["Possible\n1 1 1", "Possible\n1 1 2 2 2", "Impossible"], "notes": "NoteIn the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $$$1$$$.In the answer to the second example, the first and the second person wore the hat with type $$$1$$$ and all other wore a hat of type $$$2$$$.So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible."}, "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\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"}, {"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"} {"nl": {"description": "Sereja has got an array, consisting of n integers, a1,\u2009a2,\u2009...,\u2009an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi\u2009=\u2009xi. Increase each array element by yi. In other words, perform n assignments ai\u2009=\u2009ai\u2009+\u2009yi (1\u2009\u2264\u2009i\u2009\u2264\u2009n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.", "input_spec": "The first line contains integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20093) that represents the operation type. If ti\u2009=\u20091, then it is followed by two integers vi and xi, (1\u2009\u2264\u2009vi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009109). If ti\u2009=\u20092, then it is followed by integer yi (1\u2009\u2264\u2009yi\u2009\u2264\u2009104). And if ti\u2009=\u20093, then it is followed by integer qi (1\u2009\u2264\u2009qi\u2009\u2264\u2009n).", "output_spec": "For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.", "sample_inputs": ["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"], "sample_outputs": ["2\n9\n11\n20\n30\n40\n39"], "notes": null}, "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 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"}, {"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": "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 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": "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"}, {"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}"}], "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"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \\in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.", "sample_inputs": ["6\n5 5\n13 42\n18 4\n1337 420\n123456789 1000000000\n100500 9000"], "sample_outputs": ["0\n3\n2\n92\n87654322\n9150"], "notes": "NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \\rightarrow 23 \\rightarrow 32 \\rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \\rightarrow 10 \\rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$)."}, "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"}, {"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"}], "negative_code": [], "src_uid": "d67a97a3b69d599b03d3fce988980646"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.", "input_spec": "The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 1000$$$) \u2014 the description of test cases.", "output_spec": "For each test case output two lines. In the first line output a single integer $$$m$$$ \u2014 the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ \u2014 the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.", "sample_inputs": ["3\n3 2\n5 3\n1 1"], "sample_outputs": ["2\n3 1 \n3\n4 5 2 \n0"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "This is a harder version of the problem. The difference is only in constraints.You are given a rectangular $$$n \\times m$$$ matrix $$$a$$$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $$$i$$$-th row it is equal $$$r_i$$$. What is the maximal possible value of $$$r_1+r_2+\\ldots+r_n$$$?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 40$$$), the number of test cases in the input. The first line of each test case contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 12$$$, $$$1 \\le m \\le 2000$$$) \u2014 the number of rows and the number of columns in the given matrix $$$a$$$. Each of the following $$$n$$$ lines contains $$$m$$$ integers, the elements of $$$a$$$ ($$$1 \\le a_{i, j} \\le 10^5$$$).", "output_spec": "Print $$$t$$$ integers: answers for all test cases in the order they are given in the input.", "sample_inputs": ["3\n2 3\n2 5 7\n4 2 4\n3 6\n4 1 5 2 10 4\n8 6 6 4 9 10\n5 4 9 5 8 7\n3 3\n9 9 9\n1 1 1\n1 1 1"], "sample_outputs": ["12\n29\n27"], "notes": "NoteIn the first test case you can shift the third column down by one, this way there will be $$$r_1 = 5$$$ and $$$r_2 = 7$$$.In the second case you can don't rotate anything at all, this way there will be $$$r_1 = r_2 = 10$$$ and $$$r_3 = 9$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089final\u306f\u305a\u305b\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 @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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089final\u306f\u305a\u305b\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089final\u306f\u305a\u305b\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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< 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 Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val n = in.next().toInt\n println(in.next().split(\" \").zipWithIndex.foldLeft((0, 0)) {\n case(acc, (\"0\", i)) => 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}"}, {"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"} {"nl": {"description": "Numbers $$$1, 2, 3, \\dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal: choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$; choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$; choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of integers written on the board initially. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, in the first line, print the minimum possible number left on the board after $$$n - 1$$$ operations. Each of the next $$$n - 1$$$ lines should contain two integers\u00a0\u2014 numbers $$$a$$$ and $$$b$$$ chosen and erased in each operation.", "sample_inputs": ["1\n4"], "sample_outputs": ["2\n2 4\n3 3\n3 1"], "notes": null}, "positive_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 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"}, {"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"} {"nl": {"description": "A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \\le i \\le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^{9}$$$).", "output_spec": "For each test case, print a single integer \u00a0\u2014 the answer to the problem.", "sample_inputs": ["4\n1\n2\n3\n4"], "sample_outputs": ["1\n1\n2\n2"], "notes": "NoteIn the third case, he can connect two sticks with lengths $$$1$$$ and $$$2$$$ and he will get one stick with length $$$3$$$. So, he will have two sticks with lengths $$$3$$$.In the fourth case, he can connect two sticks with lengths $$$1$$$ and $$$3$$$ and he will get one stick with length $$$4$$$. After that, he will have three sticks with lengths $$$\\{2, 4, 4\\}$$$, so two sticks have the same length, and one stick has the other length."}, "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"}, {"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}"}], "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"} {"nl": {"description": "You went to the store, selling $$$n$$$ types of chocolates. There are $$$a_i$$$ chocolates of type $$$i$$$ in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $$$x_i$$$ chocolates of type $$$i$$$ (clearly, $$$0 \\le x_i \\le a_i$$$), then for all $$$1 \\le j < i$$$ at least one of the following must hold: $$$x_j = 0$$$ (you bought zero chocolates of type $$$j$$$) $$$x_j < x_i$$$ (you bought less chocolates of type $$$j$$$ than of type $$$i$$$) For example, the array $$$x = [0, 0, 1, 2, 10]$$$ satisfies the requirement above (assuming that all $$$a_i \\ge x_i$$$), while arrays $$$x = [0, 1, 0]$$$, $$$x = [5, 5]$$$ and $$$x = [3, 2]$$$ don't.Calculate the maximum number of chocolates you can buy.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$), denoting the number of types of chocolate. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$), denoting the number of chocolates of each type.", "output_spec": "Print the maximum number of chocolates you can buy.", "sample_inputs": ["5\n1 2 1 3 6", "5\n3 2 5 4 10", "4\n1 1 1 1"], "sample_outputs": ["10", "20", "1"], "notes": "NoteIn the first example, it is optimal to buy: $$$0 + 0 + 1 + 3 + 6$$$ chocolates.In the second example, it is optimal to buy: $$$1 + 2 + 3 + 4 + 10$$$ chocolates.In the third example, it is optimal to buy: $$$0 + 0 + 0 + 1$$$ chocolates."}, "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 Main {\n def main(args: Array[String]): Unit = {\n val s = 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": "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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease. You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.", "input_spec": "The firt line of the input contains integers n, m, s and t (2\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009m\u2009\u2264\u20091000, 1\u2009\u2264\u2009s,\u2009t\u2009\u2264\u2009n, s\u2009\u2260\u2009t)\u00a0\u2014 the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.", "output_spec": "Print one integer\u00a0\u2014 the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.", "sample_inputs": ["5 4 1 5\n1 2\n2 3\n3 4\n4 5", "5 4 3 5\n1 2\n2 3\n3 4\n4 5", "5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5"], "sample_outputs": ["0", "5", "3"], "notes": null}, "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport java.util.TreeSet\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main2 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\n val n = in.nextInt\n val m = in.nextInt\n val s = in.nextInt - 1\n val t = in.nextInt - 1\n\n val g = Array.ofDim[Boolean](n, n)\n\n for (_ <- 0 to m-1) {\n val x = in.nextInt - 1\n val y = in.nextInt - 1\n g(x)(y) = true\n g(y)(x) = true\n }\n\n val d1 = bfs(s, g)\n val d2 = bfs(t, g)\n\n var cnt = 0\n\n for {\n i <- 0 until n\n j <- i + 1 until n\n if !g(i)(j) && d1(i) + d2(j) + 1 >= d1(t) && d1(j) + d2(i) + 1 >= d1(t)\n } cnt += 1\n\n out.println(cnt)\n out.flush()\n out.close()\n\n def bfs(s: Int, g: Array[Array[Boolean]]): Array[Int] = {\n val queue = scala.collection.mutable.Queue[Int]()\n val dist = new Array[Int](1000).map(_ => Int.MaxValue)\n queue += s\n dist(s) = 0\n\n while (queue.length > 0) {\n val v = queue.dequeue()\n for (u <- 0 to n-1)\n if (g(v)(u) && dist(u) > dist(v) + 1) {\n dist(u) = dist(v) + 1\n queue += u\n }\n }\n\n dist\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": [{"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport java.util.TreeSet\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main2 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\n val n = in.nextInt\n val m = in.nextInt\n val s = in.nextInt - 1\n val t = in.nextInt - 1\n\n val g = Array.ofDim[Boolean](n, n)\n\n for (_ <- 0 to m-1) {\n val x = in.nextInt - 1\n val y = in.nextInt - 1\n g(x)(y) = true\n g(y)(x) = true\n }\n\n val d1 = bfs(s, g)\n val d2 = bfs(t, g)\n\n var cnt = 0\n\n for {\n i <- 0 until n\n j <- i + 1 until n\n if !g(i)(j) && d1(i) + d2(j) + 1 >= d1(t)\n } cnt += 1\n\n out.println(cnt)\n out.flush()\n out.close()\n\n def bfs(s: Int, g: Array[Array[Boolean]]): Array[Int] = {\n val queue = scala.collection.mutable.Queue[Int]()\n val dist = new Array[Int](1000).map(_ => Int.MaxValue)\n queue += s\n dist(s) = 0\n\n while (queue.length > 0) {\n val v = queue.dequeue()\n for (u <- 0 to n-1)\n if (g(v)(u) && dist(u) > dist(v) + 1) {\n dist(u) = dist(v) + 1\n queue += u\n }\n }\n\n dist\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}"}], "src_uid": "bd49960701cc29bcef693808db82366f"} {"nl": {"description": "A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.You are to compute the prices each buyer will pay for t-shirts.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of t-shirts. The following line contains sequence of integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u20091\u2009000\u2009000\u2009000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20093), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u20093), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of buyers. The following line contains sequence c1,\u2009c2,\u2009...,\u2009cm (1\u2009\u2264\u2009cj\u2009\u2264\u20093), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. ", "output_spec": "Print to the first line m integers \u2014 the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.", "sample_inputs": ["5\n300 200 400 500 911\n1 2 1 2 3\n2 1 3 2 1\n6\n2 3 1 2 1 1", "2\n1000000000 1\n1 1\n1 2\n2\n2 1"], "sample_outputs": ["200 400 300 500 911 -1", "1 1000000000"], "notes": null}, "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 _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"}, {"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"} {"nl": {"description": "There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.", "input_spec": "The only line consists of a single integer $$$n$$$\u00a0($$$2 \\leq n \\leq 10^9$$$)\u00a0\u2014 the number of people playing with the ball.", "output_spec": "Suppose the set of all fun values is $$$f_1, f_2, \\dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.", "sample_inputs": ["6", "16"], "sample_outputs": ["1 5 9 21", "1 10 28 64 136"], "notes": "NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$. In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively."}, "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"}, {"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"}], "negative_code": [], "src_uid": "2ae1a4d4f2e58b359c898d1ff38edb9e"} {"nl": {"description": "A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \\ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \\le |p_i - p_{i+1}| \\le 4$$$ for each $$$i$$$ ($$$1 \\le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \\le n \\le 1000$$$).", "output_spec": "Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.", "sample_inputs": ["6\n10\n2\n4\n6\n7\n13"], "sample_outputs": ["9 6 10 8 4 7 3 1 5 2 \n-1\n3 1 4 2 \n5 3 6 2 4 1 \n5 1 3 6 2 4 7 \n13 9 7 11 8 4 1 3 5 2 6 10 12"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "9b8a5d9a6cfd6b3b5d0839eeece6f777"} {"nl": {"description": "Galya is playing one-dimensional Sea Battle on a 1\u2009\u00d7\u2009n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called \"hit\") or not (this case is called \"miss\").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.", "input_spec": "The first line contains four positive integers n, a, b, k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n, 0\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string. ", "output_spec": "In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.", "sample_inputs": ["5 1 2 1\n00100", "13 3 2 3\n1000000010001"], "sample_outputs": ["2\n4 2", "2\n7 11"], "notes": "NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the \"1\" character). So, it is necessary to make two shots: one at the left part, and one at the right part."}, "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 val Array(n, a, b, k) = readInts(4)\n val shotAt = readLine\n val shootAt = new mutable.ArrayBuilder.ofInt\n\n var i = 0\n var lastShotAt = -1\n val shotsMade = 0\n while (i < n) {\n if (shotAt(i) == '1') lastShotAt = i\n else {\n if (i - lastShotAt == b) {\n lastShotAt = i\n shootAt += i + 1\n }\n }\n i += 1\n }\n\n val mustShootAt = shootAt.result.drop(a - 1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(mustShootAt.length)\n println(mustShootAt.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "d50bb59298e109b4ac5f808d24fef5a1"} {"nl": {"description": "Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $$$a$$$ vanilla cookies and $$$b$$$ chocolate cookies for the party.She invited $$$n$$$ guests of the first type and $$$m$$$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:If there are $$$v$$$ vanilla cookies and $$$c$$$ chocolate cookies at the moment, when the guest comes, then if the guest of the first type: if $$$v>c$$$ the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie. if the guest of the second type: if $$$v>c$$$ the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie. After that: If there is at least one cookie of the selected type, the guest eats one. Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains four integers $$$a$$$, $$$b$$$, $$$n$$$, $$$m$$$ ($$$0 \\le a,b,n,m \\le 10^{18}, n+m \\neq 0$$$).", "output_spec": "For each test case, print the answer in one line. If there exists at least one valid order, print \"Yes\". Otherwise, print \"No\". You can print each letter in any case (upper or lower).", "sample_inputs": ["6\n2 2 1 2\n0 100 0 1\n12 13 25 1\n27 83 14 25\n0 0 1 0\n1000000000000000000 1000000000000000000 1000000000000000000 1000000000000000000"], "sample_outputs": ["Yes\nNo\nNo\nYes\nNo\nYes"], "notes": "NoteIn the first test case, let's consider the order $$$\\{1, 2, 2\\}$$$ of types of guests. Then: The first guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$1$$$ chocolate cookie. The second guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$0$$$ chocolate cookies. The last guest selects a chocolate cookie, but there are no chocolate cookies. So, the guest gets angry. So, this order can't be chosen by Anna.Let's consider the order $$$\\{2, 2, 1\\}$$$ of types of guests. Then: The first guest eats a vanilla cookie. After that, there is $$$1$$$ vanilla cookie and $$$2$$$ chocolate cookies. The second guest eats a vanilla cookie. After that, there are $$$0$$$ vanilla cookies and $$$2$$$ chocolate cookies. The last guest eats a chocolate cookie. After that, there are $$$0$$$ vanilla cookies and $$$1$$$ chocolate cookie. So, the answer to this test case is \"Yes\".In the fifth test case, it is illustrated, that the number of cookies ($$$a + b$$$) can be equal to zero, but the number of guests ($$$n + m$$$) can't be equal to zero.In the sixth test case, be careful about the overflow of $$$32$$$-bit integer type."}, "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(a, b, n, m) = readLine().split(\" \").map(_.toLong)\n if (m > Math.min(a, b) || n + m > a + b) println(\"NO\")\n else println(\"YES\")\n }\n}\n"}], "negative_code": [], "src_uid": "0f960d19e576b7421a7c7a7166a884ea"} {"nl": {"description": "Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\leq p, a, b, c \\leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.", "output_spec": "For each test case, output one integer\u00a0\u2014 how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.", "sample_inputs": ["4\n9 5 4 8\n2 6 10 9\n10 2 5 10\n10 9 9 9"], "sample_outputs": ["1\n4\n0\n8"], "notes": "NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \\ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \\ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \\ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \\ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \\ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \\ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \\ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side."}, "positive_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 == 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"}, {"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"} {"nl": {"description": "The city Valera lives in is going to hold elections to the city Parliament.The city has n districts and n\u2009-\u20091 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.There are n candidates running the elections. Let's enumerate all candidates in some way by integers from 1 to n, inclusive. If the candidate number i will be elected in the city Parliament, he will perform exactly one promise \u2014 to repair all problem roads on the way from the i-th district to the district 1, where the city Parliament is located.Help Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of districts in the city. Then n\u2009-\u20091 lines follow. Each line contains the description of a city road as three positive integers xi, yi, ti (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, 1\u2009\u2264\u2009ti\u2009\u2264\u20092) \u2014 the districts connected by the i-th bidirectional road and the road type. If ti equals to one, then the i-th road isn't the problem road; if ti equals to two, then the i-th road is the problem road. It's guaranteed that the graph structure of the city is a tree.", "output_spec": "In the first line print a single non-negative number k \u2014 the minimum size of the required subset of candidates. Then on the second line print k space-separated integers a1,\u2009a2,\u2009... ak \u2014 the numbers of the candidates that form the required subset. If there are multiple solutions, you are allowed to print any of them.", "sample_inputs": ["5\n1 2 2\n2 3 2\n3 4 2\n4 5 2", "5\n1 2 1\n2 3 2\n2 4 1\n4 5 1", "5\n1 2 2\n1 3 2\n1 4 2\n1 5 2"], "sample_outputs": ["1\n5", "1\n3", "4\n5 4 3 2"], "notes": null}, "positive_code": [{"source_code": "//package codeforces\n\nimport java.util\n\n/**\n * ToDo: describe\n *\n * @author keks\n */\nobject T369C {\n def main(args: Array[String]) {\n val n = readInt()\n val a = new Array[List[(Int, Int)]](n)\n for (i <- 1 until n) {\n val map = readLine().split(' ').map(_.toInt)\n a(map(0) - 1) = (map(1) - 1, map(2)) :: (if (a(map(0) - 1) == null) Nil else a(map(0) - 1))\n a(map(1) - 1) = (map(0) - 1, map(2)) :: (if (a(map(1) - 1) == null) Nil else a(map(1) - 1))\n }\n\n val elections = getMinElections(a)\n println(elections.length + \"\\n\" + elections.mkString(\" \"))\n }\n\n def getMinElections(a: Array[List[(Int, Int)]]) = {\n val nodes = new util.Stack[(Int, Int)]()\n val isBads = new util.Stack[Int]()\n val isUps = new util.Stack[Int]()\n\n val visited = new java.util.HashSet[Int]()\n val list = new util.LinkedList[Int]()\n\n // 1 - gather, 2 - check\n nodes.push((0, 1))\n isBads.push(1)\n isUps.push(0)\n\n while (!nodes.isEmpty) {\n val e = nodes.pop()\n val isUp = isUps.pop()\n if (e._2 == 1) {\n visited.add(e._1)\n nodes.push((e._1, 2))\n isUps.push(list.size)\n val adj = a(e._1)\n if (adj != null) {\n adj.filter(p => !visited.contains(p._1)).map(p => {\n nodes.push((p._1, 1))\n isUps.push(list.size)\n isBads.push(p._2)\n })\n }\n } else {\n val isBad = isBads.pop()\n if (isUp == list.size && isBad == 2) list.add(e._1 + 1)\n }\n }\n\n list.toArray\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces\n\nimport java.util\n\n/**\n * ToDo: describe\n *\n * @author keks\n */\nobject T369C {\n def main(args: Array[String]) {\n val n = readInt()\n val a = new Array[List[(Int, Int)]](n)\n for (i <- 1 until n) {\n val map = readLine().split(' ').map(_.toInt)\n a(map(0) - 1) = (map(1) - 1, map(2)) :: (if (a(map(0) - 1) == null) Nil else a(map(0) - 1))\n a(map(1) - 1) = (map(0) - 1, map(2)) :: (if (a(map(1) - 1) == null) Nil else a(map(1) - 1))\n }\n\n val elections = getMinElections(a)\n println(elections.length + \"\\n\" + elections.mkString(\" \"))\n }\n\n def getMinElections(a: Array[List[(Int, Int)]]) = {\n val nodes = new util.Stack[(Int, Int)]()\n val isBads = new util.Stack[Int]()\n val isUps = new util.Stack[Int]()\n\n val visited = new java.util.HashSet[Int]()\n val list = new util.LinkedList[Int]()\n\n // 1 - gather, 2 - check\n nodes.push((0, 1))\n isBads.push(1)\n isUps.push(0)\n\n while (!nodes.isEmpty) {\n val e = nodes.pop()\n val isUp = isUps.pop()\n if (e._2 == 1) {\n visited.add(e._1)\n nodes.push((e._1, 2))\n isUps.push(list.size)\n val adj = a(e._1)\n if (adj != null) {\n adj.filter(p => !visited.contains(p._1)).map(p => {\n nodes.push((p._1, 1))\n isUps.push(list.size)\n isBads.push(p._2)\n })\n }\n } else {\n val isBad = isBads.pop()\n if (isUp != list.size) isBads.push(2) else if (isBad == 2) list.add(e._1 + 1)\n }\n }\n\n list.toArray\n }\n}\n"}, {"source_code": "//package codeforces\n\nimport java.util\n\n/**\n * ToDo: describe\n *\n * @author keks\n */\nobject T369C {\n def main(args: Array[String]) {\n val n = readInt()\n val a = new Array[List[(Int, Int)]](n)\n for (i <- 1 until n) {\n val map = readLine().split(' ').map(_.toInt)\n a(map(0) - 1) = (map(1) - 1, map(2)) :: (if (a(map(0) - 1) == null) Nil else a(map(0) - 1))\n }\n\n val elections = getMinElections(a)\n println(elections.length)\n print(elections.mkString(\" \"))\n }\n\n def getMinElections(a: Array[List[(Int, Int)]]) = {\n val nodes = new util.Stack[(Int, Int)]()\n val isBads = new util.Stack[Int]()\n val isUps = new util.Stack[Int]()\n\n var elections = List[Int]()\n\n // 1 - gather, 2 - check\n nodes.push((0, 1))\n isBads.push(1)\n isUps.push(0)\n\n while (!nodes.isEmpty) {\n val e = nodes.pop()\n val isUp = isUps.pop()\n if (e._2 == 1) {\n nodes.push((e._1, 2))\n isUps.push(elections.size)\n val adj = a(e._1)\n if (adj != null) {\n adj.map(p => {\n nodes.push((p._1, 1))\n isUps.push(elections.size)\n isBads.push(p._2)\n })\n }\n } else {\n val isBad = isBads.pop()\n if (isUp != elections.size) isBads.push(2) else if (isBad == 2) elections = (e._1 + 1) :: elections\n }\n }\n\n elections\n }\n}\n"}], "src_uid": "6dafebcc521b7523427724753187715a"} {"nl": {"description": "Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type \"di\u2009\u2192\u2009ti\", that means \"replace all digits di in string s with substrings equal to ti\". For example, if s\u2009=\u2009123123, then query \"2\u2009\u2192\u200900\" transforms s to 10031003, and query \"3\u2009\u2192\u2009\" (\"replace 3 by an empty string\") transforms it to s\u2009=\u20091212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007\u00a0(109\u2009+\u20097). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero.Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!", "input_spec": "The first line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105), consisting of digits\u00a0\u2014 the string before processing all the requests. The second line contains a single integer n (0\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of queries. The next n lines contain the descriptions of the queries. The i-th query is described by string \"di->ti\", where di is exactly one digit (from 0 to 9), ti is a string consisting of digits (ti can be an empty string). The sum of lengths of ti for all queries doesn't exceed 105. The queries are written in the order in which they need to be performed.", "output_spec": "Print a single integer \u2014 remainder of division of the resulting number by 1000000007\u00a0(109\u2009+\u20097).", "sample_inputs": ["123123\n1\n2->00", "123123\n1\n3->", "222\n2\n2->0\n0->7", "1000000008\n0"], "sample_outputs": ["10031003", "1212", "777", "1"], "notes": "NoteNote that the leading zeroes are not removed from string s after the replacement (you can see it in the third sample)."}, "positive_code": [{"source_code": "/**\n * Created by Bo You on 2014/9/8.\n */\nobject Main {\n\n def input(): (String, List[String]) = {\n val s = readLine()\n val n = readLine().toInt\n var rule = List[String]()\n for (i <- 1 to n) {\n rule = rule.+:(readLine())\n }\n return (s, rule)\n }\n\n def solve(s: String, rule: List[String]): Long = {\n\n val MOD = 1000000007\n val D = 10\n\n def modAdd(x: Int, y: Int): Int = {\n return (x + y) % MOD;\n }\n def modMultiply(x: Int, y: Int): Int = {\n return ((x.toLong * y) % MOD).toInt\n }\n def iter(h: Array[Int], p10: Array[Int], rem: List[String]): (Array[Int], Array[Int]) = {\n def parse(r: String): (Int, Array[Int]) = {\n return (r(0) - '0', r.takeRight(r.length - 3).map(_ - '0').toArray)\n }\n def evaluate(np10: Int, nh: Int, pos: Int, r: Array[Int], p10: Array[Int], h: Array[Int]): (Int, Int) = {\n if (pos == r.length) {\n return (np10, nh)\n } else {\n val d = r(pos)\n return evaluate(modMultiply(np10, p10(d)), modAdd(modMultiply(nh, p10(d)), h(d)), pos + 1, r, p10, h)\n }\n }\n if (rem.isEmpty) {\n return (h, p10)\n } else {\n val (src, dst) = parse(rem.head)\n val (np10, nh) = evaluate(1, 0, 0, dst, p10, h)\n h.update(src, nh)\n p10.update(src, np10)\n return iter(h, p10, rem.tail)\n }\n }\n\n val (h, p10) = iter((0 to D - 1).toArray, (0 to D - 1).map(_ => 10).toArray, rule)\n var ret = 0L\n for (ch <- s) {\n val d = ch - '0'\n ret = (ret * p10(d) + h(d)) % MOD\n }\n return ret\n\n }\n\n def main(args: Array[String]) {\n val (s, rule) = input()\n println(solve(s, rule))\n }\n\n}\n"}], "negative_code": [], "src_uid": "c315870f5798dfd75ddfc76c7e3f6fa5"} {"nl": {"description": "String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings \"DOG\" and \"GOD\" are anagrams, so are strings \"BABA\" and \"AABB\", but strings \"ABBAC\" and \"CAABA\" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us \"dictionary\" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1\u2009=\u2009q1, p2\u2009=\u2009q2, ..., pk\u2009-\u20091\u2009=\u2009qk\u2009-\u20091, pk\u2009<\u2009qk for some k (1\u2009\u2264\u2009k\u2009\u2264\u2009n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.", "input_spec": "The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.", "output_spec": "In the first line print z \u2014 the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.", "sample_inputs": ["ABA\nCBA", "CDBABC\nADCABD"], "sample_outputs": ["1\nABC", "2\nADBADC"], "notes": "NoteThe second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: \"ADBADC\", \"ADDABC\", \"CDAABD\", \"CDBAAD\", \"CDBADA\", \"CDDABA\", \"DDAABC\", \"DDBAAC\". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is \"ADBADC\"."}, "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"}, {"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; //\u914d\u5217\u306f()\u3002++\u306f\u99c4\u76ee\n cnts(e - 'A') += 1;\n }\n for(e <- t) at(e - 'A') += 1; //{}\u306f\u7701\u7565\u53ef\u80fd\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\u3067\u306f\u99c4\u76ee*/\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; //\u914d\u5217\u306f()\u3002++\u306f\u99c4\u76ee\n cnts(e - 'A') += 1;\n }\n for(e <- t) at(e - 'A') += 1; //{}\u306f\u7701\u7565\u53ef\u80fd\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\u3067\u306f\u99c4\u76ee*/\n }\n\n}"}], "src_uid": "b9766f25c8ae179c30521770422ce18b"} {"nl": {"description": "Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: \".\" \u2014 an empty cell; \"*\" \u2014 a cell with road works; \"S\" \u2014 the cell where Igor's home is located; \"T\" \u2014 the cell where Igor's office is located. It is guaranteed that \"S\" and \"T\" appear exactly once each.", "output_spec": "In the only line print \"YES\" if there is a path between Igor's home and Igor's office with no more than two turns, and \"NO\" otherwise.", "sample_inputs": ["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."], "sample_outputs": ["YES", "NO"], "notes": "NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: "}, "positive_code": [{"source_code": "import io.StdIn.readLine\n\nobject B1 extends App {\n val Array(n, m) = readLine.split(' ').map(_.toInt)\n\n def find(xx: Array[Array[Char]], char: Char): (Int, Int) =\n xx.indices.flatMap { i =>\n val j = xx(i).indexOf(char)\n if (j < 0) None else Some((i, j))\n }.head\n\n def line(s: Array[Char], in: Int): Range = {\n val end = s.drop(in + 1).prefixLength(c => c != '*')\n val start = s.take(in).view.reverse.prefixLength(c => c != '*')\n (in - start) to (in + end)\n }\n\n def search(xx: Array[Array[Char]]): Boolean = {\n val (sx, sy) = find(xx, 'S')\n val (tx, ty) = find(xx, 'T')\n val searchIn = line(xx(sx), sy) intersect line(xx(tx), ty)\n searchIn.exists(j => sx.min(tx) to sx.max(tx) forall (i => xx(i)(j) != '*'))\n }\n\n val ss = Array.fill(n)(readLine.toCharArray)\n\n println(if (search(ss) || search(ss.transpose)) \"YES\" else \"NO\")\n}"}], "negative_code": [], "src_uid": "16a1c5dbe8549313bae6bca630047502"} {"nl": {"description": "The Fair Nut likes kvass very much. On his birthday parents presented him $$$n$$$ kegs of kvass. There are $$$v_i$$$ liters of kvass in the $$$i$$$-th keg. Each keg has a lever. You can pour your glass by exactly $$$1$$$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $$$s$$$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $$$s$$$ liters of kvass.", "input_spec": "The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1 \\le n \\le 10^3$$$, $$$1 \\le s \\le 10^{12}$$$)\u00a0\u2014 the number of kegs and glass volume. The second line contains $$$n$$$ integers $$$v_1, v_2, \\ldots, v_n$$$ ($$$1 \\le v_i \\le 10^9$$$)\u00a0\u2014 the volume of $$$i$$$-th keg.", "output_spec": "If the Fair Nut cannot pour his glass by $$$s$$$ liters of kvass, print $$$-1$$$. Otherwise, print a single integer\u00a0\u2014 how much kvass in the least keg can be.", "sample_inputs": ["3 3\n4 3 5", "3 4\n5 3 4", "3 7\n1 2 3"], "sample_outputs": ["3", "2", "-1"], "notes": "NoteIn the first example, the answer is $$$3$$$, the Fair Nut can take $$$1$$$ liter from the first keg and $$$2$$$ liters from the third keg. There are $$$3$$$ liters of kvass in each keg.In the second example, the answer is $$$2$$$, the Fair Nut can take $$$3$$$ liters from the first keg and $$$1$$$ liter from the second keg.In the third example, the Fair Nut can't pour his cup by $$$7$$$ liters, so the answer is $$$-1$$$."}, "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 = 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}"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "You're given a list of n strings a1,\u2009a2,\u2009...,\u2009an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.Given the list of strings, output the lexicographically smallest concatenation.", "input_spec": "The first line contains integer n \u2014 the number of strings (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7104). Each of the next n lines contains one string ai (1\u2009\u2264\u2009|ai|\u2009\u2264\u200950) consisting of only lowercase English letters. The sum of string lengths will not exceed 5\u00b7104.", "output_spec": "Print the only string a \u2014 the lexicographically smallest string concatenation.", "sample_inputs": ["4\nabba\nabacaba\nbcd\ner", "5\nx\nxx\nxxa\nxxaa\nxxaaa", "3\nc\ncb\ncba"], "sample_outputs": ["abacabaabbabcder", "xxaaaxxaaxxaxxx", "cbacbc"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\n/**\n * Created by whimsy on 16/7/17.\n */\n\n\nobject P632C extends App {\n val n = StdIn.readInt()\n\n var ab = ArrayBuffer[String]()\n for (i <- 0 until n) ab += StdIn.readLine()\n val answer = ab.sortWith((a, b) => a + b < b + a)\n .foldLeft(new StringBuffer())((z, i) => z.append(i))\n\n println(answer)\n\n}\n\n"}], "negative_code": [], "src_uid": "930365b084022708eb871f3ca2f269e4"} {"nl": {"description": "This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions: The length of $$$t$$$ does not exceed the length of $$$s$$$. $$$t$$$ is a palindrome. There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( \"$$$+$$$\" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$. ", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$5000$$$.", "output_spec": "For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.", "sample_inputs": ["5\na\nabcdfdcecba\nabbaxyzyx\ncodeforces\nacbba"], "sample_outputs": ["a\nabcdfdcba\nxyzyx\nc\nabba"], "notes": "NoteIn the first test, the string $$$s = $$$\"a\" satisfies all conditions.In the second test, the string \"abcdfdcba\" satisfies all conditions, because: Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$. It is a palindrome. \"abcdfdcba\" $$$=$$$ \"abcdfdc\" $$$+$$$ \"ba\", and \"abcdfdc\" is a prefix of $$$s$$$ while \"ba\" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string \"c\" is correct, because \"c\" $$$=$$$ \"c\" $$$+$$$ \"\" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is \"s\"."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob \u2014 from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the amount of bars on the table. The second line contains a sequence t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u20091000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).", "output_spec": "Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.", "sample_inputs": ["5\n2 9 8 2 7"], "sample_outputs": ["2 3"], "notes": null}, "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 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"}, {"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 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}"}, {"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"}], "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"} {"nl": {"description": "There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: <hostname>\u00a0\u2014 server name (consists of words and maybe some dots separating them), /<path>\u00a0\u2014 optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa\u00a0\u2014 for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.", "output_spec": "First print k\u00a0\u2014 the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.", "sample_inputs": ["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"], "sample_outputs": ["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "9b35f7df9e21162858a8fac8ee2837a4"} {"nl": {"description": "Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $$$(0, 0)$$$. Robot can perform the following four kinds of operations: U \u2014 move from $$$(x, y)$$$ to $$$(x, y + 1)$$$; D \u2014 move from $$$(x, y)$$$ to $$$(x, y - 1)$$$; L \u2014 move from $$$(x, y)$$$ to $$$(x - 1, y)$$$; R \u2014 move from $$$(x, y)$$$ to $$$(x + 1, y)$$$. Vasya also has got a sequence of $$$n$$$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $$$(x, y)$$$.Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $$$maxID - minID + 1$$$, where $$$maxID$$$ is the maximum index of a changed operation, and $$$minID$$$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $$$2$$$, $$$5$$$ and $$$7$$$ are changed, so the length of changed subsegment is $$$7 - 2 + 1 = 6$$$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $$$1$$$. If there are no changes, then the length of changed subsegment is $$$0$$$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $$$(0, 0)$$$ to $$$(x, y)$$$, or tell him that it's impossible.", "input_spec": "The first line contains one integer number $$$n~(1 \\le n \\le 2 \\cdot 10^5)$$$ \u2014 the number of operations. The second line contains the sequence of operations \u2014 a string of $$$n$$$ characters. Each character is either U, D, L or R. The third line contains two integers $$$x, y~(-10^9 \\le x, y \\le 10^9)$$$ \u2014 the coordinates of the cell where the robot should end its path.", "output_spec": "Print one integer \u2014 the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from $$$(0, 0)$$$ to $$$(x, y)$$$. If this change is impossible, print $$$-1$$$.", "sample_inputs": ["5\nRURUU\n-2 3", "4\nRULR\n1 1", "3\nUUU\n100 100"], "sample_outputs": ["3", "0", "-1"], "notes": "NoteIn the first example the sequence can be changed to LULUU. So the length of the changed subsegment is $$$3 - 1 + 1 = 3$$$.In the second example the given sequence already leads the robot to $$$(x, y)$$$, so the length of the changed subsegment is $$$0$$$.In the third example the robot can't end his path in the cell $$$(x, y)$$$."}, "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 D = ns(N)\n val x, y = ni()\n\n if (N < abs(x) + abs(y)) {\n out.println(-1)\n return\n }\n\n val cumX, cumY = Array.ofDim[Int](N + 1)\n rep(N) { i =>\n val (dx, dy) = D(i) match {\n case 'R' => (1, 0)\n case 'L' => (-1, 0)\n case 'U' => (0, 1)\n case 'D' => (0, -1)\n }\n cumX(i + 1) = cumX(i) + dx\n cumY(i + 1) = cumY(i) + dy\n }\n\n def calc(len: Int): Boolean = {\n 0 to N - len foreach { iLen =>\n val i = iLen\n val jLen = N - len - iLen\n val j = N - jLen\n val x1 = cumX(i)\n val x2 = cumX(N) - cumX(j)\n val y1 = cumY(i)\n val y2 = cumY(N) - cumY(j)\n val dist = abs(x - x1 - x2) + abs(y - y1 - y2)\n if (dist <= len && (len - dist) % 2 == 0) return true\n// if (dist <= len) return true\n }\n false\n }\n\n var l = -1\n var r = N + 1\n while(r - l > 1) {\n val mid = (r + l) / 2\n if (calc(mid)) r = mid\n else l = mid\n }\n\n if (r == 0) out.println(0)\n else if (r == N + 1) out.println(-1)\n else out.println(r)\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 D = ns(N)\n val x, y = ni()\n val cumX, cumY = Array.ofDim[Int](N + 1)\n rep(N) { i =>\n val (dx, dy) = D(i) match {\n case 'R' => (1, 0)\n case 'L' => (-1, 0)\n case 'U' => (0, 1)\n case 'D' => (0, -1)\n }\n cumX(i + 1) = cumX(i) + dx\n cumY(i + 1) = cumY(i) + dy\n }\n\n def calc(len: Int): Boolean = {\n rep(N - len) { i =>\n val j = i + len\n val x1 = cumX(i)\n val x2 = cumX(N) - cumX(j)\n val y1 = cumY(i)\n val y2 = cumY(N) - cumY(j)\n val dist = abs(x - x1 - x2) + abs(y - y1 - y2)\n if (dist <= len) return true\n }\n false\n }\n\n var l = -1\n var r = N + 1\n while(r - l > 1) {\n val mid = (r + l) / 2\n if (calc(mid)) r = mid\n else l = mid\n }\n\n if (r == 0) out.println(0)\n else if (r == N + 1) out.println(-1)\n else out.println(r)\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 D = ns(N)\n val x, y = ni()\n\n if (N < abs(x) + abs(y)) {\n out.println(-1)\n return\n }\n\n val cumX, cumY = Array.ofDim[Int](N + 1)\n rep(N) { i =>\n val (dx, dy) = D(i) match {\n case 'R' => (1, 0)\n case 'L' => (-1, 0)\n case 'U' => (0, 1)\n case 'D' => (0, -1)\n }\n cumX(i + 1) = cumX(i) + dx\n cumY(i + 1) = cumY(i) + dy\n }\n\n def calc(len: Int): Boolean = {\n rep(N - len + 1) { i =>\n val j = i + len\n val x1 = cumX(i)\n val x2 = cumX(N) - cumX(j)\n val y1 = cumY(i)\n val y2 = cumY(N) - cumY(j)\n val dist = abs(x - x1 - x2) + abs(y - y1 - y2)\n if (dist <= len) return true\n }\n false\n }\n\n var l = -1\n var r = N + 1\n while(r - l > 1) {\n val mid = (r + l) / 2\n if (calc(mid)) r = mid\n else l = mid\n }\n\n if (r == 0) out.println(0)\n else if (r == N + 1) out.println(-1)\n else out.println(r)\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": "44cf7e01a72d7d8182b05678a7e5b5d3"} {"nl": {"description": "Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: Add the integer xi to the first ai elements of the sequence. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1) Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!", "input_spec": "The first line contains a single integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20093), denoting the type of the operation (see above). If ti\u2009=\u20091, it will be followed by two integers ai,\u2009xi (|xi|\u2009\u2264\u2009103;\u00a01\u2009\u2264\u2009ai). If ti\u2009=\u20092, it will be followed by a single integer ki (|ki|\u2009\u2264\u2009103). If ti\u2009=\u20093, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.", "output_spec": "Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["5\n2 1\n3\n2 3\n2 1\n3", "6\n2 1\n1 2 20\n2 2\n1 2 -3\n3\n3"], "sample_outputs": ["0.500000\n0.000000\n1.500000\n1.333333\n1.500000", "0.500000\n20.500000\n14.333333\n12.333333\n17.500000\n17.000000"], "notes": "NoteIn the second sample, the sequence becomes "}, "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 additions = Array.ofDim[Long](n + 1)\n val data = Array.ofDim[Long](n + 1)\n var sum = 0l\n var length = 1\n println((1 to n).map { _ =>\n in.next().split(' ').map(_.toInt) match {\n case Array(1, x, add) =>\n additions(x - 1) += add\n sum += add * x\n sum.toDouble / length\n case Array(2, k) =>\n data(length) = k\n additions(length) = 0\n length += 1\n sum += k\n sum.toDouble / length\n case Array(3) =>\n if (length > 1)\n additions(length - 2) += additions(length - 1)\n sum -= data(length - 1)\n sum -= additions(length - 1)\n length -= 1\n if (length == 0)\n 0\n else\n sum.toDouble / length\n }\n\n }.mkString(\"\\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 additions = Array.ofDim[Long](n)\n val data = Array.ofDim[Long](n)\n var sum = 0l\n var length = 1\n println((1 to n).map { _ =>\n in.next().split(' ').map(_.toInt) match {\n case Array(1, x, add) =>\n additions(x - 1) += add\n sum += add * x\n sum.toDouble / length\n case Array(2, k) =>\n data(length) = k\n additions(length) = 0\n length += 1\n sum += k\n sum.toDouble / length\n case Array(3) =>\n additions(Math.max(0, length - 2)) = additions(length - 1)\n sum -= data(length - 1)\n sum -= additions(length - 1)\n length -= 1\n if (length == 0)\n 0\n else\n sum.toDouble / length\n }\n\n }.mkString(\"\\n\"))\n\n}\n"}], "src_uid": "d43d4fd6c1e2722da185f34d902ace97"} {"nl": {"description": "Your program fails again. This time it gets \"Wrong answer on test 233\".This is the harder version of the problem. In this version, $$$1 \\le n \\le 2\\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.The problem is to finish $$$n$$$ one-choice-questions. Each of the questions contains $$$k$$$ options, and only one of them is correct. The answer to the $$$i$$$-th question is $$$h_{i}$$$, and if your answer of the question $$$i$$$ is $$$h_{i}$$$, you earn $$$1$$$ point, otherwise, you earn $$$0$$$ points for this question. The values $$$h_1, h_2, \\dots, h_n$$$ are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the $$$n$$$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question $$$i$$$ to the question $$$i \\bmod n + 1$$$. So it moves the answer for the question $$$1$$$ to question $$$2$$$, the answer for the question $$$2$$$ to the question $$$3$$$, ..., the answer for the question $$$n$$$ to the question $$$1$$$.We call all the $$$n$$$ answers together an answer suit. There are $$$k^n$$$ possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $$$1$$$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $$$998\\,244\\,353$$$.For example, if $$$n = 5$$$, and your answer suit is $$$a=[1,2,3,4,5]$$$, it will submitted as $$$a'=[5,1,2,3,4]$$$ because of a mistake. If the correct answer suit is $$$h=[5,2,2,3,4]$$$, the answer suit $$$a$$$ earns $$$1$$$ point and the answer suite $$$a'$$$ earns $$$4$$$ points. Since $$$4 > 1$$$, the answer suit $$$a=[1,2,3,4,5]$$$ should be counted.", "input_spec": "The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$, $$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the number of questions and the number of possible answers to each question. The following line contains $$$n$$$ integers $$$h_1, h_2, \\dots, h_n$$$, ($$$1 \\le h_{i} \\le k)$$$\u00a0\u2014 answers to the questions.", "output_spec": "Output one integer: the number of answers suits satisfying the given condition, modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["3 3\n1 3 1", "5 5\n1 1 4 2 2", "6 2\n1 1 2 2 1 1"], "sample_outputs": ["9", "1000", "16"], "notes": "NoteFor the first example, valid answer suits are $$$[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]$$$."}, "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 // nCk % MOD \u3092\u6c42\u3081\u308b\u3002\u4e0b\u6e96\u5099\u3067\u968e\u4e57F\u3068\u2261MOD\u3067\u306e\u968e\u4e57\u306e\u9006\u5143I\u3092\u4f5c\u308b\n class 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!) \u2261 (x-1)!I((x-1)!)\n // I((x-1)!) \u2261 I(x!) * x MOD\u304c\u3067\u304b\u3044\u306e\u3067(x-1)!\u306fMOD\u3068\u7d20\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\u306e\u30b0\u30eb\u30fc\u30d7\u304b\u3089k\u56de\u91cd\u8907\u3042\u308a\u3067\u9078\u3076\u7d44\u307f\u5408\u308f\u305b\u6570\n * n - 1\u306e\u3057\u304d\u308a\u3068k\u306e\u25cb\u3067\u8003\u3048\u308b\n */\n def H(n: Int, k: Int): Long = {\n comb(n + k - 1, k)\n }\n\n /**\n * private[this]\u3092\u3064\u304b\u3063\u3066\u308b\u306e\u3067getter\u304c\u5fc5\u8981\n * @return (F, I)\n */\n def get: (Array[Long], Array[Long]) = (F, I)\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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 998244353\n\n def solve(): Unit = {\n val N, K = ni()\n val H = na(N)\n var n = 0\n\n if (K == 1) {\n out.println(\"0\")\n return\n }\n\n REP(N) { i =>\n if (H(i) != H((i + 1)%N)) n += 1\n }\n\n var zero = 0L\n val comb = new Comb(N, MOD)\n TO(0, n/2) { k =>\n zero += comb.comb(n, k) *\n comb.comb(n - k, k) % MOD *\n powMod(K - 2, n - 2 * k, MOD) % MOD\n }\n val ss = (MOD + powMod(K, n, MOD) - zero % MOD) % MOD\n val s = ss * (MOD + 1) / 2 % MOD\n debug(s\"$n $zero $ss $s\")\n val ans = s * powMod(K, N - n, MOD) % MOD\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "63c4006a0a6284f9825aaabfc4c28fd1"} {"nl": {"description": "Your city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if either i\u2009=\u2009j or the police patrol car can go to j from i and then come back to i.Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions.You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and in addition in minimum number of checkposts. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other.", "input_spec": "In the first line, you will be given an integer n, number of junctions (1\u2009\u2264\u2009n\u2009\u2264\u2009105). In the next line, n space-separated integers will be given. The ith integer is the cost of building checkpost at the ith junction (costs will be non-negative and will not exceed 109). The next line will contain an integer m\u00a0(0\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105). And each of the next m lines contains two integers ui and vi\u00a0(1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n;\u00a0u\u2009\u2260\u2009v). A pair ui,\u2009vi means, that there is a one-way road which goes from ui to vi. There will not be more than one road between two nodes in the same direction.", "output_spec": "Print two integers separated by spaces. The first one is the minimum possible money needed to ensure the security of all the junctions. And the second one is the number of ways you can ensure the security modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["3\n1 2 3\n3\n1 2\n2 3\n3 2", "5\n2 8 0 6 0\n6\n1 4\n1 3\n2 4\n3 4\n4 5\n5 1", "10\n1 3 2 2 1 3 1 4 10 10\n12\n1 2\n2 3\n3 1\n3 4\n4 5\n5 6\n5 7\n6 4\n7 3\n8 9\n9 10\n10 9", "2\n7 91\n2\n1 2\n2 1"], "sample_outputs": ["3 1", "8 2", "15 6", "7 1"], "notes": null}, "positive_code": [{"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"}, {"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 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"}], "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"} {"nl": {"description": "Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer x.You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l\u2009\u2264\u2009x\u2009\u2264\u2009r, and is maximum possible. If there are multiple such numbers find the smallest of them.", "input_spec": "The first line contains integer n\u00a0\u2014 the number of queries (1\u2009\u2264\u2009n\u2009\u2264\u200910000). Each of the following n lines contain two integers li,\u2009ri\u00a0\u2014 the arguments for the corresponding query (0\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u20091018).", "output_spec": "For each query print the answer in a separate line.", "sample_inputs": ["3\n1 2\n2 4\n1 10"], "sample_outputs": ["1\n3\n7"], "notes": "NoteThe binary representations of numbers from 1 to 10 are listed below:110\u2009=\u200912210\u2009=\u2009102310\u2009=\u2009112410\u2009=\u20091002510\u2009=\u20091012610\u2009=\u20091102710\u2009=\u20091112810\u2009=\u200910002910\u2009=\u2009100121010\u2009=\u200910102"}, "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 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}"}, {"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"} {"nl": {"description": "A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of compartments in the carriage. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an showing how many students ride in each compartment (0\u2009\u2264\u2009ai\u2009\u2264\u20094). It is guaranteed that at least one student is riding in the train.", "output_spec": "If no sequence of swapping seats with other people leads to the desired result, print number \"-1\" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.", "sample_inputs": ["5\n1 2 2 4 3", "3\n4 1 1", "4\n0 3 0 4"], "sample_outputs": ["2", "2", "0"], "notes": null}, "positive_code": [{"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c// + move(1, 3)\n }\n\n def consolidate2() = {\n val c = counts(2) / 3\n counts(2) = counts(2) % 3\n counts(3) += 2 * c\n if (counts(2) == 2) {\n counts(2) = 0\n counts(4) += 1\n 2 * c + 2\n } else 2 * c\n }\n\n var moves = move(1, 2) + consolidate1() + consolidate2() //+ move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3)\n \n if (counts(1) == 1) {\n\t moves += move(1, 3) + move(4, 1) + move(4, 2)\n } else if (counts(1) == 2) {\n if (counts(3) > 1) moves += move(1, 3) \n else if (counts(4) > 0){\n moves += 2\n counts(1) = 0\n } \n } else if (counts(2) == 1) {\n moves += move(4, 2) + move(2, 3) + move(1, 3)\n }\n //+ move(4, 1) + move(1, 2) + move(4, 2)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n \n if (counts(2) == 2) {\n moves += 2\n counts(2) = 0\n }\n//println(counts(1), counts(2), counts(3), counts(4))\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}], "negative_code": [{"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c// + move(1, 3)\n }\n\n def consolidate2() = {\n val c = counts(2) / 3\n counts(2) = counts(2) % 3\n 2 * c\n }\n\n var moves = move(1, 2) + consolidate1() + consolidate2() + move(4, 2) // //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n//println(counts(1), counts(2), counts(3), counts(4))\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}, {"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c// + move(1, 3)\n }\n\n def consolidate2() = {\n val c = counts(2) / 2\n counts(2) = 0\n 2 * c\n }\n\n var moves = move(1, 2) + consolidate1() + move(4, 2) + consolidate2() + move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n\n/*println(counts(1), counts(2))\n if (counts(2) > 1) {\n val consolidate2 = counts(2) / 2\n moves += consolidate2 * 2\n counts(2) = 0\n }\n\n moves += consolidate1()*/\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}, {"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c + move(1, 3)\n }\n\n var moves = move(1, 2) + consolidate1() + move(4, 2) + move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n\n if (counts(2) > 1) {\n val consolidate2 = counts(2) / 2\n moves += consolidate2 * 2\n counts(2) = 0\n }\n\n moves += consolidate1()\n\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}, {"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n var moves = move(1, 2) + move(4, 2) + move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n\n if (counts(2) > 1) {\n val consolidate2 = counts(2) / 2\n moves += consolidate2 * 2\n counts(2) = 0\n }\n\n val consolidate1 = counts(1) / 3\n moves += consolidate1 * 2\n counts(3) += consolidate1\n counts(1) -= 3 * consolidate1\n moves += move(1, 3)\n\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}, {"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c// + move(1, 3)\n }\n\n def consolidate2() = {\n val c = counts(2) / 3\n counts(2) = counts(2) % 3\n counts(3) += 2 * c\n if (counts(2) == 2) {\n counts(2) = 0\n counts(4) += 1\n 2 * c + 2\n } else 2 * c\n }\n\n var moves = move(1, 2) + consolidate1() + consolidate2() //+ move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3)\n \n if (counts(1) == 1) {\n\t moves += move(1, 3) + move(4, 1) + move(4, 2)\n } else if (counts(1) == 2) {\n if (counts(3) > 1) moves += move(1, 3) \n else if (counts(4) > 0){\n moves += 2\n counts(1) = 0\n } \n } else if (counts(2) == 1) {\n moves += move(4, 2)\n }\n //+ move(4, 1) + move(1, 2) + move(4, 2)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n \n if (counts(2) == 2) {\n moves += 2\n counts(2) = 0\n }\n//println(counts(1), counts(2), counts(3), counts(4))\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}, {"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c// + move(1, 3)\n }\n\n def consolidate2() = {\n val c = counts(2) / 3\n counts(2) = counts(2) % 3\n 2 * c\n }\n\n var moves = move(1, 2) + consolidate1() + consolidate2() + move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3) + move(4, 1) + move(1, 2) + move(4, 2)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n \n if (counts(2) == 2) {\n moves += 2\n counts(2) = 0\n }\n//println(counts(1), counts(2), counts(3), counts(4))\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}, {"source_code": "import scala.collection._\n\nobject E extends App {\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 counts = Array.fill(5)(0)\n\n val n = readString.toInt\n readInts(n).foreach(counts(_) += 1)\n\n def move(from: Int, to: Int) = {\n val can = counts(from) min counts(to)\n counts(from) -= can\n counts(from - 1) += can\n counts(to + 1) += can\n counts(to) -= can\n can\n }\n\n def consolidate1() = {\n val c = counts(1) / 3\n counts(3) += c\n counts(1) -= 3 * c\n 2 * c// + move(1, 3)\n }\n\n def consolidate2() = {\n val c = counts(2) / 3\n counts(2) = counts(2) % 3\n 2 * c\n }\n\n var moves = move(1, 2) + consolidate1() + consolidate2() + move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)\n//println(counts(1), counts(2), counts(3), counts(4))\n println(if (counts(1) + counts(2) > 0) -1 else moves)\n}"}], "src_uid": "a7cdb90a03447fc9285819ed059383b3"} {"nl": {"description": "Students went into a class to write a test and sat in some way. The teacher thought: \"Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating.\"The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.Let's enumerate students from 1 to n\u00b7m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i\u2009-\u20091)\u00b7m\u2009+\u2009j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n\u00b7m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.", "input_spec": "The only line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105; n\u00b7m\u2009\u2264\u2009105)\u00a0\u2014 the number of rows and the number of columns in the required matrix.", "output_spec": "If there is no such matrix, output \"NO\" (without quotes). Otherwise in the first line output \"YES\" (without quotes), and in the next n lines output m integers which form the required matrix.", "sample_inputs": ["2 4", "2 1"], "sample_outputs": ["YES\n5 4 7 2 \n3 6 1 8", "NO"], "notes": "NoteIn the first test case the matrix initially looks like this:1 2 3 45 6 7 8It's easy to see that there are no two students that are adjacent in both matrices.In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors."}, "positive_code": [{"source_code": "object 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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) {\n println(\"YES\")\n println(1)\n } else if (n == 3 && m == 3) {\n println(\"YES\")\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs0 = Array.tabulate(n0, m0) { (r, c) =>\n r * m0 + c + 1\n }\n\n val xs = if (n0 > m0) xs0.transpose else xs0\n \n for {\n r <- 0 until n\n } {\n if (r % 2 == 1) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 2) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t3\n xs(r)(oo + 1) = t1\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n } else if (m % 4 == 3) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n } else if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 == 2) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t1\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t3\n } else if (m % 4 == 3) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object 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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) {\n println(\"YES\")\n println(1)\n } else if (n == 3 && m == 3) {\n println(\"YES\")\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs0 = Array.tabulate(n0, m0) { (r, c) =>\n r * m0 + c + 1\n }\n\n val xs = if (n0 > m0) xs0.transpose else xs0\n\n for {\n r <- 0 until n\n } {\n if (r % 2 == 1) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 == 2) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t1\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t3\n } else if (m % 4 == 3) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "\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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) {\n println(\"YES\")\n println(1)\n } else if (n == 3 && m == 3) {\n println(\"YES\")\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs = Array.tabulate(n, m) { (r, c) =>\n r * m + c + 1\n }\n //xs.foreach(row => println(row.mkString(\" \")))\n for {\n r <- 0 until n\n } {\n if (r % 2 == 0) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "object 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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) {\n println(\"YES\")\n println(1)\n } else if (n == 3 && m == 3) {\n println(\"YES\")\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs = Array.tabulate(n, m) { (r, c) =>\n r * m + c + 1\n }\n\n for {\n r <- 0 until n\n } {\n if (r % 2 == 1) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 == 2) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t1\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t3\n } else if (m % 4 == 3) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "\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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) println(1)\n else if (n == 3 && m == 3) {\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs = Array.tabulate(n, m) { (r, c) =>\n r * m + c + 1\n }\n //xs.foreach(row => println(row.mkString(\" \")))\n for {\n r <- 0 until n\n } {\n// if (r % 2 == 1) {\n// val rev = Array.ofDim[Int](m)\n// for (i <- 0 until m) rev(i) = xs(r)(m - i - 1)\n// xs(r) = rev\n// }\n if (r % 2 == 0) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 0) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 > 0) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "\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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) println(1)\n else if (n == 3 && m == 3) {\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs = Array.tabulate(n, m) { (r, c) =>\n r * m + c + 1\n }\n //xs.foreach(row => println(row.mkString(\" \")))\n for {\n r <- 0 until n\n } {\n// if (r % 2 == 1) {\n// val rev = Array.ofDim[Int](m)\n// for (i <- 0 until m) rev(i) = xs(r)(m - i - 1)\n// xs(r) = rev\n// }\n if (r % 2 == 0) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 0) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 > 0) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "object 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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) {\n println(\"YES\")\n println(1)\n } else if (n == 3 && m == 3) {\n println(\"YES\")\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs0 = Array.tabulate(n0, m0) { (r, c) =>\n r * m0 + c + 1\n }\n\n val xs = if (n0 > m0) xs0.transpose else xs0\n \n for {\n r <- 0 until n\n } {\n if (r % 2 == 1) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 2) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t3\n xs(r)(oo + 1) = t1\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n } else if (m % 4 == 3) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n } else if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 == 2) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t1\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t3\n } else if (m % 4 == 3) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "\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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) println(1)\n else if (n == 3 && m == 3) {\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs = Array.tabulate(n, m) { (r, c) =>\n r * m + c + 1\n }\n //xs.foreach(row => println(row.mkString(\" \")))\n for {\n r <- 0 until n\n } {\n if (r % 2 == 0) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}, {"source_code": "\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 val Array(n0, m0) = readInts(2)\n val n = n0 min m0\n val m = n0 max m0\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 1 && m == 1) {\n println(\"YES\")\n println(1)\n } else if (n == 2 && m == 3) {\n println(\"YES\")\n println(\"2 6 1\")\n println(\"4 3 5\")\n } else if (n == 3 && m == 2) {\n println(\"YES\")\n println(\"2 4\")\n println(\"6 3\")\n println(\"1 5\")\n } else if (n == 3 && m == 3) {\n println(\"YES\")\n println(\"8 3 4\")\n println(\"1 5 9\")\n println(\"6 7 2\")\n } else if (n <= 3 && m <= 3) println(\"NO\") else {\n\n val xs = Array.tabulate(n, m) { (r, c) =>\n r * m + c + 1\n }\n //xs.foreach(row => println(row.mkString(\" \")))\n for {\n r <- 0 until n\n } {\n if (r % 2 == 0) {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t3\n xs(r)(oo + 2) = t0\n xs(r)(oo + 3) = t2\n }\n if (m % 4 == 1) {\n val oo = m - 2\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n xs(r)(oo) = t1\n xs(r)(oo + 1) = t0\n }\n } else {\n for (o <- 0 until m / 4) {\n val oo = 4 * o\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n if (m % 4 > 1) {\n val oo = m - 4\n val t0 = xs(r)(oo)\n val t1 = xs(r)(oo + 1)\n val t2 = xs(r)(oo + 2)\n val t3 = xs(r)(oo + 3)\n xs(r)(oo) = t2\n xs(r)(oo + 1) = t0\n xs(r)(oo + 2) = t3\n xs(r)(oo + 3) = t1\n }\n }\n }\n\n val xs2 = if (n0 > m0) xs.transpose else xs\n\n println(\"YES\")\n xs2.foreach(row => println(row.mkString(\" \")))\n }\n\n Console.flush\n}\n"}], "src_uid": "6e67ca1033b98118b5065779e59a1c98"} {"nl": {"description": "Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly n\u2009/\u20092 piles contain number of candies that is a square of some integer and exactly n\u2009/\u20092 piles contain number of candies that is not a square of any integer.", "input_spec": "First line contains one even integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 number of piles with candies. Second line contains sequence of integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 amounts of candies in each pile.", "output_spec": "Output minimal number of steps required to make exactly n\u2009/\u20092 piles contain number of candies that is a square of some integer and exactly n\u2009/\u20092 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.", "sample_inputs": ["4\n12 14 30 4", "6\n0 0 0 0 0 0", "6\n120 110 23 34 25 45", "10\n121 56 78 81 45 100 1 0 54 78"], "sample_outputs": ["2", "6", "3", "0"], "notes": "NoteIn first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).In second example you should add two candies to any three piles."}, "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"}, {"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"}], "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"} {"nl": {"description": "Masha has $$$n$$$ types of tiles of size $$$2 \\times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \\times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \\times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 100$$$) \u2014 the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines. The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ \u2014 the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ \u2014 the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.", "output_spec": "For each test case print the answer: \"YES\" (without quotes) if Masha can construct the square of size $$$m \\times m$$$ which is a symmetric matrix. Otherwise, print \"NO\" (withtout quotes).", "sample_inputs": ["6\n3 4\n1 2\n5 6\n5 7\n7 4\n8 9\n9 8\n2 5\n1 1\n1 1\n2 2\n2 2\n1 100\n10 10\n10 10\n1 2\n4 5\n8 4\n2 2\n1 1\n1 1\n1 2\n3 4\n1 2\n1 1\n1 1"], "sample_outputs": ["YES\nNO\nYES\nNO\nYES\nYES"], "notes": "NoteThe first test case of the input has three types of tiles, they are shown on the picture below. Masha can construct, for example, the following square of size $$$4 \\times 4$$$ which is a symmetric matrix: "}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k\u2009-\u20091 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.", "input_spec": "The first line of the input contains two integers n,\u2009k\u00a0(1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k.", "output_spec": "In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.", "sample_inputs": ["6 2\n3 2 1 6 5 4", "10 5\n1 3 5 7 9 9 4 1 8 5"], "sample_outputs": ["1", "3"], "notes": "NoteExplanation of the first example.If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example.In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3."}, "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": "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}"}, {"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"} {"nl": {"description": "AquaMoon has $$$n$$$ friends. They stand in a row from left to right, and the $$$i$$$-th friend from the left wears a T-shirt with a number $$$a_i$$$ written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.AquaMoon hopes that after some operations, the numbers written on the T-shirt of $$$n$$$ friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 50$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the number of Aquamoon's friends. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^5$$$) \u2014 the numbers, written on the T-shirts. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, if there exists a possible sequence of operations, print \"YES\" (without quotes); otherwise, print \"NO\" (without quotes). You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n4\n4 3 2 5\n4\n3 3 2 2\n5\n1 2 3 5 4"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteThe possible list of operations in the first test case: Swap $$$a_1$$$ and $$$a_2$$$. The resulting sequence is $$$3, 4, 2, 5$$$. The directions are: left, left, right, right. Swap $$$a_2$$$ and $$$a_3$$$. The resulting sequence is $$$3, 2, 4, 5$$$. The directions are: left, left, right, right. Swap $$$a_1$$$ and $$$a_2$$$. The resulting sequence is $$$2, 3, 4, 5$$$. The directions are: right, right, right, right. "}, "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n def f: Array[Int] => Map[Int, (Int, Int)] =\r\n _.zipWithIndex.foldLeft(Map.empty[Int, (Int, Int)]) { case (map, (ai, i)) =>\r\n val (even, odd) = map.getOrElse(ai, (0, 0))\r\n map.updated(ai, if (i % 2 == 0) (even + 1, odd) else (even, odd + 1))\r\n // map.updatedWith(ai) {\r\n // case Some((even, odd)) => if (i % 2 == 0) Some(even + 1, odd) else Some(even, odd + 1)\r\n // case None => if (i % 2 == 0) Some(1, 0) else Some(0, 1)\r\n // }\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)\r\n\r\n val ans: Boolean = {\r\n val (amap, bmap) = (f(an), f(an.sorted))\r\n amap.foldLeft(true) { case (result, (ai, count)) => result && bmap(ai) == count }\r\n }\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": [{"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 an = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans: Boolean = {\r\n val bn = an.zipWithIndex.sorted\r\n val cn = bn.zipWithIndex.map { case ((ai, i), j) => (ai, math.abs(i - j) % 2) }\r\n\r\n def check(ls: List[Int]): Boolean = ls.forall(_ == 0) || {\r\n val ms = ls.foldLeft(List.empty[Int]) {\r\n case (0 :: ms, 0) => 1 :: 1 :: ms\r\n case (ms, l) => l :: ms\r\n }\r\n\r\n ms.mkString(\"\").split(\"0\").forall(_.length % 2 == 0)\r\n }\r\n\r\n @annotation.tailrec\r\n def go(i: Int, ls: List[Int]): Boolean =\r\n if (i == n) check(ls)\r\n else if (i != 0 && cn(i)._1 == cn(i - 1)._1) go(i + 1, cn(i)._2 :: ls)\r\n else check(ls) && go(i + 1, cn(i)._2 :: Nil)\r\n\r\n go(0, Nil)\r\n }\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"}, {"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 an = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = {\r\n val bn = an.zipWithIndex.sorted\r\n val cn = bn.zipWithIndex.map { case ((ai, i), j) => (ai, (i - j) % 2 == 0) }\r\n\r\n (0 until n).forall { i =>\r\n cn(i) match {\r\n case (ai, false) =>\r\n if (i != 0 && cn(i - 1) == (ai, false)) {\r\n cn(i) = (ai, true)\r\n cn(i - 1) = (ai, true)\r\n true\r\n } else if (i != n - 1 && cn(i + 1) == (ai, false)) {\r\n cn(i) = (ai, true)\r\n cn(i + 1) = (ai, true)\r\n true\r\n } else false\r\n case _ => true\r\n }\r\n }\r\n }\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"}], "src_uid": "1d27d6d736d891b03b7476f8a7209291"} {"nl": {"description": "You are given an array consisting of n non-negative integers a1,\u2009a2,\u2009...,\u2009an.You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the length of the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line contains a permutation of integers from 1 to n\u00a0\u2014 the order used to destroy elements.", "output_spec": "Print n lines. The i-th line should contain a single integer\u00a0\u2014 the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.", "sample_inputs": ["4\n1 3 2 5\n3 4 1 2", "5\n1 2 3 4 5\n4 2 3 5 1", "8\n5 5 4 4 6 6 5 5\n5 2 8 7 1 3 4 6"], "sample_outputs": ["5\n4\n3\n0", "6\n5\n5\n1\n0", "18\n16\n11\n8\n8\n6\n6\n0"], "notes": "NoteConsider the first sample: Third element is destroyed. Array is now 1\u00a03\u00a0\u2009*\u2009\u00a05. Segment with maximum sum 5 consists of one integer 5. Fourth element is destroyed. Array is now 1\u00a03\u00a0\u2009*\u2009\u00a0\u2009*\u2009. Segment with maximum sum 4 consists of two integers 1\u00a03. First element is destroyed. Array is now \u2009*\u2009\u00a03\u00a0\u2009*\u2009\u00a0\u2009*\u2009. Segment with maximum sum 3 consists of one integer 3. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0. "}, "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 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}"}, {"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": "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"}, {"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"}], "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"} {"nl": {"description": "Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \\to 2 \\to \\ldots n \\to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\\to$$$ take-off from the $$$1$$$-st planet $$$\\to$$$ landing to the $$$2$$$-nd planet $$$\\to$$$ $$$2$$$-nd planet $$$\\to$$$ take-off from the $$$2$$$-nd planet $$$\\to$$$ $$$\\ldots$$$ $$$\\to$$$ landing to the $$$n$$$-th planet $$$\\to$$$ the $$$n$$$-th planet $$$\\to$$$ take-off from the $$$n$$$-th planet $$$\\to$$$ landing to the $$$1$$$-st planet $$$\\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \\cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 1000$$$)\u00a0\u2014 number of planets. The second line contains the only integer $$$m$$$ ($$$1 \\le m \\le 1000$$$)\u00a0\u2014 weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.", "output_spec": "If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\\frac{|p - q|}{\\max{(1, |q|)}} \\le 10^{-6}$$$.", "sample_inputs": ["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"], "sample_outputs": ["10.0000000000", "-1", "85.4800000000"], "notes": "NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth."}, "positive_code": [{"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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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"}, {"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}"}], "negative_code": [], "src_uid": "d9bd63e03bf51ed87ba73cd15e8ce58d"} {"nl": {"description": "According to a new ISO standard, a flag of every country should have a chequered field n\u2009\u00d7\u2009m, each square should be of one of 10 colours, and the flag should be \u00abstriped\u00bb: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.", "input_spec": "The first line of the input contains numbers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), n \u2014 the amount of rows, m \u2014 the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.", "output_spec": "Output YES, if the flag meets the new ISO standard, and NO otherwise.", "sample_inputs": ["3 3\n000\n111\n222", "3 3\n000\n000\n111", "3 3\n000\n111\n002"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_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(_.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": "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": "\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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Petya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px,\u2009py), a nonzero vector with coordinates (vx,\u2009vy), positive scalars a,\u2009b,\u2009c,\u2009d,\u2009a\u2009>\u2009c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px,\u2009py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px,\u2009py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx,\u2009vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip. ", "input_spec": "The only line of the input contains eight integers px,\u2009py,\u2009vx,\u2009vy (\u2009-\u20091000\u2009\u2264\u2009px,\u2009py,\u2009vx,\u2009vy\u2009\u2264\u20091000,\u2009vx2\u2009+\u2009vy2\u2009>\u20090), a,\u2009b,\u2009c,\u2009d (1\u2009\u2264\u2009a,\u2009b,\u2009c,\u2009d\u2009\u2264\u20091000,\u2009a\u2009>\u2009c).", "output_spec": "Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10\u2009-\u20099.", "sample_inputs": ["8 8 0 2 8 3 4 5"], "sample_outputs": ["8.000000000000 11.000000000000\n4.000000000000 8.000000000000\n6.000000000000 8.000000000000\n6.000000000000 3.000000000000\n10.000000000000 3.000000000000\n10.000000000000 8.000000000000\n12.000000000000 8.000000000000"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\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 var Array(px, py, vx, vy, a, b, c, d) = in.nextLine().split(' ').map(_.toDouble)\n\n var g = Math.sqrt(vx * vx + vy * vy)\n vx = vx / g\n vy = vy / g\n val (rx, ry) = (-vy, vx)\n\n var res = ArrayBuffer.empty[(Double, Double)]\n\n res += Tuple2(px + vx * b, py + vy * b)\n res += Tuple2(px + rx * a / 2, py + ry * a / 2)\n res += Tuple2(px + rx * c / 2, py + ry * c / 2)\n res += Tuple2(px - vx * d + rx * c / 2, py - vy * d + ry * c / 2)\n res += Tuple2(px - vx * d - rx * c / 2, py - vy * d - ry * c / 2)\n res += Tuple2(px - rx * c / 2, py - ry * c / 2)\n res += Tuple2(px - rx * a / 2, py - ry * a / 2)\n\n for (p <- res) {\n println(\"%.10f %.10f\".format(p._1, p._2))\n }\n }\n}"}], "negative_code": [], "src_uid": "2cb1e7e4d25f624da934bce5c628a7ee"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \\dots r] = a_l, a_{l + 1}, \\dots, a_r$$$. The subarray $$$a[l \\dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \\dots < a_r$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer \u2014 the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element.", "sample_inputs": ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"], "sample_outputs": ["4", "2", "2"], "notes": "NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$."}, "positive_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val _ = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toInt)\n var from = 0\n var maxSoFar = calc(data, from, None)\n// println(\"First = \" + maxSoFar)\n// println(calc(data, 0, Some(2)))\n var endIndex = maxSoFar\n\n while (endIndex < data.length) {\n val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1\n val deleteSecond = calc(data, from, Some(endIndex)) - 1\n// println(\"deleteFirst \" + deleteFirst)\n// println(\"deleteSecond \" + deleteSecond)\n maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))\n from = endIndex\n endIndex = from + calc(data, from, None)\n maxSoFar = Math.max(maxSoFar, endIndex - from)\n// println(\"endIndex = \" + endIndex)\n }\n\n println(maxSoFar)\n\n def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {\n 1 + Range(from + 1, data.length)\n .takeWhile(i => removeIndex.contains(i) || (if (removeIndex.contains(i - 1) && i -2 > 0) data(i) > data(i - 2) else data(i) > data(i - 1))).size\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "negative_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val n = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toInt)\n var from = 0\n var maxSoFar = calc(data, from, None)\n// println(\"First = \" + maxSoFar)\n// println(calc(data, 0, Some(2)))\n var endIndex = maxSoFar\n\n while (endIndex < n) {\n val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1\n val deleteSecond = calc(data, from, Some(endIndex)) - 1\n// println(\"deleteFirst \" + deleteFirst)\n// println(\"deleteSecond \" + deleteSecond)\n maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))\n from = endIndex + 1\n endIndex = from + calc(data, from, None)\n maxSoFar = Math.max(maxSoFar, endIndex - from)\n// println(\"endIndex = \" + endIndex)\n }\n\n println(maxSoFar)\n\n def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {\n 1 + Range(from + 1, data.length).takeWhile(i => removeIndex.contains(i) || data(i) > data(i - 1)).size\n }\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 _ = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toInt)\n var from = 0\n var maxSoFar = calc(data, from, None)\n// println(\"First = \" + maxSoFar)\n// println(calc(data, 0, Some(2)))\n var endIndex = maxSoFar\n\n while (endIndex < data.length) {\n val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1\n val deleteSecond = calc(data, from, Some(endIndex)) - 1\n// println(\"deleteFirst \" + deleteFirst)\n// println(\"deleteSecond \" + deleteSecond)\n maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))\n from = endIndex + 1\n endIndex = from + calc(data, from, None)\n maxSoFar = Math.max(maxSoFar, endIndex - from)\n// println(\"endIndex = \" + endIndex)\n }\n\n// println(maxSoFar)\n\n def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {\n 1 + Range(from + 1, data.length)\n .takeWhile(i => removeIndex.contains(i) || (if (removeIndex.contains(i - 1)) data(i) > data(i - 2) else data(i) > data(i - 1))).size\n }\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 _ = stdin.next().toInt\n val data = stdin.next().split(' ').map(_.toInt)\n var from = 0\n var maxSoFar = calc(data, from, None)\n// println(\"First = \" + maxSoFar)\n// println(calc(data, 0, Some(2)))\n var endIndex = maxSoFar\n\n while (endIndex < data.length) {\n val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1\n val deleteSecond = calc(data, from, Some(endIndex)) - 1\n// println(\"deleteFirst \" + deleteFirst)\n// println(\"deleteSecond \" + deleteSecond)\n maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))\n from = endIndex + 1\n endIndex = from + calc(data, from, None)\n maxSoFar = Math.max(maxSoFar, endIndex - from)\n// println(\"endIndex = \" + endIndex)\n }\n\n println(maxSoFar)\n\n def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {\n 1 + Range(from + 1, data.length)\n .takeWhile(i => removeIndex.contains(i) || (if (removeIndex.contains(i - 1) && i -2 > 0) data(i) > data(i - 2) else data(i) > data(i - 1))).size\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "src_uid": "87b8dccfc0e5a63cd209c37cf8aebef0"} {"nl": {"description": "An important meeting is to be held and there are exactly $$$n$$$ people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the $$$i$$$-th person is a non-negative integer $$$a_i$$$. This means that after exactly $$$a_i$$$ talks this person leaves the meeting (and does not talk to anyone else anymore). If $$$a_i = 0$$$, the $$$i$$$-th person leaves the meeting immediately after it starts.A meeting is considered most productive if the maximum possible number of talks took place during it.You are given an array of sociability $$$a$$$, determine which people should talk to each other so that the total number of talks is as large as possible.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014the number of people in the meeting. The second line consists of $$$n$$$ space-separated integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the sociability parameters of all people. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$. It is also guaranteed that the sum of all $$$a_i$$$ (over all test cases and all $$$i$$$) does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ answers to all test cases. On the first line of each answer print the number $$$k$$$\u00a0\u2014 the maximum number of talks possible in a meeting. On each of the next $$$k$$$ lines print two integers $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$ and $$$i \\neq j$$$)\u00a0\u2014 the numbers of people who will have another talk. If there are several possible answers, you may print any of them.", "sample_inputs": ["8\n2\n2 3\n3\n1 2 3\n4\n1 2 3 4\n3\n0 0 2\n2\n6 2\n3\n0 0 2\n5\n8 2 0 1 1\n5\n0 1 0 0 6"], "sample_outputs": ["2\n1 2\n1 2\n3\n1 3\n2 3\n2 3\n5\n1 3\n2 4\n2 4\n3 4\n3 4\n0\n2\n1 2\n1 2\n0\n4\n1 2\n1 5\n1 4\n1 2\n1\n5 2"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.It is an undirected weighted graph on $$$n$$$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $$$0$$$ or $$$1$$$; exactly $$$m$$$ edges have weight $$$1$$$, and all others have weight $$$0$$$.Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$0 \\leq m \\leq \\min(\\frac{n(n-1)}{2},10^5)$$$), the number of vertices and the number of edges of weight $$$1$$$ in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq n$$$, $$$a_i \\neq b_i$$$), the endpoints of the $$$i$$$-th edge of weight $$$1$$$. It is guaranteed that no edge appears twice in the input.", "output_spec": "Output a single integer, the weight of the minimum spanning tree of the graph.", "sample_inputs": ["6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6", "3 0"], "sample_outputs": ["2", "0"], "notes": "NoteThe graph from the first sample is shown below. Dashed edges have weight $$$0$$$, other edges have weight $$$1$$$. One of the minimum spanning trees is highlighted in orange and has total weight $$$2$$$. In the second sample, all edges have weight $$$0$$$ so any spanning tree has total weight $$$0$$$."}, "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 java.security.SecureRandom\nimport scala.annotation.tailrec\n\n\nobject CF_599_D { var br = createBufferedReader(); var debugV = false\n\n import scala.collection.mutable.{Map => MyMap}\n import scala.collection.mutable.{Set => MySet}\n\n //COMMENT ME !\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 start = System.currentTimeMillis()\n val line = readLine\n \tval n = line.int //vertices\n \tval m = line.int //edge w1\n \n \tvar w1Edges = Array.fill(n)(Vector[Int]())\n \tfor(i <- 0 until m) {\n \t val vLine = readLine\n \t val a = vLine.int - 1\n val b = vLine.int - 1\n \t \n w1Edges(a) = w1Edges(a) :+ b\n w1Edges(b) = w1Edges(b) :+ a\n \t}\n \n val durRead = System.currentTimeMillis() - start\n debug(\"durRead=\"+durRead)\n \n var domains = 0\n// w1Edges = w1Edges.sortBy(_.size)\n val processed = MySet[Int]()\n while (processed.size < n) {\n domains += 1\n val startV = (0 until n).find(i => !processed(i)).get\n debug(\"Domain start: \" + (startV+1))\n goBreadth(Seq(startV))\n }\n \n def goBreadth(verts: Seq[Int]): Unit = {\n// debug(\"level: \" + verts.map(_+1).mkString(\",\"))\n// verts.foreach(v => processed += v)\n processed ++= verts\n// var all1ConnectionsVec = Vector[Int]()\n val blockMap = MyMap[Int, Int]().withDefaultValue(0)\n// verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )\n verts.foreach{a =>\n// w1Edges(a).foreach(b => blockMap(b) = blockMap(b) + 1)\n w1Edges(a).foreach(b => blockMap(b) += 1)\n }\n// val all1Connections = all1ConnectionsVec.toSet\n// val all1Connections = verts.flatMap{v =>\n// w1Edges(v)}\n// val unproc = (0 until n).filter(v => !processed(v))\n// val connectedToThisLevel = unproc.filterNot(all1Connections)\n// val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))\n \n var nextLevel = Vector[Int]()\n for (v <- 0 until n) {\n if (!processed(v) && blockMap(v) < verts.size) nextLevel = nextLevel :+ v \n }\n \n if (nextLevel.size > 0) {\n goBreadth(nextLevel)\n }\n }\n\n \tval res = (domains-1) + \"\"\n outLn(res)\n val durFull = System.currentTimeMillis() - start\n debug(s\"durFull=$durFull\")\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 = \"\"\"\n6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n\"\"\" //2\n\nval sa2 = \"\"\"\n3 0\n\"\"\" //0\n\n\nval t1 = \"\"\"\n7 5\n7 5\n1 5\n3 2\n2 6\n3 6\"\"\" //0\n\n\nval sa3 = genBig\n\ndef genBig(): String = {\n val verts = 100000\n val edges = 100000\n var res = s\"\"\"\n$verts $edges\n\"\"\"\n val sr = new SecureRandom()\n val allEdges = (0 until edges).map{i => \n val a = sr.nextInt(verts-1) + 1\n val b = sr.nextInt(verts-1) + 1\n s\"$a $b\"\n }.mkString(\"\\n\")\n res += allEdges\n println(res.take(100))\n res\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\nimport java.security.SecureRandom\nimport scala.annotation.tailrec\n\n\nobject CF_599_D { var br = createBufferedReader(); var debugV = false\n\n //import scala.collection.mutable.{Map => MyMap}\n import scala.collection.mutable.{Set => MySet}\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 start = System.currentTimeMillis()\n val line = readLine\n \tval n = line.int //vertices\n \tval m = line.int //edge w1\n \n \tvar w1Edges = Array.fill(n)(MySet[Int]())\n \tfor(i <- 0 until m) {\n \t val vLine = readLine\n \t val a = vLine.int - 1\n val b = vLine.int - 1\n \t \n w1Edges(a) += b\n w1Edges(b) += a\n \t}\n \n val durRead = System.currentTimeMillis() - start\n debug(\"durRead=\"+durRead)\n \n var domains = 0\n w1Edges = w1Edges.sortBy(x => if(x!=null)x.size else 0)\n val processed = MySet[Int]()\n while (processed.size < n) {\n domains += 1\n val startV = (0 until n).find(i => !processed(i)).get\n goBreadth(Set(startV))\n }\n \n def goBreadth(verts: Set[Int]): Unit = {\n// verts.foreach(v => processed += v)\n processed ++= verts\n// var all1ConnectionsVec = Vector[Int]()\n val all1Connections = MySet[Int]()\n// verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )\n verts.foreach(v => all1Connections ++= w1Edges(v) )\n// val all1Connections = all1ConnectionsVec.toSet\n// val all1Connections = verts.flatMap{v =>\n// w1Edges(v)}\n// val unproc = (0 until n).filter(v => !processed(v))\n// val connectedToThisLevel = unproc.filterNot(all1Connections)\n// val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))\n \n var nextLevel = Vector[Int]()\n for (v <- 0 until n) {\n if (!processed(v) && !all1Connections(v)) nextLevel = nextLevel :+ v \n }\n \n if (nextLevel.size > 0) {\n goBreadth(nextLevel.toSet)\n }\n }\n\n \tval res = (domains-1) + \"\"\n outLn(res)\n val durFull = System.currentTimeMillis() - start\n debug(s\"durFull=$durFull\")\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 = \"\"\"\n6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n\"\"\" //2\n\nval sa2 = \"\"\"\n3 0\n\"\"\" //0\n\n\nval sa3 = genBig\n\ndef genBig(): String = {\n val verts = 100000\n val edges = 100000\n var res = s\"\"\"\n$verts $edges\n\"\"\"\n val sr = new SecureRandom()\n val allEdges = (0 until edges).map{i => \n val a = sr.nextInt(verts-1) + 1\n val b = sr.nextInt(verts-1) + 1\n s\"$a $b\"\n }.mkString(\"\\n\")\n res += allEdges\n println(res.take(100))\n res\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\nimport java.security.SecureRandom\nimport scala.annotation.tailrec\n\n\nobject CF_599_D { var br = createBufferedReader(); var debugV = false\n\n //import scala.collection.mutable.{Map => MyMap}\n import scala.collection.mutable.{Set => MySet}\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 start = System.currentTimeMillis()\n val line = readLine\n \tval n = line.int //vertices\n \tval m = line.int //edge w1\n \n \tvar w1Edges = Array.fill(n)(Vector[Int]())\n \tfor(i <- 0 until m) {\n \t val vLine = readLine\n \t val a = vLine.int - 1\n val b = vLine.int - 1\n \t \n w1Edges(a) = w1Edges(a) :+ b\n w1Edges(b) = w1Edges(b) :+ a\n \t}\n \n val durRead = System.currentTimeMillis() - start\n debug(\"durRead=\"+durRead)\n \n var domains = 0\n// w1Edges = w1Edges.sortBy(_.size)\n val processed = MySet[Int]()\n while (processed.size < n) {\n domains += 1\n val startV = (0 until n).find(i => !processed(i)).get\n goBreadth(Set(startV))\n }\n \n def goBreadth(verts: Set[Int]): Unit = {\n// verts.foreach(v => processed += v)\n processed ++= verts\n// var all1ConnectionsVec = Vector[Int]()\n val all1Connections = MySet[Int]()\n// verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )\n verts.foreach(v => all1Connections ++= w1Edges(v) )\n// val all1Connections = all1ConnectionsVec.toSet\n// val all1Connections = verts.flatMap{v =>\n// w1Edges(v)}\n// val unproc = (0 until n).filter(v => !processed(v))\n// val connectedToThisLevel = unproc.filterNot(all1Connections)\n// val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))\n \n var nextLevel = Vector[Int]()\n for (v <- 0 until n) {\n if (!processed(v) && !all1Connections(v)) nextLevel = nextLevel :+ v \n }\n \n if (nextLevel.size > 0) {\n goBreadth(nextLevel.toSet)\n }\n }\n\n \tval res = (domains-1) + \"\"\n outLn(res)\n val durFull = System.currentTimeMillis() - start\n debug(s\"durFull=$durFull\")\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 = \"\"\"\n6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n\"\"\" //2\n\nval sa2 = \"\"\"\n3 0\n\"\"\" //0\n\n\nval sa3 = genBig\n\ndef genBig(): String = {\n val verts = 100000\n val edges = 100000\n var res = s\"\"\"\n$verts $edges\n\"\"\"\n val sr = new SecureRandom()\n val allEdges = (0 until edges).map{i => \n val a = sr.nextInt(verts-1) + 1\n val b = sr.nextInt(verts-1) + 1\n s\"$a $b\"\n }.mkString(\"\\n\")\n res += allEdges\n println(res.take(100))\n res\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\nimport java.security.SecureRandom\nimport scala.annotation.tailrec\n\n\nobject CF_599_D { var br = createBufferedReader(); var debugV = false\n\n //import scala.collection.mutable.{Map => MyMap}\n import scala.collection.mutable.{Set => MySet}\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 start = System.currentTimeMillis()\n val line = readLine\n \tval n = line.int //vertices\n \tval m = line.int //edge w1\n \n \tvar w1Edges = Array.fill(n)(MySet[Int]())\n \tfor(i <- 0 until m) {\n \t val vLine = readLine\n \t val a = vLine.int - 1\n val b = vLine.int - 1\n \t \n w1Edges(a) += b\n w1Edges(b) += a\n \t}\n \n val durRead = System.currentTimeMillis() - start\n debug(\"durRead=\"+durRead)\n \n var domains = 0\n w1Edges = w1Edges.sortBy(x => if(x!=null)x.size else 0)\n val processed = MySet[Int]()\n while (processed.size < n) {\n domains += 1\n val startV = (0 until n).find(i => !processed(i)).get\n goBreadth(Set(startV))\n }\n \n def goBreadth(verts: Set[Int]): Unit = {\n verts.foreach(v => processed += v)\n val unproc = (0 until n).filterNot(processed)\n val all1Connections = verts.flatMap(v=> w1Edges(v))\n val connectedToThisLevel = unproc.filterNot(all1Connections)\n if (connectedToThisLevel.size > 0) {\n goBreadth(connectedToThisLevel.toSet)\n }\n }\n\n \tval res = (domains-1) + \"\"\n outLn(res)\n val durFull = System.currentTimeMillis() - start\n debug(s\"durFull=$durFull\")\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 = \"\"\"\n6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n\"\"\" //2\n\nval sa2 = \"\"\"\n3 0\n\"\"\" //0\n\n\nval sa3 = genBig\n\ndef genBig(): String = {\n val verts = 100000\n val edges = 100000\n var res = s\"\"\"\n$verts $edges\n\"\"\"\n val sr = new SecureRandom()\n val allEdges = (0 until edges).map{i => \n val a = sr.nextInt(verts-1) + 1\n val b = sr.nextInt(verts-1) + 1\n s\"$a $b\"\n }.mkString(\"\\n\")\n res += allEdges\n println(res.take(100))\n res\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\nimport java.security.SecureRandom\nimport scala.annotation.tailrec\n\n\nobject CF_599_D { var br = createBufferedReader(); var debugV = false\n\n //import scala.collection.mutable.{Map => MyMap}\n import scala.collection.mutable.{Set => MySet}\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 start = System.currentTimeMillis()\n val line = readLine\n \tval n = line.int //vertices\n \tval m = line.int //edge w1\n \n \tvar w1Edges = Array.fill(n)(MySet[Int]())\n \tfor(i <- 0 until m) {\n \t val vLine = readLine\n \t val a = vLine.int - 1\n val b = vLine.int - 1\n \t \n w1Edges(a) += b\n w1Edges(b) += a\n \t}\n \n val durRead = System.currentTimeMillis() - start\n debug(\"durRead=\"+durRead)\n \n var domains = 0\n w1Edges = w1Edges.sortBy(x => if(x!=null)x.size else 0)\n val processed = MySet[Int]()\n while (processed.size < n) {\n domains += 1\n val startV = (0 until n).find(i => !processed(i)).get\n goBreadth(Set(startV))\n }\n \n def goBreadth(verts: Set[Int]): Unit = {\n// verts.foreach(v => processed += v)\n processed ++= verts\n// var all1ConnectionsVec = Vector[Int]()\n val all1Connections = MySet[Int]()\n// verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )\n verts.foreach(v => all1Connections ++= w1Edges(v) )\n// val all1Connections = all1ConnectionsVec.toSet\n// val all1Connections = verts.flatMap{v =>\n// w1Edges(v)}\n// val unproc = (0 until n).filter(v => !processed(v))\n// val connectedToThisLevel = unproc.filterNot(all1Connections)\n// val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))\n \n var nextLevel = Vector[Int]()\n for (v <- 0 until n) {\n if (!processed(v) && !all1Connections(v)) nextLevel = nextLevel :+ v \n }\n \n if (nextLevel.size > 0) {\n goBreadth(nextLevel.toSet)\n }\n }\n\n \tval res = (domains-1) + \"\"\n outLn(res)\n val durFull = System.currentTimeMillis() - start\n debug(s\"durFull=$durFull\")\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 = \"\"\"\n6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n\"\"\" //2\n\nval sa2 = \"\"\"\n3 0\n\"\"\" //0\n\n\nval sa3 = genBig\n\ndef genBig(): String = {\n val verts = 100000\n val edges = 100000\n var res = s\"\"\"\n$verts $edges\n\"\"\"\n val sr = new SecureRandom()\n val allEdges = (0 until edges).map{i => \n val a = sr.nextInt(verts-1) + 1\n val b = sr.nextInt(verts-1) + 1\n s\"$a $b\"\n }.mkString(\"\\n\")\n res += allEdges\n println(res.take(100))\n res\n}\n }\n}\n\n"}], "src_uid": "852e1d776c560a8720d4e9f1762b255f"} {"nl": {"description": "The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \\cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 200$$$)\u00a0\u2014 the number of test cases. Next $$$T$$$ lines contain descriptions of test cases\u00a0\u2014 one per line. Each line contains single even integer $$$n$$$ ($$$2 \\le n \\le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon.", "output_spec": "Print $$$T$$$ real numbers\u00a0\u2014 one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.", "sample_inputs": ["3\n2\n4\n200"], "sample_outputs": ["1.000000000\n2.414213562\n127.321336469"], "notes": null}, "positive_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 for (_ <- 1 to t) {\n val n = in.nextInt\n val p = n\n\n val r = 1.toDouble / (2 * math.sin(math.Pi / (2 * n)) / math.cos(math.Pi / (2 * n)))\n\n println(r * 2)\n }\n\n}\n"}], "negative_code": [], "src_uid": "0c7a476716445c535a61f4e81edc7f75"} {"nl": {"description": "You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like \"010101 ...\" or \"101010 ...\" (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of \"1011101\" are \"0\", \"1\", \"11111\", \"0111\", \"101\", \"1001\", but not \"000\", \"101010\" and \"11100\".You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' \u2014 the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \\le k \\le n$$$) \u2014 the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any.", "sample_inputs": ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"], "sample_outputs": ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: \"Send the fool further!\", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?Heidi's n friends are labeled 0 through n\u2009-\u20091, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n\u2009-\u20091 pairs of friends who know each other directly.Jenny is given the number 0.", "input_spec": "The first line of the input contains the number of friends n (3\u2009\u2264\u2009n\u2009\u2264\u2009100). The next n\u2009-\u20091 lines each contain three space-separated integers u, v and c (0\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n\u2009-\u20091, 1\u2009\u2264\u2009c\u2009\u2264\u2009104), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c. It is guaranteed that the social network of the input forms a tree.", "output_spec": "Output a single integer \u2013 the maximum sum of costs.", "sample_inputs": ["4\n0 1 4\n0 2 2\n2 3 3", "6\n1 2 3\n0 2 100\n1 4 2\n0 3 7\n3 5 10", "11\n1 0 1664\n2 0 881\n3 2 4670\n4 2 1555\n5 1 1870\n6 2 1265\n7 2 288\n8 7 2266\n9 2 1536\n10 6 3378"], "sample_outputs": ["5", "105", "5551"], "notes": "NoteIn the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 2)."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject J 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 linksBuilder = Array.fill(n)(mutable.ArrayBuilder.make[(Int, Int)])\n for (\n i <- 1 until n\n ) {\n read()\n val a = int()\n val b = int()\n val c = int()\n linksBuilder(a) += ((b, c))\n linksBuilder(b) += ((a, c))\n }\n val links = linksBuilder.map(_.result())\n\n def cost(cur: Int, prev: Int): Int = {\n val l = links(cur).filterNot(_._1 == prev)\n if (l.isEmpty) return 0\n l.map { case (next, c) =>\n c + cost(next, cur)\n }.max\n }\n\n println(cost(0, -1))\n}\n"}], "negative_code": [], "src_uid": "83ec573ad007d9385d6f0bb8f02b24e2"} {"nl": {"description": "There is an integer $$$n$$$ without zeros in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns.On her turn, Alice must swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left.You have to find the smallest integer Alice can get in the end, if she plays optimally.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$10 \\le n \\le 10^9$$$) \u2014 the integer for the game. $$$n$$$ does not have zeros in its decimal representation.", "output_spec": "For each test case output a single integer \u2014 the smallest integer Alice can get in the end of the game.", "sample_inputs": ["3\n\n12\n\n132\n\n487456398"], "sample_outputs": ["2\n1\n3"], "notes": "NoteIn the first test case Alice has to swap $$$1$$$ and $$$2$$$. After that Bob removes the last digit, $$$1$$$, so the answer is $$$2$$$.In the second test case Alice can swap $$$3$$$ and $$$1$$$: $$$312$$$. After that Bob deletes the last digit: $$$31$$$. Then Alice swaps $$$3$$$ and $$$1$$$: $$$13$$$ and Bob deletes $$$3$$$, so the answer is $$$1$$$."}, "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 {\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"}, {"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"} {"nl": {"description": "Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i\u2009+\u20091 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).", "input_spec": "The first line of input contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u20091\u2009000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1\u2009\u2264\u2009v,\u2009u\u2009\u2264\u20091018,\u2009v\u2009\u2260\u2009u,\u20091\u2009\u2264\u2009w\u2009\u2264\u2009109 states for every description line.", "output_spec": "For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.", "sample_inputs": ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"], "sample_outputs": ["94\n0\n32"], "notes": "NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32\u2009+\u200932\u2009+\u200930\u2009=\u200994. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). "}, "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.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"}, {"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"} {"nl": {"description": "This is the easy version of the problem. In this version, $$$n \\le 3000$$$, $$$x \\ge y$$$ holds. You can make hacks only if both versions of the problem are solved.You are given two binary strings $$$a$$$ and $$$b$$$, both of length $$$n$$$. You can do the following operation any number of times (possibly zero). Select two indices $$$l$$$ and $$$r$$$ ($$$l < r$$$). Change $$$a_l$$$ to $$$(1 - a_l)$$$, and $$$a_r$$$ to $$$(1 - a_r)$$$. If $$$l + 1 = r$$$, the cost of the operation is $$$x$$$. Otherwise, the cost is $$$y$$$. You have to find the minimum cost needed to make $$$a$$$ equal to $$$b$$$ or say there is no way to do so.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 600$$$)\u00a0\u2014 the number of test cases. Each test case consists of three lines. The first line of each test case contains three integers $$$n$$$, $$$x$$$, and $$$y$$$ ($$$5 \\le n \\le 3000$$$, $$$1 \\le y \\le x \\le 10^9$$$)\u00a0\u2014 the length of the strings, and the costs per operation. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. The third line of each test case contains the string $$$b$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3000$$$.", "output_spec": "For each test case, if there is no way to make $$$a$$$ equal to $$$b$$$, print $$$-1$$$. Otherwise, print the minimum cost needed to make $$$a$$$ equal to $$$b$$$.", "sample_inputs": ["4\n\n5 8 7\n\n01001\n\n00101\n\n5 7 2\n\n01000\n\n11011\n\n7 8 3\n\n0111001\n\n0100001\n\n5 10 1\n\n01100\n\n01100"], "sample_outputs": ["8\n-1\n6\n0"], "notes": "NoteIn the first test case, selecting indices $$$2$$$ and $$$3$$$ costs $$$8$$$, which is the minimum possible cost.In the second test case, we cannot make $$$a$$$ equal to $$$b$$$ using any number of operations.In the third test case, we can perform the following operations: Select indices $$$3$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0101011 now. Select indices $$$4$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0100001 now. The total cost is $$$6$$$.In the fourth test case, we don't have to perform any operations."}, "positive_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 input = readLine().split(\" \").map(_.toInt)\r\n val (n, x, y) = (input(0), input(1), input(2))\r\n val a = readLine().map(_ == '1')\r\n val b = readLine().map(_ == '1')\r\n val diffs = a.zip(b).zip(for(i <- 1 to n) yield i).filter{case ((ai, bi), i) => ai != bi}.map(_._2)\r\n if(diffs.length % 2 == 1)\r\n println(-1)\r\n else if(diffs.length == 2 && diffs(0) + 1 == diffs(1)) {\r\n if(y * 2 <= x)\r\n println(2*y)\r\n else\r\n println(x)\r\n } else println(y.toLong * diffs.length.toLong / 2)\r\n\r\n\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"}], "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 input = readLine().split(\" \").map(_.toInt)\r\n val (n, x, y) = (input(0), input(1), input(2))\r\n val a = readLine().map(_ == '1')\r\n val b = readLine().map(_ == '1')\r\n val diffs = a.zip(b).zip(for(i <- 1 to n) yield i).filter{case ((ai, bi), i) => ai != bi}.map(_._2)\r\n if(diffs.length % 2 == 1)\r\n println(-1)\r\n else if(diffs.length == 2 && diffs(0) + 1 == diffs(1)) {\r\n if(y * 2 <= x)\r\n println(2*y)\r\n else\r\n println(x)\r\n } else println(y * diffs.length / 2)\r\n\r\n\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": "f3c097872643f6fce645c05824b574e5"} {"nl": {"description": "Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price.The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below. The presented order book says that someone wants to sell the product at price $$$12$$$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $$$10$$$. There are two possible actions in this orderbook: Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer \"SELL $$$20$$$\" if there is already an offer \"BUY $$$20$$$\" or \"BUY $$$25$$$\"\u00a0\u2014 in this case you just accept the best BUY offer.You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: \"ADD $$$p$$$\" denotes adding a new order with price $$$p$$$ and unknown direction. The order must not contradict with orders still not removed from the order book. \"ACCEPT $$$p$$$\" denotes accepting an existing best offer with price $$$p$$$ and unknown direction.The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $$$10^9 + 7$$$. If it is impossible to correctly restore directions, then output $$$0$$$.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 363\\,304$$$) \u2014 the number of actions in the log. Each of the next $$$n$$$ lines contains a string \"ACCEPT\" or \"ADD\" and an integer $$$p$$$ ($$$1 \\le p \\le 308\\,983\\,066$$$), describing an action type and price. All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.", "output_spec": "Output the number of ways to restore directions of ADD actions modulo $$$10^9 + 7$$$.", "sample_inputs": ["6\nADD 1\nACCEPT 1\nADD 2\nACCEPT 2\nADD 3\nACCEPT 3", "4\nADD 1\nADD 2\nADD 3\nACCEPT 2", "7\nADD 1\nADD 2\nADD 3\nADD 4\nADD 5\nACCEPT 3\nACCEPT 5"], "sample_outputs": ["8", "2", "0"], "notes": "NoteIn the first example each of orders may be BUY or SELL.In the second example the order with price $$$1$$$ has to be BUY order, the order with the price $$$3$$$ has to be SELL order."}, "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\n var ans = 1L\n val book = new java.util.TreeSet[Int]()\n var sell, buy = -1\n\n REP(N) { _ =>\n val token = ns()\n val p = ni()\n token match {\n case \"ADD\" => book.add(p)\n case \"ACCEPT\" =>\n if (sell != -1 && sell < p || buy != -1 && p < buy) {\n out.println(0)\n return\n }\n\n // \u307e\u3060\u78ba\u5b9a\u3057\u3066\u306a\u3044\u30aa\u30fc\u30c0\u30fc\u306e\u5834\u5408\u3060\u3051*2\u3059\u308b\n if (p != sell && p != buy) ans = ans * 2 % MOD\n\n book.remove(p)\n\n val newSell = book.higher(p)\n sell = if (newSell > 0) newSell else -1\n val newBuy = book.lower(p)\n buy = if (newBuy > 0) newBuy else -1\n }\n }\n\n val it = book.iterator()\n var unknown = 0\n while(it.hasNext) {\n val p = it.next()\n if ((buy == -1 || buy < p) && (sell == -1 || p < sell)) unknown += 1\n }\n if (unknown > 0) ans = ans * (unknown + 1) % MOD\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 import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 sc = new InputReader(System.in)\n val N = sc.nextInt()\n val orders = new util.TreeSet[Int]()\n var ans = 1L\n\n var h, l: Option[Int] = None\n rep(N) { _ =>\n val command = sc.next()\n val p = sc.nextInt()\n command match {\n case \"ADD\" => orders.add(p)\n case \"ACCEPT\" =>\n if (h.exists(p > _) || l.exists(p < _)) {\n out.println(\"0\")\n return\n } else if (h.contains(p) || l.contains(p)){\n h = Option(orders.higher(p))\n l = Option(orders.lower(p))\n orders.remove(p)\n } else {\n h = Option(orders.higher(p))\n l = Option(orders.lower(p))\n ans = ans * 2 % MOD\n orders.remove(p)\n }\n }\n }\n\n val it = orders.iterator()\n while(it.hasNext) {\n val p = it.next()\n if (l.exists(p > _) && h.exists(p < _)) ans = ans * 2 % 2\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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\n var ans = 1L\n val book = new java.util.TreeSet[Int]()\n var sell, buy = -1\n\n REP(N) { _ =>\n val token = ns()\n val p = ni()\n token match {\n case \"ADD\" => book.add(p)\n case \"ACCEPT\" =>\n if (sell != -1 && sell <= p || buy != -1 && p <= buy) {\n out.println(0)\n return\n }\n\n // \u307e\u3060\u78ba\u5b9a\u3057\u3066\u306a\u3044\u30aa\u30fc\u30c0\u30fc\u306e\u5834\u5408\u3060\u3051*2\u3059\u308b\n if (p != sell && p != buy) ans = ans * 2 % MOD\n\n book.remove(p)\n\n val newSell = book.higher(p)\n sell = if (newSell > 0) newSell else -1\n val newBuy = book.lower(p)\n buy = if (newBuy > 0) newBuy else -1\n }\n }\n\n val it = book.iterator()\n var unknown = 0\n while(it.hasNext) {\n val p = it.next()\n if ((buy == -1 || buy < p) && (sell == -1 || p < sell)) unknown += 1\n }\n if (unknown > 0) ans = ans * (unknown + 1) % MOD\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": "223db02b85d93692699134a3b51914bf"} {"nl": {"description": "Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some \"forbidden\" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters \"ab\" is forbidden, then any occurrences of substrings \"ab\" and \"ba\" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any \"forbidden\" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is \"removed\" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string \"aba\", we get the string \"ba\", and if we cross out the second letter, we get \"aa\".", "input_spec": "The first line contains a non-empty string s, consisting of lowercase Latin letters \u2014 that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0\u2009\u2264\u2009k\u2009\u2264\u200913) \u2014 the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.", "output_spec": "Print the single number \u2014 the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.", "sample_inputs": ["ababa\n1\nab", "codeforces\n2\ndo\ncs"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "da2b3450a3ca05a60ea4de6bab9291e9"} {"nl": {"description": "Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1\u2009/\u2009x seconds for the first character and 1\u2009/\u2009y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.", "input_spec": "The first line contains three integers n,x,y (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009106) \u2014 the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the number of hits needed do destroy the i-th monster.", "output_spec": "Print n lines. In the i-th line print word \"Vanya\", if the last hit on the i-th monster was performed by Vanya, \"Vova\", if Vova performed the last hit, or \"Both\", if both boys performed it at the same time.", "sample_inputs": ["4 3 2\n1\n2\n3\n4", "2 1 1\n1\n2"], "sample_outputs": ["Vanya\nVova\nVanya\nBoth", "Both\nBoth"], "notes": "NoteIn the first sample Vanya makes the first hit at time 1\u2009/\u20093, Vova makes the second hit at time 1\u2009/\u20092, Vanya makes the third hit at time 2\u2009/\u20093, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1."}, "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, 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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n\u2009+\u20091 is a power of 2.In the picture you can see a complete binary tree with n\u2009=\u200915. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1\u2009\u2264\u2009ui\u2009\u2264\u2009n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui\u2009=\u20094 and si\u2009=\u2009\u00abUURL\u00bb, then the answer is 10.", "input_spec": "The first line contains two integer numbers n and q (1\u2009\u2264\u2009n\u2009\u2264\u20091018, q\u2009\u2265\u20091). n is such that n\u2009+\u20091 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1\u2009\u2264\u2009ui\u2009\u2264\u2009n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1\u2009\u2264\u2009i\u2009\u2264\u2009q) doesn't exceed 105.", "output_spec": "Print q numbers, i-th number must be the answer to the i-th query.", "sample_inputs": ["15 2\n4\nUURL\n8\nLRLLLLLLLL"], "sample_outputs": ["10\n5"], "notes": null}, "positive_code": [{"source_code": "import io.StdIn.readLine\n\nobject D extends App {\n val Array(n, q) = readLine().split(\"\\\\s+\").map(_.toLong)\n\n val root = State(Nil, (n + 1) / 2, (n + 1) / 4)\n\n case class State(path: List[State], k: Long, step: Long) {\n def command(c: Char) = c match {\n case 'L' \u21d2 if (step == 0L) this else State(this :: path, k - step, step / 2)\n case 'R' \u21d2 if (step == 0L) this else State(this :: path, k + step, step / 2)\n case 'U' \u21d2 path match {\n case prev :: rest \u21d2 prev\n case Nil \u21d2 this\n }\n }\n }\n\n def find(k: Long, node: State = root): State =\n if (node.k == k) node\n else if (node.k < k) find(k, node.command('R'))\n else find(k, node.command('L'))\n\n for (_ \u2190 1 to q.toInt) {\n val u = readLine().toLong\n val path = readLine()\n println(path.foldLeft(find(u)) {_ command _}.k)\n }\n}\n"}], "negative_code": [], "src_uid": "dc35bdf56bb0ac341895e543b001b801"} {"nl": {"description": "Permutation p is an ordered set of integers p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn.The decreasing coefficient of permutation p1,\u2009p2,\u2009...,\u2009pn is the number of such i (1\u2009\u2264\u2009i\u2009<\u2009n), that pi\u2009>\u2009pi\u2009+\u20091.You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.", "input_spec": "The single line contains two space-separated integers: n,\u2009k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009k\u2009<\u2009n) \u2014 the permutation length and the decreasing coefficient.", "output_spec": "In a single line print n space-separated integers: p1,\u2009p2,\u2009...,\u2009pn \u2014 the permutation of length n with decreasing coefficient k. If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.", "sample_inputs": ["5 2", "3 0", "3 2"], "sample_outputs": ["1 5 2 4 3", "1 2 3", "3 2 1"], "notes": null}, "positive_code": [{"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": "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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the \"sleep\" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1,\u2009r1],\u2009[l2,\u2009r2],\u2009...,\u2009[ln,\u2009rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1,\u2009rn].", "input_spec": "The first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20090\u2009\u2264\u2009P1,\u2009P2,\u2009P3\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009T1,\u2009T2\u2009\u2264\u200960). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li and ri (0\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u20091440, ri\u2009<\u2009li\u2009+\u20091 for i\u2009<\u2009n), which stand for the start and the end of the i-th period of work.", "output_spec": "Output the answer to the problem.", "sample_inputs": ["1 3 2 1 5 10\n0 10", "2 8 4 2 5 10\n20 30\n50 100"], "sample_outputs": ["30", "570"], "notes": null}, "positive_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 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"}, {"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"} {"nl": {"description": "There is a trampoline park with $$$n$$$ trampolines in a line. The $$$i$$$-th of which has strength $$$S_i$$$.Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice. If at the moment Pekora jumps on trampoline $$$i$$$, the trampoline will launch her to position $$$i + S_i$$$, and $$$S_i$$$ will become equal to $$$\\max(S_i-1,1)$$$. In other words, $$$S_i$$$ will decrease by $$$1$$$, except of the case $$$S_i=1$$$, when $$$S_i$$$ will remain equal to $$$1$$$. If there is no trampoline in position $$$i + S_i$$$, then this pass is over. Otherwise, Pekora will continue the pass by jumping from the trampoline at position $$$i + S_i$$$ by the same rule as above.Pekora can't stop jumping during the pass until she lands at the position larger than $$$n$$$ (in which there is no trampoline). Poor Pekora!Pekora is a naughty rabbit and wants to ruin the trampoline park by reducing all $$$S_i$$$ to $$$1$$$. What is the minimum number of passes she needs to reduce all $$$S_i$$$ to $$$1$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 5000$$$) \u2014 the number of trampolines. The second line of each test case contains $$$n$$$ integers $$$S_1, S_2, \\dots, S_n$$$ ($$$1 \\le S_i \\le 10^9$$$), where $$$S_i$$$ is the strength of the $$$i$$$-th trampoline. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$5000$$$.", "output_spec": "For each test case, output a single integer \u2014 the minimum number of passes Pekora needs to do to reduce all $$$S_i$$$ to $$$1$$$.", "sample_inputs": ["3\n7\n1 4 2 2 2 2 2\n2\n2 3\n5\n1 1 1 1 1"], "sample_outputs": ["4\n3\n0"], "notes": "NoteFor the first test case, here is an optimal series of passes Pekora can take. (The bolded numbers are the positions that Pekora jumps into during these passes.) $$$[1,4,\\textbf{2},2,\\textbf{2},2,\\textbf{2}]$$$ $$$[1,\\textbf{4},1,2,1,\\textbf{2},1]$$$ $$$[1,\\textbf{3},1,2,\\textbf{1},\\textbf{1},\\textbf{1}]$$$ $$$[1,\\textbf{2},1,\\textbf{2},1,\\textbf{1},\\textbf{1}]$$$ For the second test case, the optimal series of passes is show below. $$$[\\textbf{2},3]$$$ $$$[1,\\textbf{3}]$$$ $$$[1,\\textbf{2}]$$$ For the third test case, all $$$S_i$$$ are already equal to $$$1$$$."}, "positive_code": [{"source_code": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n val d = as(i) - n\n incomings(i) = Math.max(incomings(i) - d, 0)\n as(i) = n\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n && incomings(i) > 0) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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 C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n val d = n - as(i)\n incomings(i) = Math.max(incomings(i) - d, 0)\n as(i) = n\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n && incomings(i) > 0) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n val d = n - as(i)\n incomings(i) = Math.min(incomings(i) - d, 0)\n as(i) = n\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n && incomings(i) > 0) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n incomings(i) = Math.min(incomings(i), as(i) - n - 1)\n as(i) = n\n }\n// if (incomings(i) < as(i)) {\n// incomings(i) = as(i) - 1\n// }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n && incomings(i) > 0) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n incomings(i) = Math.min(incomings(i), as(i) - n)\n as(i) = n\n }\n// if (incomings(i) < as(i)) {\n// incomings(i) = as(i) - 1\n// }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n && incomings(i) > 0) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n incomings(i) = Math.min(incomings(i), as(i) - n)\n as(i) = n\n }\n if (incomings(i) < as(i)) {\n incomings(i) = as(i) - 1\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n) {\n as(i) = n\n }\n if (incomings(i) < as(i)) {\n incomings(i) = as(i) - 1\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n\n for (i <- as.indices) {\n res += Math.max(0, as(i) - incomings(i) - 1)\n if (as(i) > n - i) {\n as(i) = n - i\n }\n if (incomings(i) < as(i)) {\n incomings(i) = as(i) - 1\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C2 {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n\n for (test <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n val incomings = Array.fill(n){ 0 }\n var res = 0L\n if (as(0) > 1) {\n res += as(0) - 1\n incomings(0) = as(0) - 1\n }\n\n for (i <- as.indices) {\n if (as(i) > incomings(i)) {\n res += as(i) - incomings(i)\n }\n while (as(i) > 1) {\n val j = i + as(i)\n if (j < n) {\n incomings(j) += 1\n }\n incomings(i) -= 1\n as(i) -= 1\n }\n if (i + 1 < n) {\n incomings(i + 1) += incomings(i)\n }\n }\n\n ress(test) = res\n }\n\n out.println(ress.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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n for (i <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = 2*n // 2//2*Math.sqrt(i).toInt + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) = skipTo(skipTo(i))\n i = skipTo(i)\n }\n }\n }\n\n ress(i) = res\n }\n\n out.println(ress.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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n for (i <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = n + i // 2//2*Math.sqrt(i).toInt + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) = skipTo(skipTo(i))\n i = skipTo(i)\n }\n }\n }\n\n ress(i) = res\n }\n\n out.println(ress.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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n val t = nextInt\n val ress = Array.ofDim[Long](t)\n for (i <- 0 until t) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = n + i / 2//2*Math.sqrt(i).toInt + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) = skipTo(skipTo(i))\n i = skipTo(i)\n }\n }\n }\n\n ress(i) = res\n }\n\n out.println(ress.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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = n + 2*Math.sqrt(i).toInt + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) = skipTo(skipTo(i))\n i = skipTo(i)\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = n + Math.sqrt(i).toInt + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) = skipTo(skipTo(i))\n i = skipTo(i)\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = n + (32 - Integer.numberOfLeadingZeros(i + 1))\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) = skipTo(skipTo(i))\n i = skipTo(i)\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = 2 * n\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) += 1\n i = skipTo(i)\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n var numOnes = 0\n val skipTo = Array.ofDim[Int](n)\n for (i <- as.indices) {\n skipTo(i) = i + 1\n val nn = n + i\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n if (as(i) == 1) numOnes += 1\n }\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n if (as(i) > 1) {\n val nextI = i + as(i)\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n i = nextI\n } else {\n while (skipTo(i) < n && as(skipTo(i)) == 1) skipTo(i) += 1\n i = skipTo(i)\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n for (i <- as.indices) {\n val nn = n + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n var numOnes = as.count(_ == 1)\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) {\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n }\n i = nextI\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n// val as = nextInts(n)\n val as = Array.fill(n)(1000000000)\n var res = 0L\n for (i <- as.indices) {\n val nn = n + 10\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n var numOnes = as.count(_ == 1)\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start) == 1 && as(start + 1) == 1) start += 1\n var i = start\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) {\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n }\n i = nextI\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n// val as = Array.fill(n)(1000000000)\n var res = 0L\n for (i <- as.indices) {\n val nn = n + i\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n var numOnes = as.count(_ == 1)\n var start = 0\n var changed = true\n res -= 1\n while (changed) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (start + 1 < n && as(start + 1) == 1) start += 1\n var i = start\n changed = false\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) {\n as(i) -= 1\n// if (as(i) == 1) numOnes += 1\n changed = true\n }\n i = nextI\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n var res = 0L\n for (i <- as.indices) {\n val nn = n//2 * n + i\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n var numOnes = as.count(_ == 1)\n var start = 0\n while (numOnes < n) {\n // println(res, as.mkString(\" \"))\n res += 1\n while (as(start) == 1) start += 1\n var i = 0\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) {\n as(i) -= 1\n if (as(i) == 1) numOnes += 1\n }\n i = nextI\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"}, {"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n var res = 0L\n for (i <- as.indices) {\n val nn = (n - i) * 2 + n\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n while (as.max > 1) {\n// println(res, as.mkString(\" \"))\n res += 1\n var i = 0\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) as(i) -= 1\n i = nextI\n }\n }\n res += (as.max - 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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n var res = 0L\n for (i <- as.indices) {\n val nn = (n - i) * 2 + 1\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n while (as.max > 1) {\n// println(res, as.mkString(\" \"))\n res += 1\n var i = 0\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) as(i) -= 1\n i = nextI\n }\n }\n res += (as.max - 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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n var res = 0\n val nn = n * n\n for (i <- as.indices) {\n if (as(i) > nn) {\n res += as(i) - nn\n as(i) = nn\n }\n }\n while (as.max > 1) {\n// println(res, as.mkString(\" \"))\n res += 1\n var i = 0\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) as(i) -= 1\n i = nextI\n }\n }\n res += (as.max - 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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n var res = 0\n for (i <- as.indices) {\n if (as(i) > n) {\n res += as(i) - n\n as(i) = n\n }\n }\n while (as.max > 1) {\n// println(res, as.mkString(\" \"))\n res += 1\n var i = 0\n while (i < n) {\n val nextI = i + as(i)\n if (as(i) > 1) as(i) -= 1\n i = nextI\n }\n }\n res += (as.max - 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": "ac12faea4962613651afdc0b29537ef5"} {"nl": {"description": "While walking down the street Vanya saw a label \"Hide&Seek\". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109\u2009+\u20097.To represent the string as a number in numeral system with base 64 Vanya uses the following rules: digits from '0' to '9' correspond to integers from 0 to 9; letters from 'A' to 'Z' correspond to integers from 10 to 35; letters from 'a' to 'z' correspond to integers from 36 to 61; letter '-' correspond to integer 62; letter '_' correspond to integer 63. ", "input_spec": "The only line of the input contains a single word s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009100\u2009000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.", "output_spec": "Print a single integer\u00a0\u2014 the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109\u2009+\u20097.", "sample_inputs": ["z", "V_V", "Codeforces"], "sample_outputs": ["3", "9", "130653412"], "notes": "NoteFor a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.In the first sample, there are 3 possible solutions: z&_\u2009=\u200961&63\u2009=\u200961\u2009=\u2009z _&z\u2009=\u200963&61\u2009=\u200961\u2009=\u2009z z&z\u2009=\u200961&61\u2009=\u200961\u2009=\u2009z "}, "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"}, {"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"}], "negative_code": [], "src_uid": "1b336555c94d5d5198abe5426ff6fa7a"} {"nl": {"description": "An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i\u2009+\u20091) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.", "input_spec": "A single line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of students at an exam.", "output_spec": "In the first line print integer k \u2014 the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other. In the second line print k distinct integers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009n), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |ai\u2009-\u2009ai\u2009+\u20091|\u2009\u2260\u20091 for all i from 1 to k\u2009-\u20091. If there are several possible answers, output any of them.", "sample_inputs": ["6", "3"], "sample_outputs": ["6\n1 5 3 6 2 4", "2\n1 3"], "notes": null}, "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 \u2190 (n + 1) / 2 to 1 by -1) print(s\"${i + i - 1} \")\n for (i \u2190 n / 2 to 1 by -1) print(s\"${i + i} \")\n }\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 | 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": "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 \u2190 1 to n) {\n for (j \u2190 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 \u2190 1 to n) {\n var done = false\n for (j \u2190 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"} {"nl": {"description": "Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 1\\,000$$$)\u00a0\u2014 the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \\le a_i < b_i \\le n$$$)\u00a0\u2014 the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.", "output_spec": "If there is no such tree that can produce the given list of pairs, print \"NO\" (without quotes). Otherwise print \"YES\" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$)\u00a0\u2014 vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.", "sample_inputs": ["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"], "sample_outputs": ["YES\n1 3\n3 2\n2 4", "NO", "NO"], "notes": "NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs. "}, "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 try {\n solve2()\n } catch {\n case _: IllegalArgumentException => out.println(\"NO\")\n }\n }\n\n def solve2(): Unit = {\n val N = ni()\n val E = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n val u, v = ni()\n if (max(u, v) != N || u == v) {\n throw new IllegalArgumentException\n }\n E(i) = min(u, v)\n }\n\n if (!E.contains(N - 1)) throw new IllegalArgumentException\n\n val used = Array.ofDim[Boolean](N + 1)\n used(N) = true\n val paths = ArrayBuffer[Path]()\n val availablePaths = ArrayBuffer[Path]()\n\n def use(v: Int): Unit = {\n if (availablePaths.isEmpty) throw new IllegalArgumentException\n\n used(v) = true\n val path = availablePaths.head\n path.use(v)\n if (!path.available) availablePaths -= path\n }\n\n var prev = -1\n val cnts = E.groupBy(identity).mapValues(_.length).toSeq.sortBy(_._1).reverse\n cnts foreach { case (v, cnt) =>\n if (prev != -1) {\n v + 1 until prev foreach { u =>\n use(u)\n }\n }\n val path = Path(v, cnt + 1)\n paths += path\n if (path.available) availablePaths += path\n used(v) = true\n prev = v\n }\n\n case class Path(v: Int, size: Int) {\n val nodes = Array.ofDim[Int](size)\n nodes(0) = N\n nodes(size - 1) = v\n var last = 1\n\n def available: Boolean = {\n last < size - 1\n }\n\n def use(u: Int): Unit = {\n nodes(last) = u\n last += 1\n }\n }\n\n rep(N, 1) { i =>\n if (!used(i)) use(i)\n }\n\n out.println(\"YES\")\n paths foreach { path =>\n rep(path.size - 1) { i =>\n out.println(s\"${path.nodes(i + 1)} ${path.nodes(i)}\")\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): 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 try {\n val s = new Main()\n s.solve()\n s.out.flush()\n } catch {\n case _ => println(\"NO\")\n }\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 E = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n val u, v = ni()\n if (max(u, v) != N || u == v) {\n throw new IllegalArgumentException\n }\n E(i) = min(u, v)\n }\n\n if (!E.exists(_ == N - 1)) throw new IllegalArgumentException\n\n val used = Array.ofDim[Boolean](N + 1)\n used(N) = true\n val paths = ArrayBuffer[Path]()\n val availablePaths = ArrayBuffer[Path]()\n\n def use(v: Int): Unit = {\n if (availablePaths.isEmpty) throw new IllegalArgumentException\n\n used(v) = true\n val path = availablePaths.head\n path.use(v)\n if (!path.available) availablePaths -= path\n }\n\n var prev = -1\n val cnts = E.groupBy(identity).mapValues(_.length).toSeq.sortBy(_._1).reverse\n cnts foreach { case (v, cnt) =>\n if (prev != -1 && prev - 1 != v) {\n prev - 1 until v foreach { u =>\n use(u)\n }\n }\n val path = Path(v, cnt + 1)\n paths += path\n availablePaths += path\n used(v) = true\n prev = v\n }\n\n case class Path(v: Int, size: Int) {\n val nodes = Array.ofDim[Int](size)\n nodes(0) = N\n nodes(size - 1) = v\n var last = 1\n\n def available: Boolean = {\n last < size - 1\n }\n\n def use(u: Int): Unit = {\n nodes(last) = u\n last += 1\n }\n }\n\n rep(N, 1) { i =>\n if (!used(i)) use(i)\n }\n\n out.println(\"YES\")\n paths foreach { path =>\n rep(path.size - 1) { i =>\n out.println(s\"${path.nodes(i + 1)} ${path.nodes(i)}\")\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): 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": "531746ba8d93a76d5bdf4bab67d9ba19"} {"nl": {"description": "Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends \u2014 the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of Andrey's friends. The second line contains n real numbers pi (0.0\u2009\u2264\u2009pi\u2009\u2264\u20091.0) \u2014 the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.", "output_spec": "Print a single real number \u2014 the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10\u2009-\u20099.", "sample_inputs": ["4\n0.1 0.2 0.3 0.8", "2\n0.1 0.2"], "sample_outputs": ["0.800000000000", "0.260000000000"], "notes": "NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1\u00b70.8\u2009+\u20090.9\u00b70.2\u2009=\u20090.26."}, "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.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"}, {"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"} {"nl": {"description": "Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.", "input_spec": "The first line of the input contains five space-separated integers m1, m2, m3, m4, m5, where mi (0\u2009\u2264\u2009mi\u2009\u2264\u2009119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted. The second line contains five space-separated integers w1, w2, w3, w4, w5, where wi (0\u2009\u2264\u2009wi\u2009\u2264\u200910) is Kevin's number of wrong submissions on problem i. The last line contains two space-separated integers hs and hu (0\u2009\u2264\u2009hs,\u2009hu\u2009\u2264\u200920), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.", "output_spec": "Print a single integer, the value of Kevin's final score.", "sample_inputs": ["20 40 60 80 100\n0 1 2 3 4\n1 0", "119 119 119 119 119\n0 0 0 0 0\n10 0"], "sample_outputs": ["4900", "4930"], "notes": "NoteIn the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets of the points on each problem. So his score from solving problems is . Adding in 10\u00b7100\u2009=\u20091000 points from hacks, his total score becomes 3930\u2009+\u20091000\u2009=\u20094930."}, "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 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"}, {"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"} {"nl": {"description": "The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u2009100). Then follow n lines describing instructions. The i-th line contains m integers: xi1,\u2009xi2,\u2009...,\u2009xim (0\u2009\u2264\u2009xij\u2009\u2264\u2009k), where xij is the instruction that must be executed by the i-th core at the j-th cycle. If xij equals 0, then the corresponding instruction is \u00abdo nothing\u00bb. But if xij is a number from 1 to k, then the corresponding instruction is \u00abwrite information to the memory cell number xij\u00bb. We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.", "output_spec": "Print n lines. In the i-th line print integer ti. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.", "sample_inputs": ["4 3 5\n1 0 0\n1 0 2\n2 3 1\n3 2 0", "3 2 2\n1 2\n1 2\n2 2", "1 1 1\n0"], "sample_outputs": ["1\n1\n3\n0", "1\n1\n0", "0"], "notes": null}, "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\nobject B {\n def solve() {\n val nmk = (1 to 3).map(_ => sc.nextInt)\n val (n, m, k) = (nmk(0), nmk(1), nmk(2))\n\n var arr = Array.newBuilder[Array[Int]]\n val b = Array.newBuilder[Int]\n for ( i <- 0 until n; j <- 0 until m ) {\n b += sc.nextInt\n if (j == m - 1) {\n arr += b.result()\n b.clear()\n }\n }\n\n val a = arr.result()\n val res = Array.fill(n)(0)\n val na = Array.fill(k + 1)(false)\n for ( i <- 0 until m ) {\n a.map(_(i))\n .zipWithIndex\n .filter(p => res(p._2) == 0)\n .groupBy(_._1)\n .foreach {\n case (c, d) =>\n if (d.size >= 2 && c != 0)\n d.foreach(p => if (res(p._2) == 0) { res(p._2) = i + 1; na(c) = true; })\n else if (na(c)) d.foreach(p => if (res(p._2) == 0) res(p._2) = i + 1)\n }\n }\n\n res.foreach(pw.println)\n }\n\n def main(args: Array[String]) {\n run()\n }\n\n var sc: Scanner = null\n var pw: PrintWriter = null\n\n\n def run() {\n try {\n sc = new Scanner(System.in)\n pw = new PrintWriter(System.out)\n solve()\n pw.close()\n sc.close()\n } catch {\n case e =>\n e.printStackTrace()\n System.exit(666)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "6422a70e686c34b4b9b6b5797712998e"} {"nl": {"description": "At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \\dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way: form a list of distances $$$d_1, d_2, \\dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$); sort list $$$d$$$ in non-descending order; take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.", "input_spec": "The first line contains single integer $$$T$$$ ($$$ 1 \\le T \\le 2 \\cdot 10^5$$$) \u2014 number of queries. Next $$$2 \\cdot T$$$ lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k < n$$$) \u2014 the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_1 < a_2 < \\dots < a_n \\le 10^9$$$) \u2014 points in ascending order. It's guaranteed that $$$\\sum{n}$$$ doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.", "sample_inputs": ["3\n3 2\n1 2 5\n2 1\n1 1000000000\n1 0\n4"], "sample_outputs": ["3\n500000000\n4"], "notes": null}, "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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "negative_code": [], "src_uid": "87e39e14d6e33427148c284b16a7fb13"} {"nl": {"description": "You play a computer game. In this game, you lead a party of $$$m$$$ heroes, and you have to clear a dungeon with $$$n$$$ monsters. Each monster is characterized by its power $$$a_i$$$. Each hero is characterized by his power $$$p_i$$$ and endurance $$$s_i$$$.The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $$$k$$$ monsters, the hero fights with the monster $$$k + 1$$$). When the hero fights the monster, there are two possible outcomes: if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends; otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $$$i$$$-th hero cannot defeat more than $$$s_i$$$ monsters during each day), or if all monsters are defeated \u2014 otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u2014 the number of test cases. Then the test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of monsters in the dungeon. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the power of the $$$i$$$-th monster. The third line contains one integer $$$m$$$ ($$$1 \\le m \\le 2 \\cdot 10^5$$$) \u2014 the number of heroes in your party. Then $$$m$$$ lines follow, each describing a hero. Each line contains two integers $$$p_i$$$ and $$$s_i$$$ ($$$1 \\le p_i \\le 10^9$$$, $$$1 \\le s_i \\le n$$$) \u2014 the power and the endurance of the $$$i$$$-th hero. It is guaranteed that the sum of $$$n + m$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print one integer \u2014 the minimum number of days you have to spend to defeat all of the monsters (or $$$-1$$$ if it is impossible).", "sample_inputs": ["2\n6\n2 3 11 14 1 8\n2\n3 2\n100 1\n5\n3 5 100 2 3\n2\n30 5\n90 1"], "sample_outputs": ["5\n-1"], "notes": null}, "positive_code": [{"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u306e\u6607\u9806\u306fpower\u306e\u964d\u9806\u306b\u306a\u308b\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"} {"nl": {"description": "Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $$$1$$$. For example, park with $$$n=m=2$$$ has $$$12$$$ streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park). The park sizes are: $$$n=4$$$, $$$m=5$$$. The lighted squares are marked yellow. Please note that all streets have length $$$1$$$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$n$$$, $$$m$$$ ($$$1 \\le n, m \\le 10^4$$$) \u2014 park sizes.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer must be a single integer \u2014 the minimum number of lanterns that are required to light all the squares.", "sample_inputs": ["5\n1 1\n1 3\n2 2\n3 3\n5 3"], "sample_outputs": ["1\n2\n2\n5\n8"], "notes": "NotePossible optimal arrangement of the lanterns for the $$$2$$$-nd test case of input data example: Possible optimal arrangement of the lanterns for the $$$3$$$-rd test case of input data example: "}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "19df5f3b8b31b763162c5331c1499529"} {"nl": {"description": "The Metropolis computer network consists of $$$n$$$ servers, each has an encryption key in the range from $$$0$$$ to $$$2^k - 1$$$ assigned to it. Let $$$c_i$$$ be the encryption key assigned to the $$$i$$$-th server. Additionally, $$$m$$$ pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have distinct encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe.You have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number $$$x$$$ in the same aforementioned range, and when server $$$i$$$ is infected, its encryption key changes from $$$c_i$$$ to $$$c_i \\oplus x$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation.Sadly, you know neither the number $$$x$$$ nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs $$$(A, x)$$$, where $$$A$$$ is some (possibly empty) subset of the set of servers and $$$x$$$ is some number in the range from $$$0$$$ to $$$2^k - 1$$$, such that when all servers from the chosen subset $$$A$$$ and none of the others are infected by a virus containing the number $$$x$$$, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo $$$10^9 + 7$$$.", "input_spec": "The first line of input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\leq n \\leq 500\\,000$$$, $$$0 \\leq m \\leq \\min(\\frac{n(n - 1)}{2}, 500\\,000)$$$, $$$0 \\leq k \\leq 60$$$)\u00a0\u2014 the number of servers, the number of pairs of servers directly connected by a data communication channel, and the parameter $$$k$$$, which defines the range of possible values for encryption keys. The next line contains $$$n$$$ integers $$$c_i$$$ ($$$0 \\leq c_i \\leq 2^k - 1$$$), the $$$i$$$-th of which is the encryption key used by the $$$i$$$-th server. The next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ each ($$$1 \\leq u_i, v_i \\leq n$$$, $$$u_i \\ne v_i$$$) denoting that those servers are connected by a data communication channel. It is guaranteed that each pair of servers appears in this list at most once.", "output_spec": "The only output line should contain a single integer\u00a0\u2014 the number of safe infections of some subset of servers by a virus with some parameter, modulo $$$10^9 + 7$$$.", "sample_inputs": ["4 4 2\n0 1 0 1\n1 2\n2 3\n3 4\n4 1", "4 5 3\n7 1 7 2\n1 2\n2 3\n3 4\n4 1\n2 4"], "sample_outputs": ["50", "96"], "notes": "NoteConsider the first example.Possible values for the number $$$x$$$ contained by the virus are $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$.For values $$$0$$$, $$$2$$$ and $$$3$$$ the virus can infect any subset of the set of servers, which gives us $$$16$$$ pairs for each values. A virus containing the number $$$1$$$ can infect either all of the servers, or none. This gives us $$$16 + 2 + 16 + 16 = 50$$$ pairs in total."}, "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 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\u306b\u542b\u307e\u308c\u306a\u3044\u30ce\u30fc\u30c9\u306f\u3059\u3079\u3066\u5358\u72ec\u3067\u9023\u7d50\u6210\u5206\u306b\u306a\u308b\u306e\u3067 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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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\u306b\u542b\u307e\u308c\u306a\u3044\u30ce\u30fc\u30c9\u306f\u3059\u3079\u3066\u5358\u72ec\u3067\u9023\u7d50\u6210\u5206\u306b\u306a\u308b\u306e\u3067 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"} {"nl": {"description": "Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one \u2014 by value vi\u2009-\u20091, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20094000) \u2014 the number of kids in the line. Next n lines contain three integers each vi,\u2009di,\u2009pi (1\u2009\u2264\u2009vi,\u2009di,\u2009pi\u2009\u2264\u2009106) \u2014 the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.", "output_spec": "In the first line print number k \u2014 the number of children whose teeth Gennady will cure. In the second line print k integers \u2014 the numbers of the children who will make it to the end of the line in the increasing order.", "sample_inputs": ["5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2", "5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9"], "sample_outputs": ["2\n1 3", "4\n1 2 4 5"], "notes": "NoteIn the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to \u2009-\u20092,\u20091,\u20093,\u20091, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0,\u20092,\u20090. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,\u2009\u2009-\u20091,\u20096,\u20098. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5,\u20095,\u20097. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0,\u20093. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last."}, "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{_ =>\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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009N2. S[i]\u2009=\u2009S[j], that is the i-th symbol of string S is equal to the j-th.", "input_spec": "The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.", "output_spec": "Print a single number which represents the number of pairs i and j with the needed property. Pairs (x,\u2009y) and (y,\u2009x) should be considered different, i.e. the ordered pairs count.", "sample_inputs": ["great10", "aaaaaaaaaa"], "sample_outputs": ["7", "100"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nobject CFB47b {\n\n\tdef main(args: Array[String]): Unit = {\n\t\t\tdoIt();\n\t}\n\tdef doIt(){\n\t\tval sc = new Scanner(System.in);\n\t\tvar ary = new Array[Long](36);\n\t\tval input = sc.next();\n\t\tfor(c <- input){\n\t\t\tif('a' <= c && c <= 'z') ary(c - 'a') += 1;\n\t\t\telse ary(c - '0' + 26) += 1;\n\t\t}\n\t\tprintln(ary.map(x => x*x).foldRight(0L)((x:Long, y:Long) => x + y));\n\t}\n}"}], "negative_code": [], "src_uid": "6bb2793e275426eb076972fab69d0eba"} {"nl": {"description": "Vlad went into his appartment house entrance, now he is on the $$$1$$$-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that: the first elevator is currently on the floor $$$a$$$ (it is currently motionless), the second elevator is located on floor $$$b$$$ and goes to floor $$$c$$$ ($$$b \\ne c$$$). Please note, if $$$b=1$$$, then the elevator is already leaving the floor $$$1$$$ and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor $$$1$$$. If you call the second one, then first it will reach the floor $$$c$$$ and only then it will go to the floor $$$1$$$. It takes $$$|x - y|$$$ seconds for each elevator to move from floor $$$x$$$ to floor $$$y$$$.Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.", "input_spec": "The first line of the input contains the only $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. This is followed by $$$t$$$ lines, three integers each $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\le a, b, c \\le 10^8$$$, $$$b \\ne c$$$)\u00a0\u2014 floor numbers described in the statement.", "output_spec": "Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. As an answer, output: $$$1$$$, if it is better to call the first elevator; $$$2$$$, if it is better to call the second one; $$$3$$$, if it doesn't matter which elevator to call (both elevators will arrive in the same time). ", "sample_inputs": ["3\n\n1 2 3\n\n3 1 2\n\n3 2 1"], "sample_outputs": ["1\n3\n2"], "notes": "NoteIn the first test case of the example, the first elevator is already on the floor of $$$1$$$.In the second test case of the example, when called, the elevators would move as follows: At the time of the call, the first elevator is on the floor of $$$3$$$, and the second one is on the floor of $$$1$$$, but is already going to another floor; in $$$1$$$ second after the call, the first elevator would be on the floor $$$2$$$, the second one would also reach the floor $$$2$$$ and now can go to the floor $$$1$$$; in $$$2$$$ seconds, any elevator would reach the floor $$$1$$$. In the third test case of the example, the first elevator will arrive in $$$2$$$ seconds, and the second in $$$1$$$."}, "positive_code": [{"source_code": "object _1729A extends CodeForcesApp {\n override def solve() = repeat() {\n val a, b, c = nextInt()\n val ans = (a-1).abs.compareTo((b-c).abs + (c-1).abs) match {\n case 1 => 2\n case -1 => 1\n case _ => 3\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 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\n def main(args: Array[String]): Unit = try solve() finally out.flush()\n def solve(): Any\n}\n"}], "negative_code": [], "src_uid": "aca2346553f9e7b6e944ca2c74bb0b3d"} {"nl": {"description": "Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character \"/\". Every other directory has a name \u2014 a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory \u2014 the one that contains the given directory. It is denoted as \"..\".The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be \"..\", which means a step up to the parent directory. \u00ab..\u00bb can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or \"..\"), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.The command pwd should display the absolute path to the current directory. This path must not contain \"..\".Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.", "input_spec": "The first line of the input data contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of commands. Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter. The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive. Directories in the file system can have the same names.", "output_spec": "For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.", "sample_inputs": ["7\npwd\ncd /home/vasya\npwd\ncd ..\npwd\ncd vasya/../petya\npwd", "4\ncd /a/b\npwd\ncd ../a/b\npwd"], "sample_outputs": ["/\n/home/vasya/\n/home/\n/home/petya/", "/a/b/\n/a/a/b/"], "notes": null}, "positive_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\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": "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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $$$1$$$ to $$$n$$$.$$$s[l; r]$$$ is a continuous substring of letters from index $$$l$$$ to $$$r$$$ of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings \"baba\" and \"aabbab\" are balanced and strings \"aaab\" and \"b\" are not.Find any non-empty balanced substring $$$s[l; r]$$$ of string $$$s$$$. Print its $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le n$$$). If there is no such substring, then print $$$-1$$$ $$$-1$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the length of the string. The second line of the testcase contains a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'.", "output_spec": "For each testcase print two integers. If there exists a non-empty balanced substring $$$s[l; r]$$$, then print $$$l$$$ $$$r$$$ ($$$1 \\le l \\le r \\le n$$$). Otherwise, print $$$-1$$$ $$$-1$$$.", "sample_inputs": ["4\n1\na\n6\nabbaba\n6\nabbaba\n9\nbabbabbaa"], "sample_outputs": ["-1 -1\n1 6\n3 6\n2 5"], "notes": "NoteIn the first testcase there are no non-empty balanced subtrings.In the second and third testcases there are multiple balanced substrings, including the entire string \"abbaba\" and substring \"baba\"."}, "positive_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}"}, {"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"} {"nl": {"description": "Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.", "input_spec": "The first line contains an integer n, which is the number of contestants in the room (1\u2009\u2264\u2009n\u2009\u2264\u200950). The next n lines contain the participants of a given room. The i-th line has the format of \"handlei plusi minusi ai bi ci di ei\" \u2014 it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0\u2009\u2264\u2009plusi,\u2009minusi\u2009\u2264\u200950; 150\u2009\u2264\u2009ai\u2009\u2264\u2009500 or ai\u2009=\u20090, if problem A is not solved; 300\u2009\u2264\u2009bi\u2009\u2264\u20091000 or bi\u2009=\u20090, if problem B is not solved; 450\u2009\u2264\u2009ci\u2009\u2264\u20091500 or ci\u2009=\u20090, if problem C is not solved; 600\u2009\u2264\u2009di\u2009\u2264\u20092000 or di\u2009=\u20090, if problem D is not solved; 750\u2009\u2264\u2009ei\u2009\u2264\u20092500 or ei\u2009=\u20090, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).", "output_spec": "Print on the single line the handle of the room leader.", "sample_inputs": ["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"], "sample_outputs": ["tourist"], "notes": "NoteThe number of points that each participant from the example earns, are as follows: Petr \u2014 3860 tourist \u2014 4140 Egor \u2014 4030 c00lH4x0R \u2014 \u2009-\u2009350 some_participant \u2014 2220 Thus, the leader of the room is tourist."}, "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"}, {"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}"}], "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"} {"nl": {"description": "The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids: after the $$$1$$$-st day it will belong to the $$$5$$$-th kid, after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid, after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid, after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 200$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 200$$$) \u2014 the number of kids in the query. The second line of the query contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$, all $$$p_i$$$ are distinct, i.e. $$$p$$$ is a permutation), where $$$p_i$$$ is the kid which will get the book of the $$$i$$$-th kid.", "output_spec": "For each query, print the answer on it: $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i$$$ is the number of the day the book of the $$$i$$$-th child is returned back to him for the first time in this query.", "sample_inputs": ["6\n5\n1 2 3 4 5\n3\n2 3 1\n6\n4 6 2 1 5 3\n1\n1\n4\n3 4 1 2\n5\n5 1 2 4 3"], "sample_outputs": ["1 1 1 1 1 \n3 3 3 \n2 3 3 2 1 3 \n1 \n2 2 2 2 \n4 4 4 1 4"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $$$121, 66, 98989$$$ are palindromes, and $$$103, 239, 1241$$$ are not palindromes.Alina understands that a valid number always exist. Help her find one!", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u2014 the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100\\,000$$$) \u2014 the length of the number that is written on the ground. The second line of contains the positive $$$n$$$-digit integer without leading zeroes \u2014 the number itself. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100\\,000$$$.", "output_spec": "For each of $$$t$$$ test cases print an answer \u2014 a positive $$$n$$$-digit integer without leading zeros, such that the sum of the input integer and this number is a palindrome. We can show that at least one number satisfying the constraints exists. If there are multiple solutions, you can output any of them.", "sample_inputs": ["3\n2\n99\n4\n1023\n3\n385"], "sample_outputs": ["32\n8646\n604"], "notes": "NoteIn the first test case $$$99 + 32 = 131$$$ is a palindrome. Note that another answer is $$$12$$$, because $$$99 + 12 = 111$$$ is also a palindrome.In the second test case $$$1023 + 8646 = 9669$$$.In the third test case $$$385 + 604 = 989$$$."}, "positive_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n def suma(s:String,t:String): String = {\r\n val r = new StringBuilder\r\n var j = 0\r\n for (i <- Range(0,s.length).reverse){\r\n r ++= ((s(i).toString.toInt + t(i).toString.toInt + j ) % 10).toString\r\n j = (s(i).toString.toInt + t(i).toString.toInt + j ) / 10\r\n }\r\n r.toString.reverse\r\n }\r\n val n = readInt()\r\n for (i <- 1 to n){\r\n val x = readInt()\r\n val y = readLine()\r\n val t = for (l <- y) yield {\r\n (9-l.toString.toInt).toString.apply(0)}\r\n val li = \"1\"*(x-1) + \"2\"\r\n val q = 1\r\n if (t(0) == \"0\"(0)) {\r\n println(suma(t,li))\r\n }\r\n else println(t)\r\n\r\n }\r\n\r\n\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n for (i <- 1 to n){\r\n val x =\r\n readInt()\r\n val y = readLine()\r\n val t = for (l <- y) yield {\r\n (9-l.toString.toInt).toString.apply(0)}\r\n var j = 0\r\n val li = \"1\"*x + \"2\"\r\n val mi = li.reverse\r\n if (t(0) == \"0\"(0)) {\r\n val s = for (l <- 0 until t.length) yield {\r\n j = (t.reverse.apply(l).toString.toInt + mi.apply(l).toString.toInt + j )/ 10\r\n val s1 = (t.reverse.apply(l).toString.toInt + mi.apply(l).toString.toInt + j % 10).toString.apply(0)\r\n s1\r\n }\r\n var s2 = \"\"\r\n for (l <- s) {\r\n s2 += l.toString\r\n }\r\n println(s2.reverse)\r\n }\r\n else println(t)\r\n\r\n }\r\n\r\n\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n for (i <- 1 to n){\r\n val x = readInt()\r\n val y = readLine()\r\n val t = for (l <- y) yield {\r\n (9-l.toString.toInt).toString.apply(0)}\r\n println(if (t(0) != \"0\"(0)) t else 12)\r\n }\r\n\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n for (i <- 1 to n){\r\n val x = readInt()\r\n val y = readLine()\r\n val t = for (l <- y) yield {\r\n (9-l.toString.toInt).toString.apply(0)}\r\n println(if (t(0) != 0) t else 12)\r\n }\r\n\r\n}\r\n\r\n"}, {"source_code": "object prob1 extends App {\r\n\r\n import scala.io.StdIn\r\n import scala.math.max\r\n import scala.List\r\n\r\n val n = readInt()\r\n\r\n for (i <- 1 to n){\r\n val x = readInt()\r\n val y = readLong()\r\n val z = (math.pow(10,x) - 1).toLong\r\n println(z)\r\n val t = (z - y)\r\n val a = if (t.toString.length == x) t\r\n else (math.pow(10,x-1) + t + 12).toLong\r\n println(a)\r\n }\r\n}\r\n\r\n"}], "src_uid": "d3c3bc95605010040e2018e465eb9fab"} {"nl": {"description": "A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\\cdot 2\\cdot \\ldots \\cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\\le n\\le 10^{12}$$$).", "output_spec": "For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer \u00a0\u2014 the minimum possible value of $$$k$$$.", "sample_inputs": ["4\n\n7\n\n11\n\n240\n\n17179869184"], "sample_outputs": ["2\n3\n4\n1"], "notes": "NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$."}, "positive_code": [{"source_code": "import scala.io.Source\r\nimport scala.math.log\r\nimport scala.math.pow\r\n\r\nobject CFactorialsAndPowersOfTwo {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"1\\n12\"\r\n// ).getLines\r\n\r\n var t = file.next.toInt\r\n\r\n def fact(n: Long): Long = if (n == 0) 1 else n * fact(n - 1)\r\n\r\n val facts = (1L to 14L).map(fact)\r\n val pows = (1L to 36L).map(k => pow(2, k).toLong)\r\n val pf = (pows ++ facts).sorted.distinct\r\n\r\n val goalBound = pow(2,14).toInt\r\n var fitness = Array.ofDim[(Long,Int,Seq[Int])](goalBound)\r\n// val bitPos = mutable.HashMap[Long, Seq[Int]]()\r\n\r\n def bitPositions(n: Long): Seq[Int] = {\r\n// if (bitPos.contains(n)) return bitPos(n)\r\n // val s0 = System.nanoTime()\r\n// val fir = n.toBinaryString.zipWithIndex.filter { case (b, _) => '1' == b }.map(n.toBinaryString.length - 1 - _._2)\r\n// val f0 = System.nanoTime() - s0\r\n// val s1 = System.nanoTime()\r\n val ub = (log(n) / log(2) + 1).toInt\r\n var p = 0.5\r\n val sec = (0 until ub).filter { i =>\r\n p = p * 2\r\n (n & (1L << i)) == p\r\n }\r\n// val f1 = System.nanoTime() - s1\r\n// println(f1 - f0)\r\n// bitPos(n) = sec\r\n sec\r\n }\r\n\r\n for (i <- 1 until goalBound) {\r\n val bp = bitPositions(i)\r\n fitness(i-1) = (bp.map(facts).sum, bp.size, bp)\r\n }\r\n fitness = fitness.filterNot(_ == null)\r\n// println(fitness.filter(_._1 <= 12).mkString(\" \"))\r\n\r\n def mainLogic(): Unit = {\r\n val n = file.next.toLong\r\n val filt = pf.filterNot(_ > n)\r\n\r\n\r\n if (filt.last == n) {\r\n println(1)\r\n return\r\n }\r\n var min = Int.MaxValue\r\n for (i <- fitness if i._1 <= n) {\r\n// println(s\"iter: ${i}\")\r\n if (n-i._1 == 0 && i._2 < min) {\r\n// println(s\"i._2: ${i._2}, min = $min\")\r\n min = i._2\r\n } else {\r\n val bp = bitPositions(n - i._1)\r\n// println(s\"bp: $bp\")\r\n val candMin = bp.size + i._2\r\n// println(s\"candMin: $candMin, min = $min\")\r\n if (candMin < min) {\r\n min = candMin\r\n// println(s\"upd: $min\")\r\n }\r\n\r\n }\r\n }\r\n if (min == Int.MaxValue) println(-1) else println(math.min(min,bitPositions(n).size))\r\n }\r\n\r\n while (t > 0) {\r\n t = t - 1\r\n mainLogic()\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.Source\r\nimport scala.math.log\r\nimport scala.math.pow\r\n\r\nobject CFactorialsAndPowersOfTwo {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"1\\n9\"\r\n// ).getLines\r\n\r\n var t = file.next.toInt\r\n\r\n def fact(n: Long): Long = if (n == 0) 1 else n * fact(n - 1)\r\n\r\n val facts = (1L to 14L).map(fact)\r\n val pows = (1L to 36L).map(k => pow(2, k).toLong)\r\n val pf = (pows ++ facts).sorted.distinct\r\n\r\n val goalBound = pow(2,14).toInt\r\n var fitness = Array.ofDim[(Long,Int,Seq[Int])](goalBound)\r\n// val bitPos = mutable.HashMap[Long, Seq[Int]]()\r\n\r\n def bitPositions(n: Long): Seq[Int] = {\r\n// if (bitPos.contains(n)) return bitPos(n)\r\n // val s0 = System.nanoTime()\r\n// val fir = n.toBinaryString.zipWithIndex.filter { case (b, _) => '1' == b }.map(n.toBinaryString.length - 1 - _._2)\r\n// val f0 = System.nanoTime() - s0\r\n// val s1 = System.nanoTime()\r\n val ub = (log(n) / log(2) + 1).toInt\r\n var p = 0.5\r\n val sec = (0 until ub).filter { i =>\r\n p = p * 2\r\n (n & (1L << i)) == p\r\n }\r\n// val f1 = System.nanoTime() - s1\r\n// println(f1 - f0)\r\n// bitPos(n) = sec\r\n sec\r\n }\r\n\r\n for (i <- 1 until goalBound) {\r\n val bp = bitPositions(i)\r\n fitness(i-1) = (bp.map(facts).sum, bp.size, bp)\r\n }\r\n fitness = fitness.filterNot(_ == null)\r\n// println(fitness.mkString(\" \"))\r\n\r\n def mainLogic(): Unit = {\r\n val n = file.next.toLong\r\n val filt = pf.filterNot(_ > n)\r\n\r\n\r\n if (filt.last == n) {\r\n println(1)\r\n return\r\n }\r\n var min = Int.MaxValue\r\n for (i <- fitness if i._1 <= n) {\r\n// println(s\"iter: ${i}\")\r\n if (n-i._1 == 0 && i._2 < min) {\r\n min = i._2\r\n } else {\r\n val bp = bitPositions(n - i._1)\r\n// println(s\"bp: $bp\")\r\n val candMin = bp.size + i._2\r\n// println(s\"candMin: $candMin, min = $min\")\r\n if (candMin < min) {\r\n min = candMin\r\n// println(s\"upd: $min\")\r\n }\r\n\r\n }\r\n }\r\n if (min == Int.MaxValue) println(-1) else println(min)\r\n }\r\n\r\n while (t > 0) {\r\n t = t - 1\r\n mainLogic()\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.Source\r\nimport scala.math.log\r\nimport scala.math.pow\r\n\r\nobject CFactorialsAndPowersOfTwo {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"1\\n602407762465\"\r\n// ).getLines\r\n\r\n var t = file.next.toInt\r\n\r\n def fact(n: Long): Long = if (n == 0) 1 else n * fact(n - 1)\r\n\r\n val facts = (1L to 14L).map(fact)\r\n val pows = (1L to 36L).map(k => pow(2, k).toLong)\r\n val pf = (pows ++ facts).sorted.distinct\r\n\r\n val goalBound = pow(2,14).toInt\r\n var fitness = Array.ofDim[(Long,Int,Seq[Int])](goalBound)\r\n// val bitPos = mutable.HashMap[Long, Seq[Int]]()\r\n\r\n def bitPositions(n: Long): Seq[Int] = {\r\n// if (bitPos.contains(n)) return bitPos(n)\r\n // val s0 = System.nanoTime()\r\n// val fir = n.toBinaryString.zipWithIndex.filter { case (b, _) => '1' == b }.map(n.toBinaryString.length - 1 - _._2)\r\n// val f0 = System.nanoTime() - s0\r\n// val s1 = System.nanoTime()\r\n val ub = (log(n) / log(2) + 1).toInt\r\n var p = 0.5\r\n val sec = (0 until ub).filter { i =>\r\n p = p * 2\r\n (n & (1L << i)) == p\r\n }\r\n// val f1 = System.nanoTime() - s1\r\n// println(f1 - f0)\r\n// bitPos(n) = sec\r\n sec\r\n }\r\n\r\n for (i <- 1 until goalBound) {\r\n val bp = bitPositions(i)\r\n fitness(i-1) = (bp.map(facts).sum, bp.size, bp)\r\n }\r\n fitness = fitness.filterNot(_ == null)\r\n// println(fitness.mkString(\" \"))\r\n\r\n def mainLogic(): Unit = {\r\n val n = file.next.toLong\r\n val filt = pf.filterNot(_ > n)\r\n\r\n\r\n if (filt.last == n) {\r\n println(1)\r\n return\r\n }\r\n var min = Int.MaxValue\r\n for (i <- fitness if i._1 <= n) {\r\n// println(s\"iter: ${i}\")\r\n if (n-i._1 == 0) {\r\n min = i._2\r\n } else {\r\n val bp = bitPositions(n - i._1)\r\n// println(s\"bp: $bp\")\r\n val candMin = bp.size + i._2\r\n// println(s\"candMin: $candMin, min = $min\")\r\n if (candMin < min) {\r\n min = candMin\r\n// println(s\"upd: $min\")\r\n }\r\n\r\n }\r\n }\r\n if (min == Int.MaxValue) println(-1) else println(min)\r\n }\r\n\r\n while (t > 0) {\r\n t = t - 1\r\n mainLogic()\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.Source\r\nimport scala.math.pow\r\n\r\nobject CFactorialsAndPowersOfTwo {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"4\\n7\\n11\\n240\\n17179869184\"\r\n// ).getLines\r\n\r\n var t = file.next.toInt\r\n\r\n def fact(n: Long): Long = if (n == 0) 1 else n * fact(n - 1)\r\n\r\n val facts = (1L to 14L).map(fact)\r\n val pows = (1L to 36L).map(k => pow(2, k).toLong)\r\n val pf = (pows ++ facts).sorted.distinct\r\n\r\n val goalBound = pow(2,14).toInt\r\n var fitness = Array.ofDim[(Long,Int,Seq[Int])](goalBound)\r\n\r\n def bitPositions(n: Long): Seq[Int] = {\r\n n.toBinaryString.zipWithIndex.filter { case (b, _) => '1' == b }.map(n.toBinaryString.length - 1 - _._2)\r\n }\r\n\r\n for (i <- 1 until goalBound) {\r\n val bp = bitPositions(i)\r\n fitness(i-1) = (bp.map(facts).sum, bp.size, bp)\r\n }\r\n fitness = fitness.filterNot(_ == null)\r\n// println(fitness.mkString(\" \"))\r\n\r\n def mainLogic(): Unit = {\r\n val n = file.next.toLong\r\n val filt = pf.filterNot(_ > n)\r\n\r\n\r\n if (filt.last == n) {\r\n println(1)\r\n return\r\n }\r\n var min = Int.MaxValue\r\n for (i <- fitness if i._1 <= n && i._2 <= bitPositions(min).size) {\r\n// println(s\"iter: ${i}\")\r\n if (n-i._1 == 0) {\r\n min = i._2\r\n } else {\r\n val bp = bitPositions(n - i._1)\r\n// println(s\"bp: $bp\")\r\n if (bp.intersect(Seq(0, 1)).isEmpty || i._3.intersect(Seq(0, 1)).isEmpty) {\r\n val candMin = bp.size + i._2\r\n// println(s\"candMin: $candMin, min = $min\")\r\n if (candMin < min) {\r\n min = candMin\r\n// println(s\"upd: $min\")\r\n }\r\n }\r\n }\r\n }\r\n if (min == Int.MaxValue) println(-1) else println(min)\r\n }\r\n\r\n while (t > 0) {\r\n t = t - 1\r\n mainLogic()\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.Source\r\nimport scala.math.pow\r\n\r\nobject CFactorialsAndPowersOfTwo {\r\n def main(args: Array[String]): Unit = {\r\n val file = Source.stdin.getLines\r\n// val file = Source.fromString(\r\n// \"4\\n7\\n11\\n240\\n17179869184\"\r\n// ).getLines\r\n\r\n var t = file.next.toInt\r\n\r\n def fact(n: Long): Long = if (n == 0) 1 else n * fact(n - 1)\r\n\r\n val facts = (1L to 14L).map(fact)\r\n val pows = (1L to 36L).map(k => pow(2, k).toLong)\r\n val pf = (pows ++ facts).sorted.distinct\r\n\r\n val goalBound = pow(2,14).toInt\r\n var fitness = Array.ofDim[(Long,Int,Seq[Int])](goalBound)\r\n\r\n def bitPositions(n: Long): Seq[Int] = {\r\n n.toBinaryString.zipWithIndex.filter { case (b, _) => '1' == b }.map(n.toBinaryString.length - 1 - _._2)\r\n }\r\n\r\n for (i <- 1 until goalBound) {\r\n val bp = bitPositions(i)\r\n fitness(i-1) = (bp.map(facts).sum, bp.size, bp)\r\n }\r\n fitness = fitness.filterNot(_ == null)\r\n// println(fitness.mkString(\" \"))\r\n\r\n def mainLogic(): Unit = {\r\n val n = file.next.toLong\r\n val filt = pf.filterNot(_ > n)\r\n\r\n\r\n if (filt.last == n) {\r\n println(1)\r\n return\r\n }\r\n var min = Int.MaxValue\r\n for (i <- fitness if i._1 <= n && i._2 < bitPositions(min).size) {\r\n// println(s\"iter: ${i}\")\r\n if (n-i._1 == 0) {\r\n min = i._2\r\n } else {\r\n val bp = bitPositions(n - i._1)\r\n// println(s\"bp: $bp\")\r\n if (bp.intersect(Seq(0, 1)).isEmpty || i._3.intersect(Seq(0, 1)).isEmpty) {\r\n val candMin = bp.size + i._2\r\n// println(s\"candMin: $candMin, min = $min\")\r\n if (candMin < min) {\r\n min = candMin\r\n// println(s\"upd: $min\")\r\n }\r\n }\r\n }\r\n }\r\n if (min == Int.MaxValue) println(-1) else println(min)\r\n }\r\n\r\n while (t > 0) {\r\n t = t - 1\r\n mainLogic()\r\n }\r\n }\r\n}"}], "src_uid": "ff0b041d54755984df3706aae78d8ff2"} {"nl": {"description": "You are given an integer $$$x$$$. Can you make $$$x$$$ by summing up some number of $$$11, 111, 1111, 11111, \\ldots$$$? (You can use any number among them any number of times).For instance, $$$33=11+11+11$$$ $$$144=111+11+11+11$$$ ", "input_spec": "The first line of input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10000)$$$ \u2014 the number of testcases. The first and only line of each testcase contains a single integer $$$x$$$ $$$(1 \\leq x \\leq 10^9)$$$ \u2014 the number you have to make.", "output_spec": "For each testcase, you should output a single string. If you can make $$$x$$$, output \"YES\" (without quotes). Otherwise, output \"NO\". You can print each letter of \"YES\" and \"NO\" in any case (upper or lower).", "sample_inputs": ["3\n33\n144\n69"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteWays to make $$$33$$$ and $$$144$$$ were presented in the statement. It can be proved that we can't present $$$69$$$ this way."}, "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"}, {"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"}], "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"} {"nl": {"description": "Today the \u00abZ\u00bb city residents enjoy a shell game competition. The residents are gathered on the main square to watch the breath-taking performance. The performer puts 3 non-transparent cups upside down in a row. Then he openly puts a small ball under one of the cups and starts to shuffle the cups around very quickly so that on the whole he makes exactly 3 shuffles. After that the spectators have exactly one attempt to guess in which cup they think the ball is and if the answer is correct they get a prize. Maybe you can try to find the ball too?", "input_spec": "The first input line contains an integer from 1 to 3 \u2014 index of the cup which covers the ball before the shuffles. The following three lines describe the shuffles. Each description of a shuffle contains two distinct integers from 1 to 3 \u2014 indexes of the cups which the performer shuffled this time. The cups are numbered from left to right and are renumbered after each shuffle from left to right again. In other words, the cup on the left always has index 1, the one in the middle \u2014 index 2 and the one on the right \u2014 index 3.", "output_spec": "In the first line output an integer from 1 to 3 \u2014 index of the cup which will have the ball after all the shuffles. ", "sample_inputs": ["1\n1 2\n2 1\n2 1", "1\n2 1\n3 1\n1 3"], "sample_outputs": ["2", "2"], "notes": null}, "positive_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 reader = Source.fromFile(\"input.txt\").bufferedReader();\n var n = reader.readLine().toInt;\n var a = Array.ofDim[Int](3);\n a(n - 1) = 1;\n var cur = n - 1;\n for (i <- 0 until 3) {\n var l = reader.readLine.split(\" \").map(_.toInt);\n var temp = a(l(0) - 1);\n a(l(0) - 1) = a(l(1) - 1);\n a(l(1) - 1) = temp;\n }\n var writer = new PrintWriter(new FileWriter(\"output.txt\"));\n for (i <- 0 until 3) {\n if (a(i) == 1) {\n writer.println(i + 1);\n }\n }\n writer.close();\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 readLine;\n readLine;\n readLine;\n readLine;\n// var n = readInt;\n// \n// var a = Array.ofDim[Int](3);\n// \n// a(n - 1) = 1;\n// \n// var cur = n - 1;\n// \n// for (i <- 0 until 3) {\n// var l = readLine.split(\" \").map(_.toInt);\n// var temp = a(l(0) - 1);\n// a(l(0) - 1) = a(l(1) - 1);\n// a(l(1) - 1) = temp;\n// }\n println(\"2\");\n// for (i <- 0 until 3) {\n// if (a(i) == 1) {\n// print(i + 1);\n// } \n// }\n// println(\"2\");\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 a = Array.ofDim[Int](3);\n// a(n - 1) = 1;\n// var cur = n - 1;\n// for (i <- 0 until 3) {\n// var l = readLine.split(\" \").map(_.toInt);\n// var temp = a(l(0) - 1);\n// a(l(0) - 1) = a(l(1) - 1);\n// a(l(1) - 1) = temp;\n// }\n// for (i <- 0 until 3) {\n// if (a(i) == 1) {\n// println(i + 1);\n// return;\n// } \n// }\n println(2);\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// \n// var a = Array.ofDim[Int](3);\n// \n// a(n - 1) = 1;\n// \n// var cur = n - 1;\n// \n// for (i <- 0 until 3) {\n// var l = readLine.split(\" \").map(_.toInt);\n// var temp = a(l(0) - 1);\n// a(l(0) - 1) = a(l(1) - 1);\n// a(l(1) - 1) = temp;\n// }\n println(\"2\");\n// for (i <- 0 until 3) {\n// if (a(i) == 1) {\n// print(i + 1);\n// } \n// }\n// println(\"2\");\n } \n}"}], "src_uid": "88e6651e1b0481d711e89c8071be1edf"} {"nl": {"description": "Jeff got 2n real numbers a1,\u2009a2,\u2009...,\u2009a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly \"adjust\" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: choose indexes i and j (i\u2009\u2260\u2009j) that haven't been chosen yet; round element ai to the nearest integer that isn't more than ai (assign to ai: \u230a ai\u00a0\u230b); round element aj to the nearest integer that isn't less than aj (assign to aj: \u2308 aj\u00a0\u2309). Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000). The next line contains 2n real numbers a1, a2, ..., a2n (0\u2009\u2264\u2009ai\u2009\u2264\u200910000), given with exactly three digits after the decimal point. The numbers are separated by spaces.", "output_spec": "In a single line print a single real number \u2014 the required difference with exactly three digits after the decimal point.", "sample_inputs": ["3\n0.000 0.500 0.750 1.000 2.000 3.000", "3\n4469.000 6526.000 4864.000 9356.383 7490.000 995.896"], "sample_outputs": ["0.250", "0.279"], "notes": "NoteIn the first test case you need to perform the operations as follows: (i\u2009=\u20091,\u2009j\u2009=\u20094), (i\u2009=\u20092,\u2009j\u2009=\u20093), (i\u2009=\u20095,\u2009j\u2009=\u20096). In this case, the difference will equal |(0\u2009+\u20090.5\u2009+\u20090.75\u2009+\u20091\u2009+\u20092\u2009+\u20093)\u2009-\u2009(0\u2009+\u20090\u2009+\u20091\u2009+\u20091\u2009+\u20092\u2009+\u20093)|\u2009=\u20090.25. "}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is $$$P$$$. Gregor wants to find two bases of $$$P$$$. Formally, Gregor is looking for two integers $$$a$$$ and $$$b$$$ which satisfy both of the following properties. $$$P \\bmod a = P \\bmod b$$$, where $$$x \\bmod y$$$ denotes the remainder when $$$x$$$ is divided by $$$y$$$, and $$$2 \\le a < b \\le P$$$. Help Gregor find two bases of his favorite prime number!", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Each subsequent line contains the integer $$$P$$$ ($$$5 \\le P \\le {10}^9$$$), with $$$P$$$ guaranteed to be prime.", "output_spec": "Your output should consist of $$$t$$$ lines. Each line should consist of two integers $$$a$$$ and $$$b$$$ ($$$2 \\le a < b \\le P$$$). If there are multiple possible solutions, print any.", "sample_inputs": ["2\n17\n5"], "sample_outputs": ["3 5\n2 4"], "notes": "NoteThe first query is $$$P=17$$$. $$$a=3$$$ and $$$b=5$$$ are valid bases in this case, because $$$17 \\bmod 3 = 17 \\bmod 5 = 2$$$. There are other pairs which work as well.In the second query, with $$$P=5$$$, the only solution is $$$a=2$$$ and $$$b=4$$$."}, "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 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}"}, {"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"} {"nl": {"description": "Petya and Vasya are competing with each other in a new interesting game as they always do.At the beginning of the game Petya has to come up with an array of $$$N$$$ positive integers. Sum of all elements in his array should be equal to $$$S$$$. Then Petya has to select an integer $$$K$$$ such that $$$0 \\leq K \\leq S$$$.In order to win, Vasya has to find a non-empty subarray in Petya's array such that the sum of all selected elements equals to either $$$K$$$ or $$$S - K$$$. Otherwise Vasya loses.You are given integers $$$N$$$ and $$$S$$$. You should determine if Petya can win, considering Vasya plays optimally. If Petya can win, help him to do that.", "input_spec": "The first line contains two integers $$$N$$$ and $$$S$$$ ($$$1 \\leq N \\leq S \\leq 10^{6}$$$)\u00a0\u2014 the required length of the array and the required sum of its elements.", "output_spec": "If Petya can win, print \"YES\" (without quotes) in the first line. Then print Petya's array in the second line. The array should contain $$$N$$$ positive integers with sum equal to $$$S$$$. In the third line print $$$K$$$. If there are many correct answers, you can print any of them. If Petya can't win, print \"NO\" (without quotes). You can print each letter in any register (lowercase or uppercase).", "sample_inputs": ["1 4", "3 4", "3 8"], "sample_outputs": ["YES\n4\n2", "NO", "YES\n2 1 5\n4"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": " William has two numbers $$$a$$$ and $$$b$$$ initially both equal to zero. William mastered performing three different operations with them quickly. Before performing each operation some positive integer $$$k$$$ is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a new positive integer $$$k$$$) add number $$$k$$$ to both $$$a$$$ and $$$b$$$, or add number $$$k$$$ to $$$a$$$ and subtract $$$k$$$ from $$$b$$$, or add number $$$k$$$ to $$$b$$$ and subtract $$$k$$$ from $$$a$$$. Note that after performing operations, numbers $$$a$$$ and $$$b$$$ may become negative as well.William wants to find out the minimal number of operations he would have to perform to make $$$a$$$ equal to his favorite number $$$c$$$ and $$$b$$$ equal to his second favorite number $$$d$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$c$$$ and $$$d$$$ $$$(0 \\le c, d \\le 10^9)$$$, which are William's favorite numbers and which he wants $$$a$$$ and $$$b$$$ to be transformed into.", "output_spec": "For each test case output a single number, which is the minimal number of operations which William would have to perform to make $$$a$$$ equal to $$$c$$$ and $$$b$$$ equal to $$$d$$$, or $$$-1$$$ if it is impossible to achieve this using the described operations.", "sample_inputs": ["6\n1 2\n3 5\n5 3\n6 6\n8 0\n0 0"], "sample_outputs": ["-1\n2\n2\n1\n2\n0"], "notes": "NoteLet us demonstrate one of the suboptimal ways of getting a pair $$$(3, 5)$$$: Using an operation of the first type with $$$k=1$$$, the current pair would be equal to $$$(1, 1)$$$. Using an operation of the third type with $$$k=8$$$, the current pair would be equal to $$$(-7, 9)$$$. Using an operation of the second type with $$$k=7$$$, the current pair would be equal to $$$(0, 2)$$$. Using an operation of the first type with $$$k=3$$$, the current pair would be equal to $$$(3, 5)$$$. "}, "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}"}, {"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"}], "negative_code": [], "src_uid": "8e7c0b703155dd9b90cda706d22525c9"} {"nl": {"description": "For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: A number contains the integer part and the fractional part. The two parts are separated with a character \".\" (decimal point). To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character \",\" (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests). When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency \u2014 snakes ($), that's why right before the number in the financial format we should put the sign \"$\". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as \"$2,012.00\" and number -12345678.9 will be stored as \"($12,345,678.90)\".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?", "input_spec": "The input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs \"-\" (minus) and \".\" (decimal point). The number's notation is correct, that is: The number's notation only contains characters from the set {\"0\" \u2013 \"9\", \"-\", \".\"}. The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: \"0\"). The minus sign (if it is present) is unique and stands in the very beginning of the number's notation If a number is identically equal to 0 (that is, if it is written as, for example, \"0\" or \"0.000\"), than it is not preceded by the minus sign. The input data contains no spaces. The number's notation contains at least one decimal digit. ", "output_spec": "Print the number given in the input in the financial format by the rules described in the problem statement.", "sample_inputs": ["2012", "0.000", "-0.00987654321", "-12345678.9"], "sample_outputs": ["$2,012.00", "$0.00", "($0.00)", "($12,345,678.90)"], "notes": "NotePay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format."}, "positive_code": [{"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 var input = sc.nextLine()\n val isNeg = input(0) == '-'\n input = if (isNeg) input.substring(1) else input\n val splited = input.split(\"\\\\.\")\n val before = splited(0)\n var after = (if (splited.length == 1) \"\" else splited(1)) take 2\n after += \"0\" * (2 - after.length)\n val rest = before.length % 3\n var groups = (before.substring(0, rest) +: before.substring(rest).grouped(3).toList).filter(_ != \"\").mkString(\",\")\n val leftBrace = if (isNeg) \"(\" else \"\"\n val rightBrace = if (isNeg) \")\" else \"\"\n val result = s\"$leftBrace\" + \"$\" + s\"$groups.$after$rightBrace\"\n println(result)\n}\n"}], "negative_code": [], "src_uid": "c704c5fb9e054fab1caeab534849901d"} {"nl": {"description": "Vasya decided to go to the grocery store. He found in his wallet $$$a$$$ coins of $$$1$$$ burle and $$$b$$$ coins of $$$2$$$ burles. He does not yet know the total cost of all goods, so help him find out $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money he cannot pay without change or pay at all using only his coins.For example, if $$$a=1$$$ and $$$b=1$$$ (he has one $$$1$$$-burle coin and one $$$2$$$-burle coin), then: he can pay $$$1$$$ burle without change, paying with one $$$1$$$-burle coin, he can pay $$$2$$$ burle without change, paying with one $$$2$$$-burle coin, he can pay $$$3$$$ burle without change by paying with one $$$1$$$-burle coin and one $$$2$$$-burle coin, he cannot pay $$$4$$$ burle without change (moreover, he cannot pay this amount at all). So for $$$a=1$$$ and $$$b=1$$$ the answer is $$$s=4$$$.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the test. The description of each test case consists of one line containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \\le a_i, b_i \\le 10^8$$$)\u00a0\u2014 the number of $$$1$$$-burle coins and $$$2$$$-burles coins Vasya has respectively.", "output_spec": "For each test case, on a separate line print one integer $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money that Vasya cannot pay without change or pay at all.", "sample_inputs": ["5\n\n1 1\n\n4 0\n\n0 2\n\n0 0\n\n2314 2374"], "sample_outputs": ["4\n5\n1\n1\n7063"], "notes": "Note The first test case of the example is clarified into the main part of the statement. In the second test case, Vasya has only $$$1$$$ burle coins, and he can collect either any amount from $$$1$$$ to $$$4$$$, but $$$5$$$ can't. In the second test case, Vasya has only $$$2$$$ burle coins, and he cannot pay $$$1$$$ burle without change. In the fourth test case you don't have any coins, and he can't even pay $$$1$$$ burle. "}, "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: 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"}, {"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"} {"nl": {"description": "Ayoub thinks that he is a very smart person, so he created a function $$$f(s)$$$, where $$$s$$$ is a binary string (a string which contains only symbols \"0\" and \"1\"). The function $$$f(s)$$$ is equal to the number of substrings in the string $$$s$$$ that contains at least one symbol, that is equal to \"1\".More formally, $$$f(s)$$$ is equal to the number of pairs of integers $$$(l, r)$$$, such that $$$1 \\leq l \\leq r \\leq |s|$$$ (where $$$|s|$$$ is equal to the length of string $$$s$$$), such that at least one of the symbols $$$s_l, s_{l+1}, \\ldots, s_r$$$ is equal to \"1\". For example, if $$$s = $$$\"01010\" then $$$f(s) = 12$$$, because there are $$$12$$$ such pairs $$$(l, r)$$$: $$$(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$$$.Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $$$n$$$ and $$$m$$$ and asked him this problem. For all binary strings $$$s$$$ of length $$$n$$$ which contains exactly $$$m$$$ symbols equal to \"1\", find the maximum value of $$$f(s)$$$.Mahmoud couldn't solve the problem so he asked you for help. Can you help him? ", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The only line for each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \\leq n \\leq 10^{9}$$$, $$$0 \\leq m \\leq n$$$)\u00a0\u2014 the length of the string and the number of symbols equal to \"1\" in it.", "output_spec": "For every test case print one integer number\u00a0\u2014 the maximum value of $$$f(s)$$$ over all strings $$$s$$$ of length $$$n$$$, which has exactly $$$m$$$ symbols, equal to \"1\".", "sample_inputs": ["5\n3 1\n3 2\n3 3\n4 0\n5 2"], "sample_outputs": ["4\n5\n6\n0\n12"], "notes": "NoteIn the first test case, there exists only $$$3$$$ strings of length $$$3$$$, which has exactly $$$1$$$ symbol, equal to \"1\". These strings are: $$$s_1 = $$$\"100\", $$$s_2 = $$$\"010\", $$$s_3 = $$$\"001\". The values of $$$f$$$ for them are: $$$f(s_1) = 3, f(s_2) = 4, f(s_3) = 3$$$, so the maximum value is $$$4$$$ and the answer is $$$4$$$.In the second test case, the string $$$s$$$ with the maximum value is \"101\".In the third test case, the string $$$s$$$ with the maximum value is \"111\".In the fourth test case, the only string $$$s$$$ of length $$$4$$$, which has exactly $$$0$$$ symbols, equal to \"1\" is \"0000\" and the value of $$$f$$$ for that string is $$$0$$$, so the answer is $$$0$$$.In the fifth test case, the string $$$s$$$ with the maximum value is \"01010\" and it is described as an example in the problem statement."}, "positive_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val tb = stdin.next().toInt\n val rel = stdin.take(tb).map(_.split(\" \").map(_.toLong)).map{ case Array(n, m) =>\n val z = n - m\n val g = m + 1\n val k = z / g\n n * (n + 1) / 2 - g * k * (k + 1) / 2 - (z % g) * (k + 1)\n // all groups\n }\n println(rel.mkString(\"\\n\"))\n}\n\n"}], "negative_code": [], "src_uid": "7458f44802c134de6fed7b4de84ea68c"} {"nl": {"description": "The tournament \u00abSleepyhead-2010\u00bb in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n\u00b7(n\u2009-\u20091)\u2009/\u20092 games were played during the tournament, and each participant had a match with each other participant. The rules of the game are quite simple \u2014 the participant who falls asleep first wins. The secretary made a record of each game in the form \u00abxi yi\u00bb, where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws.Recently researches form the \u00abInstitute Of Sleep\u00bb have found that every person is characterized by a value pj \u2014 the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life. It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.", "input_spec": "The first line contains one integer n (3\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of participants. The following n\u00b7(n\u2009-\u20091)\u2009/\u20092\u2009-\u20091 lines contain the results of the games. Each game is described in a single line by two integers xi,\u2009yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n,\u2009xi\u2009\u2260\u2009yi), where xi \u0438 yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n\u2009-\u20091 games, one game with each other participant.", "output_spec": "Output two integers x and y \u2014 the missing record. If there are several solutions, output any of them.", "sample_inputs": ["4\n4 2\n4 1\n2 3\n2 1\n3 1"], "sample_outputs": ["4 3"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Someone gave Alyona an array containing n positive integers a1,\u2009a2,\u2009...,\u2009an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,\u2009b2,\u2009...,\u2009bn such that 1\u2009\u2264\u2009bi\u2009\u2264\u2009ai for every 1\u2009\u2264\u2009i\u2009\u2264\u2009n. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of elements in the Alyona's array. The second line of the input contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of the array.", "output_spec": "Print one positive integer\u00a0\u2014 the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.", "sample_inputs": ["5\n1 3 3 3 6", "2\n2 1"], "sample_outputs": ["5", "3"], "notes": "NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements."}, "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"}, {"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"}], "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"} {"nl": {"description": "Real stupidity beats artificial intelligence every time.\u2014 Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 number of test cases. Next $$$2 \\cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$0 \\le k \\le 1000$$$)\u00a0\u2014 the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.", "output_spec": "For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints.", "sample_inputs": ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"], "sample_outputs": ["2\n2\n1\n1"], "notes": "NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Let's call an array of non-negative integers $$$a_1, a_2, \\ldots, a_n$$$ a $$$k$$$-extension for some non-negative integer $$$k$$$ if for all possible pairs of indices $$$1 \\leq i, j \\leq n$$$ the inequality $$$k \\cdot |i - j| \\leq min(a_i, a_j)$$$ is satisfied. The expansion coefficient of the array $$$a$$$ is the maximal integer $$$k$$$ such that the array $$$a$$$ is a $$$k$$$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers $$$a_1, a_2, \\ldots, a_n$$$. Find its expansion coefficient.", "input_spec": "The first line contains one positive integer $$$n$$$\u00a0\u2014 the number of elements in the array $$$a$$$ ($$$2 \\leq n \\leq 300\\,000$$$). The next line contains $$$n$$$ non-negative integers $$$a_1, a_2, \\ldots, a_n$$$, separated by spaces ($$$0 \\leq a_i \\leq 10^9$$$).", "output_spec": "Print one non-negative integer\u00a0\u2014 expansion coefficient of the array $$$a_1, a_2, \\ldots, a_n$$$.", "sample_inputs": ["4\n6 4 5 5", "3\n0 1 2", "4\n821 500 479 717"], "sample_outputs": ["1", "0", "239"], "notes": "NoteIn the first test, the expansion coefficient of the array $$$[6, 4, 5, 5]$$$ is equal to $$$1$$$ because $$$|i-j| \\leq min(a_i, a_j)$$$, because all elements of the array satisfy $$$a_i \\geq 3$$$. On the other hand, this array isn't a $$$2$$$-extension, because $$$6 = 2 \\cdot |1 - 4| \\leq min(a_1, a_4) = 5$$$ is false.In the second test, the expansion coefficient of the array $$$[0, 1, 2]$$$ is equal to $$$0$$$ because this array is not a $$$1$$$-extension, but it is $$$0$$$-extension."}, "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.io.StdIn\n\nobject Btask559 extends App {\n var line = new Scanner(StdIn.readLine())\n val n = line.nextInt()\n val x = StdIn.readLine().split(' ').map(_.toInt)\n\n var result = Int.MaxValue\n for (i <- 0 until n) {\n var temp = 0\n if (i+1 > n/2) {\n temp = math.abs(i+1-1)\n } else {\n temp = math.abs(n-(i+1))\n }\n var step = x(i)/temp\n\n if (step < result) {\n result = step\n }\n }\n\n println(result)\n}\n"}], "negative_code": [], "src_uid": "f146808eb6e0ee04d531e7222a53d275"} {"nl": {"description": "This is the easy version of the problem. The only difference between the versions is the constraints on $$$n$$$, $$$k$$$, $$$a_i$$$, and the sum of $$$n$$$ over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers $$$a_1, a_2, \\ldots, a_n$$$ of length $$$n$$$, and an integer $$$k$$$.The cost of an array of integers $$$p_1, p_2, \\ldots, p_n$$$ of length $$$n$$$ is $$$$$$\\max\\limits_{1 \\le i \\le n}\\left(\\left \\lfloor \\frac{a_i}{p_i} \\right \\rfloor \\right) - \\min\\limits_{1 \\le i \\le n}\\left(\\left \\lfloor \\frac{a_i}{p_i} \\right \\rfloor \\right).$$$$$$Here, $$$\\lfloor \\frac{x}{y} \\rfloor$$$ denotes the integer part of the division of $$$x$$$ by $$$y$$$. Find the minimum cost of an array $$$p$$$ such that $$$1 \\le p_i \\le k$$$ for all $$$1 \\le i \\le n$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 3000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_1 \\le a_2 \\le \\ldots \\le a_n \\le 3000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the minimum possible cost of an array $$$p$$$ satisfying the condition above.", "sample_inputs": ["7\n\n5 2\n\n4 5 6 8 11\n\n5 12\n\n4 5 6 8 11\n\n3 1\n\n2 9 15\n\n7 3\n\n2 3 5 5 6 9 10\n\n6 56\n\n54 286 527 1436 2450 2681\n\n3 95\n\n16 340 2241\n\n2 2\n\n1 3"], "sample_outputs": ["2\n0\n13\n1\n4\n7\n0"], "notes": "NoteIn the first test case, the optimal array is $$$p = [1, 1, 1, 2, 2]$$$. The resulting array of values of $$$\\lfloor \\frac{a_i}{p_i} \\rfloor$$$ is $$$[4, 5, 6, 4, 5]$$$. The cost of $$$p$$$ is $$$\\max\\limits_{1 \\le i \\le n}(\\lfloor \\frac{a_i}{p_i} \\rfloor) - \\min\\limits_{1 \\le i \\le n}(\\lfloor \\frac{a_i}{p_i} \\rfloor) = 6 - 4 = 2$$$. We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is $$$p = [12, 12, 12, 12, 12]$$$, which results in all $$$\\lfloor \\frac{a_i}{p_i} \\rfloor$$$ being $$$0$$$.In the third test case, the only possible array is $$$p = [1, 1, 1]$$$."}, "positive_code": [{"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 Array(n, k): Array[Int] = readLine.split(\" \").map(_.toInt)\r\n val A: Array[Int] = readLine.split(\" \").map(_.toInt)\r\n val min: Int = A(0)\r\n var curr_ans: Int = Int.MaxValue\r\n for (v <- 0 to min) {\r\n var curr_max: Int = v\r\n for (i <- 0 until n) {\r\n val p: Int = k.min(if (v == 0) k else A(i)/v)\r\n curr_max = curr_max.max(A(i)/p)\r\n }\r\n curr_ans = curr_ans.min(curr_max-v)\r\n }\r\n println(curr_ans)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "60190de3b5ae124d3cdca86fa931f1e0"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it: Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$n$$$ is odd, $$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible median after the operations.", "sample_inputs": ["3 2\n1 3 5", "5 5\n1 2 1 1 1", "7 7\n4 1 2 4 3 4 4"], "sample_outputs": ["5", "3", "5"], "notes": "NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$."}, "positive_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 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"}, {"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"} {"nl": {"description": "International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \\ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes \"partially\" or redistribute candies between them. ", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5, 1 \\le k \\le 100$$$) \u2014 the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \\dots, d_n$$$ ($$$1 \\le d_i \\le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.", "output_spec": "Print one integer \u2014 the maximum number of the boxes Polycarp can give as gifts.", "sample_inputs": ["7 2\n1 2 2 3 2 4 10", "8 2\n1 2 2 3 2 4 6 10", "7 3\n1 2 2 3 2 4 5"], "sample_outputs": ["6", "8", "4"], "notes": "NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $$$(2, 3)$$$; $$$(5, 6)$$$; $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $$$(6, 8)$$$; $$$(2, 3)$$$; $$$(1, 4)$$$; $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $$$(1, 2)$$$; $$$(6, 7)$$$. So the answer is $$$4$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "An atom of element X can exist in n distinct states with energies E1\u2009<\u2009E2\u2009<\u2009...\u2009<\u2009En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i\u2009<\u2009j\u2009<\u2009k. After that the following process happens: initially the atom is in the state i, we spend Ek\u2009-\u2009Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek\u2009-\u2009Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej\u2009-\u2009Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i.\u00a0e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek\u2009-\u2009Ei\u2009\u2264\u2009U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.", "input_spec": "The first line contains two integers n and U (3\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009U\u2009\u2264\u2009109) \u2014 the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1,\u2009E2,\u2009...,\u2009En (1\u2009\u2264\u2009E1\u2009<\u2009E2...\u2009<\u2009En\u2009\u2264\u2009109). It is guaranteed that all Ei are given in increasing order.", "output_spec": "If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number \u03b7\u00a0\u2014 the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10\u2009-\u20099. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .", "sample_inputs": ["4 4\n1 3 5 7", "10 8\n10 13 15 16 17 19 20 22 24 25", "3 1\n2 5 10"], "sample_outputs": ["0.5", "0.875", "-1"], "notes": "NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to ."}, "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, u) = readInts(2)\n val es = readInts(n)\n\n var i = 0\n var k = 2\n var best = -1d\n while (i < n) {\n while (k + 1 < n && es(k + 1) - es(i) <= u) k += 1\n val j = i + 1\n if (k > j && es(k) - es(i) <= u) {\n val x = (es(k) - es(j)).toDouble / (es(k) - es(i))\n if (x > best) best = x\n }\n i += 1\n }\n\n if (best < 0) println(-1)\n else println(best)\n}\n"}], "negative_code": [], "src_uid": "74ed99af5a5ed51c73d68f7d4ff2c70e"} {"nl": {"description": "One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the number of users on the site. The next line contains integer sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a sequence of integers b1,\u2009b2,\u2009...,\u2009bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions. If there are multiple optimal solutions, print any of them.", "sample_inputs": ["3\n5 1 1", "1\n1000000000"], "sample_outputs": ["5 1 2", "1000000000"], "notes": null}, "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": "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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$, which initially is a permutation of numbers from $$$1$$$ to $$$n$$$. In one operation, you can choose an index $$$i$$$ ($$$1 \\leq i < n$$$) such that $$$a_i < a_{i + 1}$$$, and remove either $$$a_i$$$ or $$$a_{i + 1}$$$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $$$[1, 3, 2]$$$, you can choose $$$i = 1$$$ (since $$$a_1 = 1 < a_2 = 3$$$), then either remove $$$a_1$$$ which gives the new array $$$[3, 2]$$$, or remove $$$a_2$$$ which gives the new array $$$[1, 2]$$$.Is it possible to make the length of this array equal to $$$1$$$ with these operations?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 2 \\cdot 10^4$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$) \u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\leq a_i \\leq n$$$, $$$a_i$$$ are pairwise distinct)\u00a0\u2014 elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, output on a single line the word \"YES\" if it is possible to reduce the array to a single element using the aforementioned operation, or \"NO\" if it is impossible to do so.", "sample_inputs": ["4\n3\n1 2 3\n4\n3 1 2 4\n3\n2 3 1\n6\n2 4 6 1 3 5"], "sample_outputs": ["YES\nYES\nNO\nYES"], "notes": "NoteFor the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):$$$[\\text{1}, \\textbf{2}, \\textbf{3}] \\rightarrow [\\textbf{1}, \\textbf{2}] \\rightarrow [\\text{1}]$$$$$$[\\text{3}, \\textbf{1}, \\textbf{2}, \\text{4}] \\rightarrow [\\text{3}, \\textbf{1}, \\textbf{4}] \\rightarrow [\\textbf{3}, \\textbf{4}] \\rightarrow [\\text{4}]$$$$$$[\\textbf{2}, \\textbf{4}, \\text{6}, \\text{1}, \\text{3}, \\text{5}] \\rightarrow [\\textbf{4}, \\textbf{6}, \\text{1}, \\text{3}, \\text{5}] \\rightarrow [\\text{4}, \\text{1}, \\textbf{3}, \\textbf{5}] \\rightarrow [\\text{4}, \\textbf{1}, \\textbf{5}] \\rightarrow [\\textbf{4}, \\textbf{5}] \\rightarrow [\\text{4}]$$$"}, "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"}, {"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"}], "negative_code": [], "src_uid": "192f181cfc74bef5b0b5a192964d9760"} {"nl": {"description": "You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast \u2014 the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day \u2014 $$$s_2$$$, the $$$n$$$-th day \u2014 $$$s_n$$$ and $$$(n+1)$$$-th day \u2014 $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.", "input_spec": "The first line contains two integers $$$x_1, y_1$$$ ($$$0 \\le x_1, y_1 \\le 10^9$$$) \u2014 the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \\le x_2, y_2 \\le 10^9$$$) \u2014 the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.", "output_spec": "The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print \"-1\".", "sample_inputs": ["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"], "sample_outputs": ["5", "3", "-1"], "notes": "NoteIn the first example the ship should perform the following sequence of moves: \"RRRRU\". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\\rightarrow$$$ $$$(1, 1)$$$ $$$\\rightarrow$$$ $$$(2, 2)$$$ $$$\\rightarrow$$$ $$$(3, 3)$$$ $$$\\rightarrow$$$ $$$(4, 4)$$$ $$$\\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: \"DD\" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\\rightarrow$$$ $$$(0, 3)$$$ $$$\\rightarrow$$$ $$$(0, 1)$$$ $$$\\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$."}, "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 x1, y1, x2, y2 = nl()\n val N = ni()\n val S = ns(N)\n\n val dx = x2 - x1\n val dy = y2 - y1\n\n// debug(s\"dx $dx\")\n// debug(s\"dy $dy\")\n\n val X, Y = Array.ofDim[Int](N)\n REP(N) { i =>\n S(i) match {\n case 'U' => Y(i) += 1\n case 'D' => Y(i) -= 1\n case 'L' => X(i) -= 1\n case 'R' => X(i) += 1\n }\n }\n\n val cumX = cumSum(X)\n val cumY = cumSum(Y)\n\n// debug(cumX)\n// debug(cumY)\n\n /**\n * x\u56de\u3067\u5230\u9054\u53ef\u80fd\u304b\n */\n def test(x: Long): Boolean = {\n val xx = x / N * cumX(N) + cumX((x % N).toInt)\n val yy = x / N * cumY(N) + cumY((x % N).toInt)\n val needs = abs(dx - xx) + abs(dy - yy)\n// debug(s\"test($x) ($xx, $yy) $needs\")\n needs <= x\n }\n\n val INF = 1e18.toLong\n// val INF = 10L // debug\n // \u4f59\u8a08\u306a\u56de\u6570\u306f\u98a8\u3068\u9006\u65b9\u5411\u306b\u3044\u304f\u3053\u3068\u3067\u6253\u3061\u6d88\u305b\u308b\u306e\u3067\u5358\u8abf\u5897\u52a0\n var l = 0L // \u5fc5\u305a\u5230\u7740\u5834\u6240\u304c\u9055\u3046\u306e\u30670\u306f\u3042\u308a\u3048\u306a\u3044\n // \u3088\u304f\u308f\u304b\u3089\u3093\u3051\u3069long\u306a\u3089\u5927\u4e08\u592b\u3067\u3057\u3087\u3046\n var r = INF\n while(r - l > 1) {\n val mid = (r + l) / 2\n if (test(mid)) r = mid\n else l = mid\n }\n\n if (r == INF) out.println(-1)\n else out.println(r)\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": "3967727db1225c4b6072d9f18e0dce00"} {"nl": {"description": "During the loading of the game \"Dungeons and Candies\" you are required to get descriptions of k levels from the server. Each description is a map of an n\u2009\u00d7\u2009m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as \".\" on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. When you transmit information via a network, you want to minimize traffic \u2014 the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: You can transmit the whole level A. Then you need to transmit n\u00b7m bytes via the network. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA,\u2009B\u00b7w bytes, where dA,\u2009B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA,\u2009B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic.", "input_spec": "The first line contains four integers n,\u2009m,\u2009k,\u2009w (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200910;\u00a01\u2009\u2264\u2009k,\u2009w\u2009\u2264\u20091000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot (\".\"). Please note that the case of the letters matters.", "output_spec": "In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1,\u2009y1,\u2009x2,\u2009y2,\u2009...,\u2009xk,\u2009yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them.", "sample_inputs": ["2 3 3 2\nA.A\n...\nA.a\n..C\nX.Y\n...", "1 1 4 1\nA\n.\nB\n.", "1 3 5 2\nABA\nBBB\nBBA\nBAB\nABB"], "sample_outputs": ["14\n1 0\n2 1\n3 1", "3\n1 0\n2 0\n4 2\n3 0", "11\n1 0\n3 1\n2 3\n4 2\n5 1"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell. Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. A test case consists of only one line, containing six integers $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, and $$$c_d$$$ ($$$1 \\le n, m \\le 100$$$, $$$1 \\le r_b, r_d \\le n$$$, $$$1 \\le c_b, c_d \\le m$$$)\u00a0\u2014 the sizes of the room, the initial position of the robot and the position of the dirt cell.", "output_spec": "For each test case, print an integer \u2014 the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.", "sample_inputs": ["5\n10 10 6 1 2 8\n10 10 9 9 1 1\n9 8 5 6 2 1\n6 9 2 2 5 8\n2 2 1 1 2 1"], "sample_outputs": ["7\n10\n9\n3\n0"], "notes": "NoteIn the first example, the floor has the size of $$$10\\times 10$$$. The initial position of the robot is $$$(6, 1)$$$ and the position of the dirty cell is $$$(2, 8)$$$. See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now $$$(9, 9)$$$, and the position of the dirty cell is $$$(1, 1)$$$. In this example, the robot went straight to the dirty cell and clean it. In the third example, the floor has the size $$$9 \\times 8$$$. The initial position of the robot is $$$(5, 6)$$$, and the position of the dirty cell is $$$(2, 1)$$$. In the fourth example, the floor has the size $$$6 \\times 9$$$. The initial position of the robot is $$$(2, 2)$$$ and the position of the dirty cell is $$$(5, 8)$$$. In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away. "}, "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}"}, {"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"}], "negative_code": [], "src_uid": "6f819ce1d88d5211cd475a8673edba97"} {"nl": {"description": "There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.Each colony arrangement can be expressed as a string of even length, where the $$$i$$$-th character of the string represents the type of villain in the $$$i$$$-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.Now Iron Man asks Jarvis $$$q$$$ questions. In each question, he gives Jarvis two numbers $$$x$$$ and $$$y$$$. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in $$$x$$$-th hole or $$$y$$$-th hole live in the same half and the Iron Man can destroy that colony arrangement.Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.", "input_spec": "The first line contains a string $$$s$$$ ($$$2 \\le |s| \\le 10^{5}$$$), representing the initial colony arrangement. String $$$s$$$ can have both lowercase and uppercase English letters and its length is even. The second line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^{5}$$$)\u00a0\u2014 the number of questions. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le |s|$$$, $$$x_i \\ne y_i$$$)\u00a0\u2014 the two numbers given to the Jarvis for the $$$i$$$-th question.", "output_spec": "For each question output the number of arrangements possible modulo $$$10^9+7$$$.", "sample_inputs": ["abba\n2\n1 4\n1 2", "AAaa\n2\n1 2\n1 3", "abcd\n1\n1 3"], "sample_outputs": ["2\n0", "2\n0", "8"], "notes": "NoteConsider the first example. For the first question, the possible arrangements are \"aabb\" and \"bbaa\", and for the second question, index $$$1$$$ contains 'a' and index $$$2$$$ contains 'b' and there is no valid arrangement in which all 'a' and 'b' are in the same half."}, "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 val CtoI = Array.fill[Int](128)(-1)\n REP(26) { i =>\n CtoI('a' + i) = i\n CtoI('A' + i) = 26 + i\n }\n\n def solve(): Unit = {\n val S = ns()\n val N = S.length\n\n val NN = 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 val F = Array.ofDim[Long](NN + 1)\n F(0) = 1\n REP(NN) { i =>\n F(i + 1) = F(i) * (i + 1) % MOD\n }\n val I = Array.ofDim[Long](F.length)\n I(NN) = powMod(F(NN).toInt, MOD - 2, MOD)\n\n // x! = x(x-1)!\n // x!I(x!) \u2261 (x-1)!I((x-1)!)\n // I((x-1)!) \u2261 I(x!) * x MOD\u304c\u3067\u304b\u3044\u306e\u3067(x-1)!\u306fMOD\u3068\u7d20\n REP_r(NN) { i =>\n I(i) = I(i + 1) * (i + 1) % MOD\n }\n\n val C = Array.ofDim[Int](52)\n REP(N) { i =>\n C(CtoI(S(i))) += 1\n }\n// debug(C)\n\n var ALL = F(N / 2) * F(N / 2) % MOD\n REP(52) { i =>\n ALL = ALL * I(C(i)) % MOD\n }\n// debug(s\"ALL $ALL\")\n\n val dp = Array.ofDim[Int](N + 1)\n dp(0) = 1\n REP(52) { i =>\n val num = C(i)\n if (num > 0) {\n REP_r(N + 1) { j =>\n if (j - num >= 0) {\n dp(j) += dp(j - num)\n if (dp(j) >= MOD) dp(j) -= MOD\n }\n }\n }\n }\n\n// debug(\"DP\")\n// debug(dp)\n\n def reverse(i: Int, work: Array[Int]): Unit = {\n val num = C(i)\n REP(N + 1) { i =>\n if (i - num >= 0) {\n work(i) += MOD - work(i - num)\n if (work(i) >= MOD) work(i) -= MOD\n }\n }\n\n // debug(s\"reverseDP\")\n // debug(work)\n }\n\n val calced = Array.ofDim[Long](52, 52)\n REP(52) { i =>\n val revI = dp.clone()\n reverse(i, revI)\n calced(i)(i) = revI(N / 2)\n\n val revJ = revI.clone()\n i + 1 until 52 foreach { j =>\n // i < j\n\n Array.copy(revI, 0, revJ, 0, N + 1)\n reverse(j, revJ)\n calced(i)(j) = revJ(N / 2)\n }\n }\n\n REP(ni()) { _ =>\n val x, y = ni() - 1\n val (p1, p2) = (CtoI(S(x)), CtoI(S(y)))\n val i = min(p1, p2)\n val j = max(p1, p2)\n val ans = ALL * calced(i)(j) % MOD * 2 % MOD\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 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": "da11e843698b3ad997e12be2dbd0b71f"} {"nl": {"description": "Wherever the destination is, whoever we meet, let's render this song together.On a Cartesian coordinate plane lies a rectangular stage of size w\u2009\u00d7\u2009h, represented by a rectangle with corners (0,\u20090), (w,\u20090), (w,\u2009h) and (0,\u2009h). It can be seen that no collisions will happen before one enters the stage.On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: Vertical: stands at (xi,\u20090), moves in positive y direction (upwards); Horizontal: stands at (0,\u2009yi), moves in positive x direction (rightwards). According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.", "input_spec": "The first line of input contains three space-separated positive integers n, w and h (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 2\u2009\u2264\u2009w,\u2009h\u2009\u2264\u2009100\u2009000) \u2014 the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1\u2009\u2264\u2009gi\u2009\u2264\u20092, 1\u2009\u2264\u2009pi\u2009\u2264\u200999\u2009999, 0\u2009\u2264\u2009ti\u2009\u2264\u2009100\u2009000), describing a dancer's group gi (gi\u2009=\u20091 \u2014 vertical, gi\u2009=\u20092 \u2014 horizontal), position, and waiting time. If gi\u2009=\u20091 then pi\u2009=\u2009xi; otherwise pi\u2009=\u2009yi. It's guaranteed that 1\u2009\u2264\u2009xi\u2009\u2264\u2009w\u2009-\u20091 and 1\u2009\u2264\u2009yi\u2009\u2264\u2009h\u2009-\u20091. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.", "output_spec": "Output n lines, the i-th of which contains two space-separated integers (xi,\u2009yi) \u2014 the stopping position of the i-th dancer in the input.", "sample_inputs": ["8 10 8\n1 1 10\n1 4 13\n1 7 1\n1 8 2\n2 2 0\n2 5 14\n2 6 0\n2 6 1", "3 2 3\n1 1 2\n2 1 1\n1 1 5"], "sample_outputs": ["4 8\n10 5\n8 8\n10 6\n10 2\n1 8\n7 8\n10 6", "1 3\n2 1\n1 3"], "notes": "NoteThe first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. In the second example, no dancers collide."}, "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 case class Dancer(id: Int, g: Int, p: Int, t: Int) {\n def diag: Int = p - t\n def ord1: Int = if (g == 2) -p else p\n def ord2: Int = if (g == 1) p else 1000000 - p\n }\n\n val Array(n, w, h) = readInts(3)\n val dancers = Array.tabulate(n) { id =>\n val Array(g, p, t) = readInts(3)\n Dancer(id, g, p, t)\n }\n\n val resX, resY = Array.ofDim[Int](n)\n\n for {\n group <- dancers.groupBy(_.diag).valuesIterator\n sorted1 = group.sortBy(_.ord1)\n sorted2 = group.sortBy(_.ord2)\n i <- sorted1.indices\n } {\n val id = sorted1(i).id\n if (sorted2(i).g == 1) {\n resX(id) = sorted2(i).p\n resY(id) = h\n } else {\n resX(id) = w\n resY(id) = sorted2(i).p\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (i <- 0 until n) {\n println(resX(i) + \" \" + resY(i))\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\n case class Dancer(id: Int, g: Int, p: Int, t: Int) {\n def diag: Int = p - t\n def ord1: Int = if (g == 2) -p else p\n def ord2: Int = if (g == 1) p else 1000000 + p\n }\n\n val Array(n, w, h) = readInts(3)\n val dancers = Array.tabulate(n) { id =>\n val Array(g, p, t) = readInts(3)\n Dancer(id, g, p, t)\n }\n\n val resX, resY = Array.ofDim[Int](n)\n\n for {\n group <- dancers.groupBy(_.diag).valuesIterator\n sorted1 = group.sortBy(_.ord1)\n sorted2 = group.sortBy(_.ord2)\n i <- sorted1.indices\n } {\n val id = sorted1(i).id\n if (sorted2(i).g == 1) {\n resX(id) = sorted2(i).p\n resY(id) = h\n } else {\n resX(id) = w\n resY(id) = sorted2(i).p\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n for (i <- 0 until n) {\n println(resX(i) + \" \" + resY(i))\n }\n\n Console.flush\n}\n"}], "src_uid": "8f64c179a883047bf66ee14994364580"} {"nl": {"description": "Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.\u00a0The dragon has a hit point of $$$x$$$ initially. When its hit point goes to $$$0$$$ or under $$$0$$$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells. Void Absorption Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will become $$$\\left\\lfloor \\frac{h}{2} \\right\\rfloor + 10$$$. Here $$$\\left\\lfloor \\frac{h}{2} \\right\\rfloor$$$ denotes $$$h$$$ divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by $$$10$$$. Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will be lowered to $$$h-10$$$.Due to some reasons Kana can only cast no more than $$$n$$$ Void Absorptions and $$$m$$$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u00a0\u2014 the number of test cases. The next $$$t$$$ lines describe test cases. For each test case the only line contains three integers $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\\le x \\le 10^5$$$, $$$0\\le n,m\\le30$$$) \u00a0\u2014 the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.", "output_spec": "If it is possible to defeat the dragon, print \"YES\" (without quotes). Otherwise, print \"NO\" (without quotes). You can print each letter in any case (upper or lower).", "sample_inputs": ["7\n100 3 4\n189 3 4\n64 2 3\n63 2 3\n30 27 7\n10 9 1\n69117 21 2"], "sample_outputs": ["YES\nNO\nNO\nYES\nYES\nYES\nYES"], "notes": "NoteOne possible casting sequence of the first test case is shown below: Void Absorption $$$\\left\\lfloor \\frac{100}{2} \\right\\rfloor + 10=60$$$. Lightning Strike $$$60-10=50$$$. Void Absorption $$$\\left\\lfloor \\frac{50}{2} \\right\\rfloor + 10=35$$$. Void Absorption $$$\\left\\lfloor \\frac{35}{2} \\right\\rfloor + 10=27$$$. Lightning Strike $$$27-10=17$$$. Lightning Strike $$$17-10=7$$$. Lightning Strike $$$7-10=-3$$$."}, "positive_code": [{"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 var x = input(0)\n var n = input(1)\n val m = input(2)\n while (n > 0 && x > 18) {\n x = (x / 2) + 10\n n -= 1\n }\n if (x - 10 * m > 0) {\n println(\"NO\")\n } else {\n println(\"YES\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "78f25e2bc4ff22dbac94f72af68a745f"} {"nl": {"description": "Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The next n lines contain pairs of integers. The i-th line contains integers ci,\u2009ti (1\u2009\u2264\u2009ci,\u2009ti\u2009\u2264\u2009109) \u2014 the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1,\u2009v2,\u2009...,\u2009vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi\u2009<\u2009vi\u2009+\u20091 (i\u2009<\u2009m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.", "output_spec": "Print m integers \u2014 the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.", "sample_inputs": ["1 2\n2 8\n1 16", "4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9"], "sample_outputs": ["1\n1", "1\n1\n2\n2\n3\n4\n4\n4\n4"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "c4398a9f342a23baf1d7ebc9f4e9577d"} {"nl": {"description": "Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows: $$$a_1 = -1$$$ $$$a_2 = 2$$$ $$$a_3 = -3$$$ $$$a_4 = 4$$$ $$$a_5 = -5$$$ And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \\cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you\u00a0\u2014 the best programmer.Help her find the answers!", "input_spec": "The first line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^3$$$)\u00a0\u2014 the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 10^9$$$)\u00a0\u2014 the descriptions of the queries.", "output_spec": "Print $$$q$$$ lines, each containing one number\u00a0\u2014 the answer to the query. ", "sample_inputs": ["5\n1 3\n2 5\n5 5\n4 4\n2 3"], "sample_outputs": ["-2\n-2\n-5\n4\n-1"], "notes": "NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$."}, "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\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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Sherlock Holmes and Dr. Watson played some game on a checkered board n\u2009\u00d7\u2009n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8\u2009+\u20093\u2009+\u20096\u2009+\u20097\u2009=\u200924, sum of its row numbers equals 9\u2009+\u20095\u2009+\u20093\u2009+\u20092\u2009=\u200919, and 24\u2009>\u200919.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u200930). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.", "output_spec": "Print the single number \u2014 the number of the winning squares.", "sample_inputs": ["1\n1", "2\n1 2\n3 4", "4\n5 7 8 4\n9 5 3 2\n1 6 6 4\n9 5 7 3"], "sample_outputs": ["0", "2", "6"], "notes": "NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3"}, "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 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}"}, {"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"} {"nl": {"description": "There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob \u2014 from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob \u2014 from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate \u2014 that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then: move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$. move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$. move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$. move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$. move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$. move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers: $$$a$$$ \u2014 the total size of all sweets eaten by Alice during the game; $$$b$$$ \u2014 the total size of all sweets eaten by Bob during the game. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u2014 the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$) \u2014 the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each set of input data print three integers \u2014 the number of moves in the game and the required values $$$a$$$ and $$$b$$$.", "sample_inputs": ["7\n11\n3 1 4 1 5 9 2 6 5 3 5\n1\n1000\n3\n1 1 1\n13\n1 2 3 4 5 6 7 8 9 10 11 12 13\n2\n2 1\n6\n1 1 1 1 1 1\n7\n1 1 1 1 1 1 1"], "sample_outputs": ["6 23 21\n1 1000 0\n2 1 2\n6 45 46\n2 2 1\n3 4 2\n4 4 3"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "d70ee6d3574e0f2cac3c683729e2979d"} {"nl": {"description": "Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0,\u20090) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0,\u20090) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a,\u20090). We also know that the length of the marathon race equals nd\u2009+\u20090.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d,\u20092\u00b7d,\u2009...,\u2009n\u00b7d meters.", "input_spec": "The first line contains two space-separated real numbers a and d (1\u2009\u2264\u2009a,\u2009d\u2009\u2264\u2009105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) showing that Valera needs an extra drink n times.", "output_spec": "Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi,\u2009yi) after he covers i\u00b7d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20094. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.", "sample_inputs": ["2 5\n2", "4.147 2.8819\n6"], "sample_outputs": ["1.0000000000 2.0000000000\n2.0000000000 0.0000000000", "2.8819000000 0.0000000000\n4.1470000000 1.6168000000\n3.7953000000 4.1470000000\n0.9134000000 4.1470000000\n0.0000000000 2.1785000000\n0.7034000000 0.0000000000"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App{\n val in = scala.io.Source.stdin.getLines()\n val Array(a, d) = in.next().split(\" \").map(_.toDouble)\n val n = in.next().toInt\n// val distance = n * d + 0.5\n var count = 1\n val res: Array[String] = Array.ofDim(n)\n while (count <= n) {\n val distance = count * d\n val side = Math.floor(distance / a).toLong % 4\n val rel_distance = distance - Math.floor(distance / a).toLong * a\n val y = if (side < 1)\n 0\n else if (side < 2)\n rel_distance\n else if (side < 3)\n a\n else a - rel_distance\n val x =\n if (side < 1)\n rel_distance\n else if (side < 2)\n a\n else if (side < 3)\n a - rel_distance\n else\n 0\n res(count - 1) = s\"$x $y\"\n count += 1\n }\n println(res.mkString(\"\\n\"))\n\n}\n"}], "negative_code": [], "src_uid": "d00b8423c3c52b19fec25bc63e4d4c1c"} {"nl": {"description": "The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as \"11...11000..000\". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise \"and\" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise \"and\" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.", "input_spec": "The first line contains two integers, n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.", "output_spec": "In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.", "sample_inputs": ["5 3\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3", "5 2\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3", "2 1\n255.0.0.1\n0.0.0.2"], "sample_outputs": ["255.255.254.0", "255.255.0.0", "-1"], "notes": null}, "positive_code": [{"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}"}, {"source_code": "/*\nC. \u041c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n4 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0412 \u0437\u0430\u0434\u0430\u0447\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0443\u043f\u0440\u043e\u0449\u0435\u043d\u043d\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c \u0430\u0434\u0440\u0435\u0441\u043e\u0432 \u0432 TCP/IP, \u0432\u043d\u0438\u043c\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u0440\u043e\u0447\u0442\u0438\u0442\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u0435.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0443\u0441\u0442\u0440\u043e\u0438\u043b\u0441\u044f \u043d\u0430 \u0440\u0430\u0431\u043e\u0442\u0443 \u0441\u0438\u0441\u0442\u0435\u043c\u043d\u044b\u043c \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440\u043e\u043c. \u041a\u0430\u043a-\u0442\u043e \u0440\u0430\u0437 \u043a \u043d\u0435\u043c\u0443 \u0432 \u0440\u0443\u043a\u0438 \u043f\u043e\u043f\u0430\u043b\u0438 n IP-\u0430\u0434\u0440\u0435\u0441\u043e\u0432. \u041a\u0430\u0436\u0434\u044b\u0439 IP-\u0430\u0434\u0440\u0435\u0441 \u2014 \u044d\u0442\u043e 32-\u0431\u0438\u0442\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u043e\u0435 \u0432 \u0432\u0438\u0434\u0435 \u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0434\u0435\u0441\u044f\u0442\u0438\u0447\u043d\u044b\u0445 8-\u0431\u0438\u0442\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b (\u0431\u0435\u0437 \u043b\u0438\u0434\u0438\u0440\u0443\u044e\u0449\u0438\u0445 \u043d\u0443\u043b\u0435\u0439), \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043d\u044b\u0445 \u0447\u0435\u0440\u0435\u0437 \u0442\u043e\u0447\u043a\u0443. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0437\u0430\u043f\u0438\u0441\u044c 0.255.1.123 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b\u0439 IP-\u0430\u0434\u0440\u0435\u0441, \u0430 \u0437\u0430\u043f\u0438\u0441\u0438 0.256.1.123 \u0438 0.255.1.01 \u2014 \u043d\u0435\u0442. \u0412 \u0434\u0430\u043d\u043d\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u043b\u044c\u043d\u0430\u044f \u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0430 8-\u0431\u0438\u0442\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b\u043c IP-\u0430\u0434\u0440\u0435\u0441\u043e\u043c.\n\n\u041f\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0432 \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440\u043e\u043c, \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0443\u0437\u043d\u0430\u043b, \u0447\u0442\u043e, \u0437\u043d\u0430\u044f IP-\u0430\u0434\u0440\u0435\u0441, \u043c\u043e\u0436\u043d\u043e, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u043c\u0430\u0441\u043a\u0443 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0430\u0434\u0440\u0435\u0441 \u0441\u0435\u0442\u0438, \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 \u044d\u0442\u043e\u0442 IP-\u0430\u0434\u0440\u0435\u0441.\n\n\u041c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 \u2014 \u044d\u0442\u043e IP-\u0430\u0434\u0440\u0435\u0441, \u043e\u0431\u043b\u0430\u0434\u0430\u044e\u0449\u0438\u0439 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e\u043c: \u0435\u0441\u043b\u0438 \u0437\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u044d\u0442\u043e\u0442 IP-\u0430\u0434\u0440\u0435\u0441, \u043a\u0430\u043a 32-\u0431\u0438\u0442\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443, \u0442\u043e \u043e\u043d \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u043c \u0432 \u0432\u0438\u0434\u0435 \u00ab11...11000..000\u00bb. \u0414\u0440\u0443\u0433\u0438\u043c\u0438 \u0441\u043b\u043e\u0432\u0430\u043c\u0438, \u0432 \u043c\u0430\u0441\u043a\u0435 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 \u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0438\u0434\u0435\u0442 \u043e\u0434\u0438\u043d \u0438\u043b\u0438 \u0431\u043e\u043b\u0435\u0435 \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u044b\u0439 \u0431\u0438\u0442, \u0430 \u0437\u0430\u0442\u0435\u043c \u043e\u0434\u0438\u043d \u0438\u043b\u0438 \u0431\u043e\u043b\u0435\u0435 \u043d\u0443\u043b\u0435\u0432\u043e\u0439 \u0431\u0438\u0442 (\u0432\u0441\u0435\u0433\u043e \u0431\u0438\u0442\u043e\u0432 32). \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, IP-\u0430\u0434\u0440\u0435\u0441 2.0.0.0 \u043d\u0435 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0439 \u043c\u0430\u0441\u043a\u043e\u0439 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u0442\u0430\u043a \u043a\u0430\u043a \u0435\u0433\u043e 32-\u0431\u0438\u0442\u043d\u0430\u044f \u0437\u0430\u043f\u0438\u0441\u044c \u0438\u043c\u0435\u0435\u0442 \u0432\u0438\u0434 00000010000000000000000000000000.\n\n\u0414\u043b\u044f \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u044f \u0430\u0434\u0440\u0435\u0441\u0430 \u0441\u0435\u0442\u0438 IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u043d\u0443\u0436\u043d\u043e \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e \u043f\u043e\u0431\u0438\u0442\u043e\u0432\u043e\u0433\u043e \u00ab\u0438\u00bb (\u00aband\u00bb) IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u0438 \u043c\u0430\u0441\u043a\u0438 \u043f\u043e\u0434\u0441\u0435\u0442\u0438. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0435\u0441\u043b\u0438 \u043c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 255.192.0.0, \u0430 IP-\u0430\u0434\u0440\u0435\u0441 192.168.1.2, \u0442\u043e \u0430\u0434\u0440\u0435\u0441 \u0441\u0435\u0442\u0438 \u0440\u0430\u0432\u0435\u043d 192.128.0.0. \u041f\u0440\u0438 \u043f\u043e\u0431\u0438\u0442\u043e\u0432\u043e\u043c \u00ab\u0438\u00bb \u0432 \u0437\u0430\u043f\u0438\u0441\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430 \u0431\u0438\u0442 \u0440\u0430\u0432\u0435\u043d 1 \u0442\u043e\u0433\u0434\u0430 \u0438 \u0442\u043e\u043b\u044c\u043a\u043e \u0442\u043e\u0433\u0434\u0430, \u043a\u043e\u0433\u0434\u0430 \u0443 \u043e\u0431\u043e\u0438\u0445 \u043e\u043f\u0435\u0440\u0430\u043d\u0434\u043e\u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0431\u0438\u0442\u044b \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u044b\u0435.\n\n\u0422\u0435\u043f\u0435\u0440\u044c \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0445\u043e\u0447\u0435\u0442 \u043d\u0430\u0439\u0442\u0438 \u0432\u0441\u0435 \u0441\u0435\u0442\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442 \u0435\u0433\u043e IP-\u0430\u0434\u0440\u0435\u0441\u0430. \u041a \u0441\u043e\u0436\u0430\u043b\u0435\u043d\u0438\u044e, \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u043f\u043e\u0442\u0435\u0440\u044f\u043b \u043c\u0430\u0441\u043a\u0443 \u043f\u043e\u0434\u0441\u0435\u0442\u0438. \u041a \u0441\u0447\u0430\u0441\u0442\u044c\u044e, \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u0430\u043f\u043e\u043c\u043d\u0438\u043b, \u0447\u0442\u043e \u0435\u0433\u043e IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u043b\u0438 \u0440\u043e\u0432\u043d\u043e k \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u043c \u0441\u0435\u0442\u044f\u043c. \u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u043d\u0430\u0439\u0442\u0438 \u043c\u0430\u0441\u043a\u0443 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u0442\u0430\u043a\u0443\u044e, \u0447\u0442\u043e \u0435\u0433\u043e IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u0431\u0443\u0434\u0443\u0442 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442\u044c \u0440\u043e\u0432\u043d\u043e k \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u043c \u0441\u0435\u0442\u044f\u043c. \u0415\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445 \u043c\u0430\u0441\u043e\u043a \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e, \u043d\u0430\u0439\u0434\u0438\u0442\u0435 \u0442\u0443, \u0432 \u0431\u0438\u0442\u043e\u0432\u043e\u0439 \u0437\u0430\u043f\u0438\u0441\u0438 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0430\u0438\u043c\u0435\u043d\u044c\u0448\u0435\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0435\u0434\u0438\u043d\u0438\u0446. \u0415\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445 \u043c\u0430\u0441\u043e\u043a \u043d\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442, \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u0435 \u043e\u0431 \u044d\u0442\u043e\u043c.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e IP-\u0430\u0434\u0440\u0435\u0441\u043e\u0432 \u0438 \u0441\u0435\u0442\u0435\u0439. \u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 n \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0441\u0430\u043c\u0438 IP-\u0430\u0434\u0440\u0435\u0441\u0430. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 IP-\u0430\u0434\u0440\u0435\u0441 \u043c\u0430\u0441\u043a\u0438 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u043e\u043c \u0432 \u0443\u0441\u043b\u043e\u0432\u0438\u0438, \u0435\u0441\u043b\u0438 \u0442\u0440\u0435\u0431\u0443\u0435\u043c\u0430\u044f \u043c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442. \u0418\u043d\u0430\u0447\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 -1.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n255.255.254.0\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n255.255.0.0\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2 1\n255.0.0.1\n0.0.0.2\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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}"}, {"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"}], "negative_code": [{"source_code": "/*\nC. \u041c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n4 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0412 \u0437\u0430\u0434\u0430\u0447\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0443\u043f\u0440\u043e\u0449\u0435\u043d\u043d\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c \u0430\u0434\u0440\u0435\u0441\u043e\u0432 \u0432 TCP/IP, \u0432\u043d\u0438\u043c\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u0440\u043e\u0447\u0442\u0438\u0442\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u0435.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0443\u0441\u0442\u0440\u043e\u0438\u043b\u0441\u044f \u043d\u0430 \u0440\u0430\u0431\u043e\u0442\u0443 \u0441\u0438\u0441\u0442\u0435\u043c\u043d\u044b\u043c \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440\u043e\u043c. \u041a\u0430\u043a-\u0442\u043e \u0440\u0430\u0437 \u043a \u043d\u0435\u043c\u0443 \u0432 \u0440\u0443\u043a\u0438 \u043f\u043e\u043f\u0430\u043b\u0438 n IP-\u0430\u0434\u0440\u0435\u0441\u043e\u0432. \u041a\u0430\u0436\u0434\u044b\u0439 IP-\u0430\u0434\u0440\u0435\u0441 \u2014 \u044d\u0442\u043e 32-\u0431\u0438\u0442\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u043e\u0435 \u0432 \u0432\u0438\u0434\u0435 \u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0434\u0435\u0441\u044f\u0442\u0438\u0447\u043d\u044b\u0445 8-\u0431\u0438\u0442\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b (\u0431\u0435\u0437 \u043b\u0438\u0434\u0438\u0440\u0443\u044e\u0449\u0438\u0445 \u043d\u0443\u043b\u0435\u0439), \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043d\u044b\u0445 \u0447\u0435\u0440\u0435\u0437 \u0442\u043e\u0447\u043a\u0443. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0437\u0430\u043f\u0438\u0441\u044c 0.255.1.123 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b\u0439 IP-\u0430\u0434\u0440\u0435\u0441, \u0430 \u0437\u0430\u043f\u0438\u0441\u0438 0.256.1.123 \u0438 0.255.1.01 \u2014 \u043d\u0435\u0442. \u0412 \u0434\u0430\u043d\u043d\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u043b\u044c\u043d\u0430\u044f \u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0430 8-\u0431\u0438\u0442\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b\u043c IP-\u0430\u0434\u0440\u0435\u0441\u043e\u043c.\n\n\u041f\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0432 \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440\u043e\u043c, \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0443\u0437\u043d\u0430\u043b, \u0447\u0442\u043e, \u0437\u043d\u0430\u044f IP-\u0430\u0434\u0440\u0435\u0441, \u043c\u043e\u0436\u043d\u043e, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u043c\u0430\u0441\u043a\u0443 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0430\u0434\u0440\u0435\u0441 \u0441\u0435\u0442\u0438, \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 \u044d\u0442\u043e\u0442 IP-\u0430\u0434\u0440\u0435\u0441.\n\n\u041c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 \u2014 \u044d\u0442\u043e IP-\u0430\u0434\u0440\u0435\u0441, \u043e\u0431\u043b\u0430\u0434\u0430\u044e\u0449\u0438\u0439 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e\u043c: \u0435\u0441\u043b\u0438 \u0437\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u044d\u0442\u043e\u0442 IP-\u0430\u0434\u0440\u0435\u0441, \u043a\u0430\u043a 32-\u0431\u0438\u0442\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443, \u0442\u043e \u043e\u043d \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u043c \u0432 \u0432\u0438\u0434\u0435 \u00ab11...11000..000\u00bb. \u0414\u0440\u0443\u0433\u0438\u043c\u0438 \u0441\u043b\u043e\u0432\u0430\u043c\u0438, \u0432 \u043c\u0430\u0441\u043a\u0435 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 \u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0438\u0434\u0435\u0442 \u043e\u0434\u0438\u043d \u0438\u043b\u0438 \u0431\u043e\u043b\u0435\u0435 \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u044b\u0439 \u0431\u0438\u0442, \u0430 \u0437\u0430\u0442\u0435\u043c \u043e\u0434\u0438\u043d \u0438\u043b\u0438 \u0431\u043e\u043b\u0435\u0435 \u043d\u0443\u043b\u0435\u0432\u043e\u0439 \u0431\u0438\u0442 (\u0432\u0441\u0435\u0433\u043e \u0431\u0438\u0442\u043e\u0432 32). \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, IP-\u0430\u0434\u0440\u0435\u0441 2.0.0.0 \u043d\u0435 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0439 \u043c\u0430\u0441\u043a\u043e\u0439 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u0442\u0430\u043a \u043a\u0430\u043a \u0435\u0433\u043e 32-\u0431\u0438\u0442\u043d\u0430\u044f \u0437\u0430\u043f\u0438\u0441\u044c \u0438\u043c\u0435\u0435\u0442 \u0432\u0438\u0434 00000010000000000000000000000000.\n\n\u0414\u043b\u044f \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u044f \u0430\u0434\u0440\u0435\u0441\u0430 \u0441\u0435\u0442\u0438 IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u043d\u0443\u0436\u043d\u043e \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e \u043f\u043e\u0431\u0438\u0442\u043e\u0432\u043e\u0433\u043e \u00ab\u0438\u00bb (\u00aband\u00bb) IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u0438 \u043c\u0430\u0441\u043a\u0438 \u043f\u043e\u0434\u0441\u0435\u0442\u0438. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0435\u0441\u043b\u0438 \u043c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 255.192.0.0, \u0430 IP-\u0430\u0434\u0440\u0435\u0441 192.168.1.2, \u0442\u043e \u0430\u0434\u0440\u0435\u0441 \u0441\u0435\u0442\u0438 \u0440\u0430\u0432\u0435\u043d 192.128.0.0. \u041f\u0440\u0438 \u043f\u043e\u0431\u0438\u0442\u043e\u0432\u043e\u043c \u00ab\u0438\u00bb \u0432 \u0437\u0430\u043f\u0438\u0441\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430 \u0431\u0438\u0442 \u0440\u0430\u0432\u0435\u043d 1 \u0442\u043e\u0433\u0434\u0430 \u0438 \u0442\u043e\u043b\u044c\u043a\u043e \u0442\u043e\u0433\u0434\u0430, \u043a\u043e\u0433\u0434\u0430 \u0443 \u043e\u0431\u043e\u0438\u0445 \u043e\u043f\u0435\u0440\u0430\u043d\u0434\u043e\u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0431\u0438\u0442\u044b \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u044b\u0435.\n\n\u0422\u0435\u043f\u0435\u0440\u044c \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0445\u043e\u0447\u0435\u0442 \u043d\u0430\u0439\u0442\u0438 \u0432\u0441\u0435 \u0441\u0435\u0442\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442 \u0435\u0433\u043e IP-\u0430\u0434\u0440\u0435\u0441\u0430. \u041a \u0441\u043e\u0436\u0430\u043b\u0435\u043d\u0438\u044e, \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u043f\u043e\u0442\u0435\u0440\u044f\u043b \u043c\u0430\u0441\u043a\u0443 \u043f\u043e\u0434\u0441\u0435\u0442\u0438. \u041a \u0441\u0447\u0430\u0441\u0442\u044c\u044e, \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u0430\u043f\u043e\u043c\u043d\u0438\u043b, \u0447\u0442\u043e \u0435\u0433\u043e IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u043b\u0438 \u0440\u043e\u0432\u043d\u043e k \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u043c \u0441\u0435\u0442\u044f\u043c. \u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u043d\u0430\u0439\u0442\u0438 \u043c\u0430\u0441\u043a\u0443 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u0442\u0430\u043a\u0443\u044e, \u0447\u0442\u043e \u0435\u0433\u043e IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u0431\u0443\u0434\u0443\u0442 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442\u044c \u0440\u043e\u0432\u043d\u043e k \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u043c \u0441\u0435\u0442\u044f\u043c. \u0415\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445 \u043c\u0430\u0441\u043e\u043a \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e, \u043d\u0430\u0439\u0434\u0438\u0442\u0435 \u0442\u0443, \u0432 \u0431\u0438\u0442\u043e\u0432\u043e\u0439 \u0437\u0430\u043f\u0438\u0441\u0438 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0430\u0438\u043c\u0435\u043d\u044c\u0448\u0435\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0435\u0434\u0438\u043d\u0438\u0446. \u0415\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445 \u043c\u0430\u0441\u043e\u043a \u043d\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442, \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u0435 \u043e\u0431 \u044d\u0442\u043e\u043c.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e IP-\u0430\u0434\u0440\u0435\u0441\u043e\u0432 \u0438 \u0441\u0435\u0442\u0435\u0439. \u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 n \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0441\u0430\u043c\u0438 IP-\u0430\u0434\u0440\u0435\u0441\u0430. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 IP-\u0430\u0434\u0440\u0435\u0441\u0430 \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 IP-\u0430\u0434\u0440\u0435\u0441 \u043c\u0430\u0441\u043a\u0438 \u043f\u043e\u0434\u0441\u0435\u0442\u0438, \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u043e\u043c \u0432 \u0443\u0441\u043b\u043e\u0432\u0438\u0438, \u0435\u0441\u043b\u0438 \u0442\u0440\u0435\u0431\u0443\u0435\u043c\u0430\u044f \u043c\u0430\u0441\u043a\u0430 \u043f\u043e\u0434\u0441\u0435\u0442\u0438 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442. \u0418\u043d\u0430\u0447\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 -1.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n255.255.254.0\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n255.255.0.0\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2 1\n255.0.0.1\n0.0.0.2\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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"} {"nl": {"description": "Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he \"see an elephant\"? He can \"see an elephant\" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).Your task is to count the number of segments where Horace can \"see an elephant\".", "input_spec": "The first line contains two integers n and w (1\u2009\u2264\u2009n,\u2009w\u2009\u2264\u20092\u00b7105) \u2014 the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the heights of the towers in the bears' wall. The third line contains w integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u2009109) \u2014 the heights of the towers in the elephant's wall.", "output_spec": "Print the number of segments in the bears' wall where Horace can \"see an elephant\".", "sample_inputs": ["13 5\n2 4 5 5 4 3 2 2 2 3 3 2 1\n3 4 4 3 2"], "sample_outputs": ["2"], "notes": "NoteThe picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can \"see an elephant\" are in gray. "}, "positive_code": [{"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}"}, {"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 \u03c0 = new Array[Int](string.length)\n \u03c0(0) = 0\n for (i <- 1 to string.length - 1) {\n var j = \u03c0(i - 1)\n while (j != 0 && string(j) != string(i)) {\n j = \u03c0(j - 1)\n }\n if (string(j) == string(i)) {\n \u03c0(i) = j + 1\n } else {\n \u03c0(i) = 0\n }\n }\n \u03c0\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 \u03c0 = new Array[Int](string.length)\n \u03c0(0) = 0\n for (i <- 1 to string.length - 1) {\n var j = \u03c0(i - 1)\n while (j != 0 && string(j) != string(i)) {\n j = \u03c0(j - 1)\n }\n if (string(j) == string(i)) {\n \u03c0(i) = j + 1\n } else {\n \u03c0(i) = 0\n }\n }\n \u03c0\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"} {"nl": {"description": "Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array $$$a$$$ of $$$n$$$ integers. You are also given an integer $$$k$$$. Lord Omkar wants you to do $$$k$$$ operations with this array.Define one operation as the following: Set $$$d$$$ to be the maximum value of your array. For every $$$i$$$ from $$$1$$$ to $$$n$$$, replace $$$a_{i}$$$ with $$$d-a_{i}$$$. The goal is to predict the contents in the array after $$$k$$$ operations. Please help Ray determine what the final sequence will look like!", "input_spec": "Each test contains multiple test cases. The first line contains the number of cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5, 1 \\leq k \\leq 10^{18}$$$) \u2013 the length of your array and the number of operations to perform. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \\leq a_{i} \\leq 10^9)$$$ \u2013 the initial contents of your array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each case, print the final version of array $$$a$$$ after $$$k$$$ operations described above.", "sample_inputs": ["3\n2 1\n-199 192\n5 19\n5 -1 4 2 0\n1 2\n69"], "sample_outputs": ["391 0\n0 6 1 3 5\n0"], "notes": "NoteIn the first test case the array changes as follows:Initially, the array is $$$[-199, 192]$$$. $$$d = 192$$$.After the operation, the array becomes $$$[d-(-199), d-192] = [391, 0]$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which\u00a0\u2014 in the second?", "input_spec": "The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \\leq a, b \\leq 10^{9}$$$)\u00a0\u2014 the number of hours Lesha has today and the number of hours Lesha has tomorrow.", "output_spec": "In the first line print a single integer $$$n$$$ ($$$0 \\leq n \\leq a$$$)\u00a0\u2014 the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\leq p_i \\leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \\leq m \\leq b$$$)\u00a0\u2014 the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \\ldots, q_m$$$ ($$$1 \\leq q_i \\leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.", "sample_inputs": ["3 3", "9 12"], "sample_outputs": ["1\n3 \n2\n2 1", "2\n3 6\n4\n1 2 4 5"], "notes": "NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Positive integer $$$x$$$ is called divisor of positive integer $$$y$$$, if $$$y$$$ is divisible by $$$x$$$ without remainder. For example, $$$1$$$ is a divisor of $$$7$$$ and $$$3$$$ is not divisor of $$$8$$$.We gave you an integer $$$d$$$ and asked you to find the smallest positive integer $$$a$$$, such that $$$a$$$ has at least $$$4$$$ divisors; difference between any two divisors of $$$a$$$ is at least $$$d$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 3000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$d$$$ ($$$1 \\leq d \\leq 10000$$$).", "output_spec": "For each test case print one integer $$$a$$$\u00a0\u2014 the answer for this test case.", "sample_inputs": ["2\n1\n2"], "sample_outputs": ["6\n15"], "notes": "NoteIn the first test case, integer $$$6$$$ have following divisors: $$$[1, 2, 3, 6]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$1$$$. There is no smaller integer with at least $$$4$$$ divisors.In the second test case, integer $$$15$$$ have following divisors: $$$[1, 3, 5, 15]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$2$$$.The answer $$$12$$$ is INVALID because divisors are $$$[1, 2, 3, 4, 6, 12]$$$. And the difference between, for example, divisors $$$2$$$ and $$$3$$$ is less than $$$d=2$$$."}, "positive_code": [{"source_code": "object Hemlo {\r\n import scala.io.{StdIn => in}\r\n import scala.util.control._\r\n val C = new Array[Boolean](30005)\r\n def sieve(): Unit = {\r\n for (i <- 1 until 30005)\r\n C(i) = false\r\n for (i <- 2 until 30005) {\r\n if (C(i) == false) {\r\n for (j <- 2 * i until 30005 by i)\r\n C(j) = true\r\n }\r\n }\r\n }\r\n def cube(c: Long): Long = {\r\n c * c * c\r\n }\r\n def main(args: Array[String]): Unit = {\r\n sieve()\r\n var t: Int = in.readInt()\r\n while (t > 0) {\r\n val n: Int = in.readInt()\r\n var m1, m2: Long = -1\r\n val loop = new Breaks\r\n loop.breakable {\r\n for (i <- n + 1 until 300005) {\r\n if (C(i) == false) {\r\n if (m1 == -1) {\r\n m1 = i\r\n } else if (m2 == -1 && i - m1 >= n) {\r\n m2 = i\r\n loop.break()\r\n }\r\n }\r\n }\r\n }\r\n var ans: Long = 0\r\n if (cube(m1) <= m1 * m2)\r\n ans = cube(m1)\r\n else ans = m1 * m2\r\n println(ans)\r\n t -= 1\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object Hemlo {\r\n import scala.io.{StdIn => in}\r\n import scala.util.control._\r\n val C = new Array[Boolean](30005)\r\n def sieve(): Unit = {\r\n for (i <- 1 until 30005)\r\n C(i) = false\r\n for (i <- 2 until 30005) {\r\n if (C(i) == false) {\r\n for (j <- 2 * i until 30005 by i)\r\n C(j) = true\r\n }\r\n }\r\n }\r\n def cube(c: Int): Int = {\r\n c * c * c\r\n }\r\n def main(args: Array[String]): Unit = {\r\n sieve()\r\n var t: Int = in.readInt()\r\n while (t > 0) {\r\n val n: Int = in.readInt()\r\n var m1, m2: Int = -1\r\n val loop = new Breaks\r\n loop.breakable {\r\n for (i <- n + 1 until 300005) {\r\n if (C(i) == false) {\r\n if (m1 == -1) {\r\n m1 = i\r\n } else if (m2 == -1 && i - m1 >= n) {\r\n m2 = i\r\n loop.break()\r\n }\r\n }\r\n }\r\n }\r\n var ans: Int = 0\r\n if (cube(m1) <= m1 * m2)\r\n ans = cube(m1)\r\n else ans = m1 * m2\r\n println(ans)\r\n t -= 1\r\n }\r\n }\r\n}\r\n"}], "src_uid": "648ec67565c506c3e2ffd007ad44e8c3"} {"nl": {"description": "Arkady is playing Battleship. The rules of this game aren't really important.There is a field of $$$n \\times n$$$ cells. There should be exactly one $$$k$$$-decker on the field, i.\u00a0e. a ship that is $$$k$$$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 100$$$)\u00a0\u2014 the size of the field and the size of the ship. The next $$$n$$$ lines contain the field. Each line contains $$$n$$$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).", "output_spec": "Output two integers\u00a0\u2014 the row and the column of a cell that belongs to the maximum possible number of different locations of the ship. If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.", "sample_inputs": ["4 3\n#..#\n#.#.\n....\n.###", "10 4\n#....##...\n.#...#....\n..#..#..#.\n...#.#....\n.#..##.#..\n.....#...#\n...#.##...\n.#...#.#..\n.....#..#.\n...#.#...#", "19 6\n##..............###\n#......#####.....##\n.....#########.....\n....###########....\n...#############...\n..###############..\n.#################.\n.#################.\n.#################.\n.#################.\n#####....##....####\n####............###\n####............###\n#####...####...####\n.#####..####..#####\n...###........###..\n....###########....\n.........##........\n#.................#"], "sample_outputs": ["3 2", "6 1", "1 8"], "notes": "NoteThe picture below shows the three possible locations of the ship that contain the cell $$$(3, 2)$$$ in the first sample. "}, "positive_code": [{"source_code": "object _965B 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\n val canHasShip = io.read[Vector, String](n)\n .map(row => row.map(_ == '.'))\n\n val result = Array.ofDim[Int](n, n)\n for {\n r <- 0 until n\n c <- 0 until n\n horizontal = (0 until k).forall(i => canHasShip(r).isDefinedAt(c + i) && canHasShip(r)(c + i))\n vertical = (0 until k).forall(i => canHasShip.isDefinedAt(r + i) && canHasShip(r + i)(c))\n } {\n if (horizontal) (0 until k).foreach(i => result(r)(c + i) += 1)\n if (vertical) (0 until k).foreach(i => result(r + i)(c) += 1)\n }\n\n var maxX, maxY, maxC = -1\n\n for {\n r <- 0 until n\n c <- 0 until n\n if result(r)(c) > maxC\n } {\n maxC = result(r)(c)\n maxX = r+1\n maxY = c+1\n }\n\n io.write(s\"$maxX $maxY\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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": "6fb20914525715af737d81f3a5d98636"} {"nl": {"description": "Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills\u00a0\u2014 $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him\u00a0\u2014 write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^8$$$)\u00a0\u2014 the initial sum in rubles Andrew has. The second line of the input contains one integer $$$d$$$ ($$$30 \\leq d \\leq 100$$$)\u00a0\u2014 the price of one dollar in rubles. The third line of the input contains integer $$$e$$$ ($$$30 \\leq e \\leq 100$$$)\u00a0\u2014 the price of one euro in rubles.", "output_spec": "Output one integer\u00a0\u2014 the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.", "sample_inputs": ["100\n60\n70", "410\n55\n70", "600\n60\n70"], "sample_outputs": ["40", "5", "0"], "notes": "NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill."}, "positive_code": [{"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\n val n = readLong\n val d, e = readInt\n\n var res = n % d\n\n for (i <- 1 to 1000) {\n for (j <- 1 to 1000) {\n val x = n % (5L * i * e) % (d * j)\n val y = n % (d * j) % (5L * i * e)\n if (x < res) res = x\n if (y < res) res = y\n }\n }\n\n println(res)\n}\n"}], "negative_code": [{"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 n = readLong\n val d, e = readInt\n\n var res = n % d\n\n for (i <- 1 to 100000) {\n val x = n % (5L * i * e) % d\n if (x < res) res = x\n }\n\n println(res)\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 n = readLong\n val d, e = readInt\n\n val res = math.min(n % d, n % (5 * e) % d)\n\n println(res)\n}\n"}], "src_uid": "8c5d9b4fd297706fac3be83fc85028a0"} {"nl": {"description": "Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.", "input_spec": "You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.", "output_spec": "Print the string t. If a suitable t string does not exist, then print \"Just a legend\" without the quotes.", "sample_inputs": ["fixprefixsuffix", "abcdabc"], "sample_outputs": ["fix", "Just a legend"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of throws of the first team. Then follow n integer numbers \u2014 the distances of throws ai (1\u2009\u2264\u2009ai\u2009\u2264\u20092\u00b7109). Then follows number m (1\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of the throws of the second team. Then follow m integer numbers \u2014 the distances of throws of bi (1\u2009\u2264\u2009bi\u2009\u2264\u20092\u00b7109).", "output_spec": "Print two numbers in the format a:b \u2014 the score that is possible considering the problem conditions where the result of subtraction a\u2009-\u2009b is maximum. If there are several such scores, find the one in which number a is maximum.", "sample_inputs": ["3\n1 2 3\n2\n5 6", "5\n6 7 8 9 10\n5\n1 2 3 4 5"], "sample_outputs": ["9:6", "15:10"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.2) String a is lexicographically smaller than c.3) String c is lexicographically smaller than b.For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009...,\u2009xi\u2009-\u20091\u2009=\u2009yi\u2009-\u20091,\u2009xi\u2009<\u2009yi.Since the answer can be very large, you need to find answer modulo 109\u2009+\u20097.", "input_spec": "First line contains string a, second line contains string b. Strings a,\u2009b consist of lowercase English letters. Their lengths are equal and don't exceed 106. It is guaranteed that a is lexicographically smaller than b.", "output_spec": "Print one integer \u00a0\u2014 the number of different strings satisfying the condition of the problem modulo 109\u2009+\u20097.", "sample_inputs": ["abc\nddd", "abcdef\nabcdeg", "abacaba\nubuduba"], "sample_outputs": ["5", "0", "64"], "notes": "NoteIn first sample from string abc can be obtained strings acb,\u2009bac,\u2009bca,\u2009cab,\u2009cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0."}, "positive_code": [{"source_code": "object Main extends App {\n\n import io.StdIn.readLine\n\n val MOD = 1000000007\n\n val a = readLine().map(_ - 'a')\n val d = readLine().map(_ - 'a')\n val n = a length\n\n val fact = new Array[Integer](n+10)\n val rfact = new Array[Integer](n+10)\n\n fact(0) = 1\n for (i <- 1 to n) fact(i) = (1l*fact(i-1)*i%MOD).toInt\n rfact(n) = pow(fact(n), MOD - 2)\n for (i <- n-1 to 0 by -1) rfact(i) = 1l * rfact(i+1) * (i+1) % MOD toInt\n\n println(((f(d) - f(a) - 1)%MOD + MOD)%MOD)\n\n def f(s: IndexedSeq[Int]): Integer = {\n\n val cnt = new Array[Int](26)\n for (k <- a) cnt(k) += 1\n\n var ans = 0\n val n = s.length\n var mul = fact(n)\n for (i <- 0 until 26)\n mul = 1l * mul * rfact(cnt(i)) % MOD toInt\n\n //System.err.println(mul)\n\n for (i <- 0 to n-1) {\n\n mul = (1l * mul * rfact(n - i) % MOD).toInt\n mul = (1l * mul * fact(n - i - 1) % MOD).toInt\n\n //mul = (1l * mul * pow(n - i, MOD - 2) % MOD).toInt\n\n for (ch <- 0 until s(i)) {\n //System.err.println(mul)\n if (cnt(ch) > 0) {\n mul = (1l * mul * fact(cnt(ch)) % MOD).toInt\n mul = (1l * mul * rfact(cnt(ch)-1) % MOD).toInt\n ans = (ans + mul) % MOD\n mul = (1l * mul * fact(cnt(ch)-1) % MOD).toInt\n mul = (1l * mul * rfact(cnt(ch)) % MOD).toInt\n }\n }\n\n if (cnt(s(i)) == 0) return ans\n\n mul = (1l * mul * fact(cnt(s(i))) % MOD).toInt\n mul = (1l * mul * rfact(cnt(s(i))-1) % MOD).toInt\n cnt(s(i)) -= 1\n\n }\n\n ans\n }\n\n def pow(x: Int, n: Int): Int = n%2 match {\n case 0 if n == 0 => 1\n case 0 if n > 0 => {\n val res = pow(x, n/2)\n 1l * res * res % MOD toInt\n }\n case 1 => {\n (1l * pow(x, n-1) * x) % MOD toInt\n }\n }\n\n}"}], "negative_code": [], "src_uid": "382155ac360f44e7dec0d1170764ed45"} {"nl": {"description": "Omkar has received a message from Anton saying \"Your story for problem A is confusing. Just make a formal statement.\" Because of this, Omkar gives you an array $$$a = [a_1, a_2, \\ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \\ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\leq t \\leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$) \u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \\cdots, a_n$$$ ($$$-100 \\leq a_i \\leq 100$$$) \u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \\leq k \\leq 300$$$). Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \\cdots, b_k$$$ ($$$-10^9 \\leq b_i \\leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \\cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any. ", "sample_inputs": ["4\n3\n3 0 9\n2\n3 4\n5\n-7 3 13 -2 8\n4\n4 8 12 6"], "sample_outputs": ["yes\n4\n6 0 3 9\nyEs\n5\n5 3 1 2 4\nNO\nYes\n6\n8 12 6 2 4 10"], "notes": "NoteFor the first case, you can add integers to $$$a$$$ to receive the array $$$b = [6, 0, 3, 9]$$$. Note that $$$|6-3| = |9-6| = |3-0| = 3$$$ and $$$3$$$ is in $$$b$$$, $$$|6-0| = |9-3| = 6$$$ and $$$6$$$ is in $$$b$$$, and $$$|9-0| = 9$$$ is in $$$b$$$, so $$$b$$$ is nice.For the second case, you can add integers to $$$a$$$ to receive the array $$$b = [5, 3, 1, 2, 4]$$$. We have that $$$|2-1| = |3-2| = |4-3| = |5-4| = 1$$$ is in $$$b$$$, $$$|3-1| = |4-2| = |5-3| = 2$$$ is in $$$b$$$, $$$|4-1| = |5-2| = 3$$$ is in $$$b$$$, and $$$|5-1| = 4$$$ is in $$$b$$$, so $$$b$$$ is nice.For the fourth case, you can add integers to $$$a$$$ to receive the array $$$b = [8, 12, 6, 2, 4, 10]$$$. We have that $$$|4-2| = |6-4| = |8-6| = |10-8| = |12-10| = 2$$$ is in $$$b$$$, $$$|6-2| = |8-4| = |10-6| = |12-8| = 4$$$ is in $$$b$$$, $$$|8-2| = |10-4| = |12-6| = 6$$$ is in $$$b$$$, $$$|10-2| = |12-4| = 8$$$ is in $$$b$$$, and $$$|12-2| = 10$$$ is in $$$b$$$, so $$$b$$$ is nice.It can be proven that for all other test cases it is impossible to create a nice array $$$b$$$."}, "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 (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"}, {"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"} {"nl": {"description": "You have a string of decimal digits s. Let's define bij\u2009=\u2009si\u00b7sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i,\u2009j) that are the elements of the rectangle equals a in each rectangle.A rectangle in a matrix is a group of four integers (x,\u2009y,\u2009z,\u2009t) (x\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009t). The elements of the rectangle are all cells (i,\u2009j) such that x\u2009\u2264\u2009i\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009j\u2009\u2264\u2009t.", "input_spec": "The first line contains integer a (0\u2009\u2264\u2009a\u2009\u2264\u2009109), the second line contains a string of decimal integers s (1\u2009\u2264\u2009|s|\u2009\u2264\u20094000).", "output_spec": "Print a single integer \u2014 the answer to a problem. Please, do not write the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["10\n12345", "16\n439873893693495623498263984765"], "sample_outputs": ["6", "40"], "notes": null}, "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\u2009=\u2009si\u00b7sj. Find\n * in matrix b the number of such rectangles that the sum bij for all\n * cells (i,\u2009j) 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,\u2009y,\u2009z,\u2009t)\n * (x\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009t). The elements of the rectangle are all cells (i,\u2009j)\n * such that x\u2009\u2264\u2009i\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009j\u2009\u2264\u2009t.\n *\n * Input The first line contains integer a (0\u2009\u2264\u2009a\u2009\u2264\u2009109), the second line\n * contains a string of decimal integers s (1\u2009\u2264\u2009|s|\u2009\u2264\u20094000).\n *\n * Output Print a single integer \u2014 the answer to a problem.\n *\n * Please, do not write the %lld specifier to read or write 64-bit\n * integers in \u0421++. 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 \u2190 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 \u2190 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 \u2190 0 until prefix.length\n j \u2190 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 \u21d2 a % i == 0 && a / i < count.length)\n .map(i \u21d2 count(i) * count(a / i))\n .sum\n }\n println(res)\n }\n}"}, {"source_code": "/**\n * Contest 213, Div 2, problem C\n *\n *

You have a string of decimal digits s. Let's define bij\u2009=\u2009si\u00b7sj. Find\n * in matrix b the number of such rectangles that the sum bij for all\n * cells (i,\u2009j) 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,\u2009y,\u2009z,\u2009t)\n * (x\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009t). The elements of the rectangle are all cells (i,\u2009j)\n * such that x\u2009\u2264\u2009i\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009j\u2009\u2264\u2009t.\n *\n * Input The first line contains integer a (0\u2009\u2264\u2009a\u2009\u2264\u2009109), the second line\n * contains a string of decimal integers s (1\u2009\u2264\u2009|s|\u2009\u2264\u20094000).\n *\n * Output Print a single integer \u2014 the answer to a problem.\n *\n * Please, do not write the %lld specifier to read or write 64-bit\n * integers in \u0421++. 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 \u2190 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 \u2190 0 until prefix.length\n j \u2190 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 \u21d2 a % i == 0 && a / i < count.length)\n .map(i \u21d2 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\u2009=\u2009si\u00b7sj. Find\n * in matrix b the number of such rectangles that the sum bij for all\n * cells (i,\u2009j) 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,\u2009y,\u2009z,\u2009t)\n * (x\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009t). The elements of the rectangle are all cells (i,\u2009j)\n * such that x\u2009\u2264\u2009i\u2009\u2264\u2009y,\u2009z\u2009\u2264\u2009j\u2009\u2264\u2009t.\n *\n * Input The first line contains integer a (0\u2009\u2264\u2009a\u2009\u2264\u2009109), the second line\n * contains a string of decimal integers s (1\u2009\u2264\u2009|s|\u2009\u2264\u20094000).\n *\n * Output Print a single integer \u2014 the answer to a problem.\n *\n * Please, do not write the %lld specifier to read or write 64-bit\n * integers in \u0421++. 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 \u2190 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 \u2190 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 \u2190 0 until prefix.length\n j \u2190 i + 1 until prefix.length\n } count(prefix(j) - prefix(i)) += 1\n val res = (1 until count.length)\n .withFilter(i \u21d2 a % i == 0 && a / i < count.length)\n .map(i \u21d2 count(i) * count(a / i))\n .sum\n println(res)\n }\n}"}], "src_uid": "b429b42ba8be9df4b87b68420e9873bc"} {"nl": {"description": "Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v\u2009=\u2009|sa\u2009-\u2009sb|.In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5,\u20091,\u20093,\u20092,\u20094] and the array b is [3,\u20093,\u20092] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2,\u20091,\u20093,\u20092,\u20094] and the new array b [3,\u20093,\u20095].Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of elements in the array a. The second line contains n integers ai (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of the array a. The third line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u20092000) \u2014 the number of elements in the array b. The fourth line contains m integers bj (\u2009-\u2009109\u2009\u2264\u2009bj\u2009\u2264\u2009109) \u2014 the elements of the array b.", "output_spec": "In the first line print the minimal value v\u2009=\u2009|sa\u2009-\u2009sb| that can be got with no more than two swaps. The second line should contain the number of swaps k (0\u2009\u2264\u2009k\u2009\u2264\u20092). Each of the next k lines should contain two integers xp,\u2009yp (1\u2009\u2264\u2009xp\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009yp\u2009\u2264\u2009m) \u2014 the index of the element in the array a and the index of the element in the array b in the p-th swap. If there are several optimal solutions print any of them. Print the swaps in order the professor did them.", "sample_inputs": ["5\n5 4 3 2 1\n4\n1 1 1 1", "5\n1 2 3 4 5\n1\n15", "5\n1 2 3 4 5\n4\n1 2 3 4"], "sample_outputs": ["1\n2\n1 1\n4 2", "0\n0", "1\n1\n3 1"], "notes": null}, "positive_code": [{"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r) {\n val mid = (l + r) / 2\n if (2L * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2L * cur) < v) {\n v = Math.abs(diff - 2L * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- i+1 to n) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n\n for (i <- 1 to m) {\n for (j <- i+1 to m) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n\n val na = nb.result()\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {\n v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n\n if (v == 14520) {\n println(diff)\n println(a(37) + \" \" + a(1627))\n println(b(0) + \" \" + b(2))\n }\n\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "negative_code": [{"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r ) {\n val mid = (l + r) / 2\n if (2 * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n\n val diff: Long = a.sum - b.sum\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur: Long = a(i-1) - b(j-1)\n if (Math.abs(diff - 2 * cur) < v) {\n v = Math.abs(diff - 2 * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- 1 to n) {\n if (i != j) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n }\n\n for (i <- 1 to m) {\n for (j <- 1 to m) {\n if (i != j) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n }\n\n val na = nb.result().sortWith(_.d < _.d)\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {\n v = Math.abs(diff+2*ma(idx).d-2*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"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 final case class Pair(d: Long, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r ) {\n val mid = (l + r) / 2\n if (2 * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readLongs(n)\n val m = readLine().toInt\n val b = readLongs(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n\n val diff = a.sum - b.sum\n var v = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2 * cur) < v) {\n v = diff - 2 * cur\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- 1 to n) {\n if (i != j) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n }\n\n for (i <- 1 to m) {\n for (j <- 1 to m) {\n if (i != j) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n }\n\n val na = nb.result().sortWith(_.d < _.d)\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {\n v = Math.abs(diff+2*ma(idx).d-2*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r) {\n val mid = (l + r) / 2\n if (2L * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2L * cur) < v) {\n v = Math.abs(diff - 2L * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- i+1 to n) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n\n for (i <- 1 to m) {\n for (j <- i+1 to m) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n\n val na = nb.result()\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {\n v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n\n if (v == 14520) {\n println(diff)\n println(a(37) + \" \" + a(1627))\n println(b(0) + \" \" + b(2))\n }\n\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r ) {\n val mid = (l + r) / 2\n if (2 * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n\n val diff: Long = a.sum - b.sum\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2 * cur) < v) {\n v = Math.abs(diff - 2 * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- 1 to n) {\n if (i != j) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n }\n\n for (i <- 1 to m) {\n for (j <- 1 to m) {\n if (i != j) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n }\n\n val na = nb.result().sortWith(_.d < _.d)\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {\n v = Math.abs(diff+2*ma(idx).d-2*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r ) {\n val mid = (l + r) / 2\n if (2L * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2L * cur) < v) {\n v = Math.abs(diff - 2L * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- i+1 to n) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n\n for (i <- 1 to m) {\n for (j <- i+1 to m) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n\n val na = nb.result()\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {\n v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r ) {\n val mid = (l + r) / 2\n if (2 * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n\n val diff: Long = a.map(_.toLong).sum - b.map(_.toLong).sum\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2 * cur) < v) {\n v = Math.abs(diff - 2 * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- 1 to n) {\n if (i != j) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n }\n\n for (i <- 1 to m) {\n for (j <- 1 to m) {\n if (i != j) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n }\n\n val na = nb.result().sortWith(_.d < _.d)\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {\n v = Math.abs(diff+2*ma(idx).d-2*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}, {"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 final case class Pair(d: Int, a: Int, b: Int)\n\n def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {\n var l = start\n var r = end\n while (l <= r ) {\n val mid = (l + r) / 2\n if (2 * a(mid).d > v) r = mid - 1\n else l = mid + 1\n }\n if (r >= start && a(r).d <= v) r\n else -1\n }\n\n def main(args: Array[String]) {\n val n = readLine().toInt\n val a = readInts(n)\n val m = readLine().toInt\n val b = readInts(m)\n val nb = ArrayBuilder.make[Pair]()\n val mb = ArrayBuilder.make[Pair]()\n val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)\n var v: Long = Math.abs(diff)\n var k = 0\n val npb = ArrayBuilder.make[Int]()\n val mpb = ArrayBuilder.make[Int]()\n\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n val cur = a(i-1) - b(j-1)\n if (Math.abs(diff - 2L * cur) < v) {\n v = Math.abs(diff - 2L * cur)\n npb.clear()\n npb += i\n mpb.clear()\n mpb += j\n k = 1\n }\n }\n }\n\n for (i <- 1 to n) {\n for (j <- i+1 to n) {\n nb += Pair(a(i-1) + a(j-1), i, j)\n }\n }\n\n for (i <- 1 to m) {\n for (j <- i+1 to m) {\n mb += Pair(b(i-1) + b(j-1), i, j)\n }\n }\n\n val na = nb.result()\n val ma = mb.result().sortWith(_.d < _.d)\n\n for (i <- na.indices) {\n var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)\n if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {\n idx += 1\n }\n if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {\n v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)\n npb.clear()\n npb += (na(i).a, na(i).b)\n mpb.clear()\n mpb += (ma(idx).a, ma(idx).b)\n mpb += (ma(idx).a, ma(idx).b)\n k = 2\n }\n }\n\n val np = npb.result()\n val mp = mpb.result()\n println(v)\n println(k)\n for (i <- np.indices) {\n println(np(i) + \" \" + mp(i))\n }\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "src_uid": "b8016e8d1e7a3bb6d0ffdcc5ef9ced19"} {"nl": {"description": "You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following: decrease the number on the clock by $$$1$$$, or swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \\ldots, s_n$$$ ($$$0 \\le s_1, s_2, \\ldots, s_n \\le 9$$$) \u2014 the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.", "output_spec": "For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.", "sample_inputs": ["7\n3\n007\n4\n1000\n5\n00000\n3\n103\n4\n2020\n9\n123456789\n30\n001678294039710047203946100020"], "sample_outputs": ["7\n2\n0\n5\n6\n53\n115"], "notes": "NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly $$$m$$$ books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ \u2014 the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose exactly $$$m$$$ books from the given $$$n$$$ books in such a way that: Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set; the total reading time of these $$$m$$$ books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le k \\le m \\le n \\le 2 \\cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le t_i \\le 10^4$$$, $$$0 \\le a_i, b_i \\le 1$$$), where: $$$t_i$$$ \u2014 the amount of time required for reading the $$$i$$$-th book; $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise; $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise. ", "output_spec": "If there is no solution, print only one integer -1. If the solution exists, print $$$T$$$ in the first line \u2014 the minimum total reading time of the suitable set of books. In the second line print $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ in any order \u2014 indices of books which are in the set you found. If there are several answers, print any of them.", "sample_inputs": ["6 3 1\n6 0 0\n11 1 0\n9 0 1\n21 1 1\n10 1 0\n8 0 1", "6 3 2\n6 0 0\n11 1 0\n9 0 1\n21 1 1\n10 1 0\n8 0 1"], "sample_outputs": ["24\n6 5 1", "39\n4 6 5"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contests._1374\n\nobject ReadingBookHard {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val (aliceL, bobL, bothL, noneL) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)])) {\n case ((alice, bob, both, none), i) =>\n val Array(time, a, b) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (\n if (a == 1 && b == 0) (time, i) :: alice else alice,\n if (a == 0 && b == 1) (time, i) :: bob else bob,\n if (a == 1 && b == 1) (time, i) :: both else both,\n if (a == 0 && b == 0) (time, i) :: none else none\n )\n }\n\n val aliceA = aliceL.toArray.sortBy(_._1)\n val bobA = bobL.toArray.sortBy(_._1)\n val bothA = bothL.toArray.sortBy(_._1)\n val noneA = noneL.toArray.sortBy(_._1)\n\n val c = bothA.length min k // next pos\n val a, b = k - c // next pos\n\n if (a > aliceA.length || b > bobA.length || a + b + c > m)\n println(-1)\n else {\n @scala.annotation.tailrec\n def loop(a: Int, b: Int, c: Int, d: Int, mi: Int = 0): (Int, Int, Int, Int) = {\n if (mi == m) (a, b, c, d)\n else {\n if (0 < c && a < aliceA.length && b < bobA.length && {\n val delta = aliceA(a)._1 + bobA(b)._1 - bothA(c - 1)._1\n !(delta > aliceA(a)._1) && !(delta > bobA(b)._1) && !(c < bothA.length && delta > bothA(c)._1) && !(d < noneA.length && delta > noneA(d)._1)\n })\n loop(a + 1, b + 1, c - 1, d, mi + 1)\n else if (a < aliceA.length && !(b < bobA.length && aliceA(a)._1 > bobA(b)._1) && !(c < bothA.length && aliceA(a)._1 > bothA(c)._1) && !(d < noneA.length && aliceA(a)._1 > noneA(d)._1))\n loop(a + 1, b, c, d, mi + 1)\n else if (b < bobA.length && !(a < aliceA.length && bobA(b)._1 > aliceA(a)._1) && !(c < bothA.length && bobA(b)._1 > bothA(c)._1) && !(d < noneA.length && bobA(b)._1 > noneA(d)._1))\n loop(a, b + 1, c, d, mi + 1)\n else if (c < bothA.length && !(a < aliceA.length && bothA(c)._1 > aliceA(a)._1) && !(b < bobA.length && bothA(c)._1 > bobA(b)._1) && !(d < noneA.length && bothA(c)._1 > noneA(d)._1))\n loop(a, b, c + 1, d, mi + 1)\n else if (d < noneA.length && !(a < aliceA.length && noneA(d)._1 > aliceA(a)._1) && !(b < bobA.length && noneA(d)._1 > bobA(b)._1) && !(c < bothA.length && noneA(d)._1 > bothA(c)._1))\n loop(a, b, c, d + 1, mi + 1)\n else\n (a, b, c, d)\n }\n }\n\n val (fai, fbi, fci, fdi) = loop(a, b, c, 0, a + b + c)\n\n val faiIncluded = (0 until fai).foldLeft((0, List.empty[Int])) { case ((res, indices), i) =>\n (res + aliceA(i)._1, aliceA(i)._2 :: indices)\n }\n\n val fbiIncluded = (0 until fbi).foldLeft(faiIncluded) { case ((res, indices), i) =>\n (res + bobA(i)._1, bobA(i)._2 :: indices)\n }\n\n val fciIncluded = (0 until fci).foldLeft(fbiIncluded) { case ((res, indices), i) =>\n (res + bothA(i)._1, bothA(i)._2 :: indices)\n }\n\n val fdiIncluded = (0 until fdi).foldLeft(fciIncluded) { case ((res, indices), i) =>\n (res + noneA(i)._1, noneA(i)._2 :: indices)\n }\n\n val (res, indices) = fdiIncluded\n\n println(res)\n println(indices.mkString(\" \"))\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1374\n\nobject ReadingBookHard {\n\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val (aliceL, bobL, bothL, noneL) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)])) {\n case ((alice, bob, both, none), i) =>\n val Array(time, a, b) = io.StdIn.readLine.split(\" \").map(_.toInt)\n (\n if (a == 1 && b == 0) (time, i) :: alice else alice,\n if (a == 0 && b == 1) (time, i) :: bob else bob,\n if (a == 1 && b == 1) (time, i) :: both else both,\n if (a == 0 && b == 0) (time, i) :: none else none\n )\n }\n\n val aliceA = aliceL.toArray.sortBy(_._1)\n val bobA = bobL.toArray.sortBy(_._1)\n val bothA = bothL.toArray.sortBy(_._1)\n val noneA = noneL.toArray.sortBy(_._1)\n\n val c = bothA.length min k // next pos\n val a, b = k - c // next pos\n\n if (a >= aliceA.length || b >= bobA.length || a + b + c > m)\n println(-1)\n else {\n @scala.annotation.tailrec\n def loop(a: Int, b: Int, c: Int, d: Int, mi: Int = 0): (Int, Int, Int, Int) = {\n if (mi == m) (a, b, c, d)\n else {\n if (0 < c && a < aliceA.length && b < bobA.length && {\n val delta = aliceA(a)._1 + bobA(b)._1 - bothA(c - 1)._1\n !(delta > aliceA(a)._1) && !(delta > bobA(b)._1) && !(c < bothA.length && delta > bothA(c)._1) && !(d < noneA.length && delta > noneA(d)._1)\n })\n loop(a + 1, b + 1, c - 1, d, mi + 1)\n else if (a < aliceA.length && !(b < bobA.length && aliceA(a)._1 > bobA(b)._1) && !(c < bothA.length && aliceA(a)._1 > bothA(c)._1) && !(d < noneA.length && aliceA(a)._1 > noneA(d)._1))\n loop(a + 1, b, c, d, mi + 1)\n else if (b < bobA.length && !(a < aliceA.length && bobA(b)._1 > aliceA(a)._1) && !(c < bothA.length && bobA(b)._1 > bothA(c)._1) && !(d < noneA.length && bobA(b)._1 > noneA(d)._1))\n loop(a, b + 1, c, d, mi + 1)\n else if (c < bothA.length && !(a < aliceA.length && bothA(c)._1 > aliceA(a)._1) && !(b < bobA.length && bothA(c)._1 > bobA(b)._1) && !(d < noneA.length && bothA(c)._1 > noneA(d)._1))\n loop(a, b, c + 1, d, mi + 1)\n else if (d < noneA.length && !(a < aliceA.length && noneA(d)._1 > aliceA(a)._1) && !(b < bobA.length && noneA(d)._1 > bobA(b)._1) && !(c < bothA.length && noneA(d)._1 > bothA(c)._1))\n loop(a, b, c, d + 1, mi + 1)\n else\n (a, b, c, d)\n }\n }\n\n val (fai, fbi, fci, fdi) = loop(a, b, c, 0, a + b + c)\n\n val faiIncluded = (0 until fai).foldLeft((0, List.empty[Int])) { case ((res, indices), i) =>\n (res + aliceA(i)._1, aliceA(i)._2 :: indices)\n }\n\n val fbiIncluded = (0 until fbi).foldLeft(faiIncluded) { case ((res, indices), i) =>\n (res + bobA(i)._1, bobA(i)._2 :: indices)\n }\n\n val fciIncluded = (0 until fci).foldLeft(fbiIncluded) { case ((res, indices), i) =>\n (res + bothA(i)._1, bothA(i)._2 :: indices)\n }\n\n val fdiIncluded = (0 until fdi).foldLeft(fciIncluded) { case ((res, indices), i) =>\n (res + noneA(i)._1, noneA(i)._2 :: indices)\n }\n\n val (res, indices) = fdiIncluded\n\n println(res)\n println(indices.mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "21765379e446ec4c91810eff1ce28db9"} {"nl": {"description": "Let's denote that some array $$$b$$$ is bad if it contains a subarray $$$b_l, b_{l+1}, \\dots, b_{r}$$$ of odd length more than $$$1$$$ ($$$l < r$$$ and $$$r - l + 1$$$ is odd) such that $$$\\forall i \\in \\{0, 1, \\dots, r - l\\}$$$ $$$b_{l + i} = b_{r - i}$$$.If an array is not bad, it is good.Now you are given an array $$$a_1, a_2, \\dots, a_n$$$. Some elements are replaced by $$$-1$$$. Calculate the number of good arrays you can obtain by replacing each $$$-1$$$ with some integer from $$$1$$$ to $$$k$$$.Since the answer can be large, print it modulo $$$998244353$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n, k \\le 2 \\cdot 10^5$$$) \u2014 the length of array $$$a$$$ and the size of \"alphabet\", i.\u2009e., the upper bound on the numbers you may use to replace $$$-1$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$a_i = -1$$$ or $$$1 \\le a_i \\le k$$$) \u2014 the array $$$a$$$.", "output_spec": "Print one integer \u2014 the number of good arrays you can get, modulo $$$998244353$$$.", "sample_inputs": ["2 3\n-1 -1", "5 2\n1 -1 -1 1 2", "5 3\n1 -1 -1 1 2", "4 200000\n-1 -1 12345 -1"], "sample_outputs": ["9", "0", "2", "735945883"], "notes": null}, "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 = 998244353\n val out = new PrintWriter(System.out)\n\n def solve(): Unit = {\n val N, K = ni()\n val A = na(N)\n REP(N - 2) { i =>\n // \u3069\u3046\u3084\u3063\u3066\u3082\u56de\u6587\u304c\u3067\u304d\u308b\u30d1\u30bf\u30fc\u30f3\n if (A(i) != -1 && A(i + 2) != -1 && A(i) == A(i + 2)) {\n println(0)\n return\n }\n }\n\n val flg = Array.ofDim[Boolean](N)\n case class Group(l: Int, r: Int)\n\n val G = ArrayBuffer[Group]()\n REP(N) { l =>\n if (A(l) == -1 && !flg(l)) {\n flg(l) = true\n var r = l\n while(r + 2 < N && A(r + 2) == -1) {\n r += 2\n flg(r) = true\n }\n G += Group(l, r)\n }\n }\n\n debug(G.mkString(\",\"))\n\n def calcDP(g: Group, init: Int) = {\n val n = (g.r - g.l) / 2 + 1\n val dp = Array.ofDim[Long](n, 2)\n dp(0)(0) = init\n dp(0)(1) = 1\n REP(n - 1) { j =>\n dp(j + 1)(0) = dp(j)(1) * (K - 1) % MOD\n dp(j + 1)(1) = (dp(j)(0) + dp(j)(1) * (K - 2)) % MOD\n debug(\"dump DP\")\n debug(s\"${dp(j + 1)(0)} ${dp(j + 1)(1)}\")\n }\n (dp(n - 1)(0), dp(n - 1)(1))\n }\n\n var ans = 1L\n REP(G.length) { i =>\n val g = G(i)\n // \u4e21\u30b5\u30a4\u30c9\u304c\u306a\u3044\n val v: Long = if (g.l - 2 < 0 && g.r + 2 >= N) {\n val (dp1, dpN) = calcDP(g, 1)\n debug(s\"A $dp1 $dpN\")\n (dp1 + dpN * (K - 1)) % MOD\n\n // \u7247\u5074\u304c\u306a\u3044\n } else if (g.l - 2 < 0 || g.r + 2 >= N) {\n val (dp1, dpN) = calcDP(g, 1)\n debug(s\"B $dp1 $dpN\")\n dpN * (K - 1) % MOD\n\n // \u4e21\u30b5\u30a4\u30c9\u304c\u540c\u3058\n } else if (A(g.l - 2) == A(g.r + 2)) {\n val (dp1, dpN) = calcDP(g, 0)\n debug(s\"C $dp1 $dpN\")\n dpN * (K - 1) % MOD\n\n // \u4e21\u30b5\u30a4\u30c9\u304c\u9055\u3046\n } else {\n val (dp1, dpN) = calcDP(g, 0)\n debug(s\"D $dp1 $dpN\")\n (dp1 + dpN * (K - 2)) % MOD\n }\n\n ans = ans * v % MOD\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": [], "src_uid": "a393e63c1d9fcdb7b0e8d525a1f1b8dd"} {"nl": {"description": "Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s\u2009\u2260\u2009t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.", "input_spec": "The first lines contain four integers n, m, s and t (2\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009m\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009s,\u2009t\u2009\u2264\u2009n) \u2014 the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s\u2009\u2260\u2009t). Next m lines contain the roads. Each road is given as a group of three integers ai,\u2009bi,\u2009li (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi;\u00a01\u2009\u2264\u2009li\u2009\u2264\u2009106) \u2014 the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads.", "output_spec": "Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word \"YES\" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word \"CAN\" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print \"NO\" (without the quotes).", "sample_inputs": ["6 7 1 6\n1 2 2\n1 3 10\n2 3 7\n2 4 8\n3 5 3\n4 5 2\n5 6 1", "3 3 1 3\n1 2 10\n2 3 10\n1 3 100", "2 2 1 2\n1 2 1\n1 2 2"], "sample_outputs": ["YES\nCAN 2\nCAN 1\nCAN 1\nCAN 1\nCAN 1\nYES", "YES\nYES\nCAN 81", "YES\nNO"], "notes": "NoteThe cost of repairing the road is the difference between the time needed to ride along it before and after the repairing.In the first sample president initially may choose one of the two following ways for a ride: 1\u2009\u2192\u20092\u2009\u2192\u20094\u2009\u2192\u20095\u2009\u2192\u20096 or 1\u2009\u2192\u20092\u2009\u2192\u20093\u2009\u2192\u20095\u2009\u2192\u20096."}, "positive_code": [{"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n val inf = 10000000000007L\n val mod = 1000000021\n\n def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[Long]): Unit = {\n val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)\n\n pq.enqueue((0, start))\n D(start) = 0\n W(start) = 1\n while (pq.nonEmpty) {\n val (cd, ci) = pq.dequeue()\n if (cd <= D(ci)) {\n for ((ni, nd) <- adj(ci)) {\n if (D(ci) + nd < D(ni)) {\n D(ni) = D(ci) + nd\n pq.enqueue((D(ni), ni))\n W(ni) = W(ci) % mod\n } else if (D(ci) + nd == D(ni)) W(ni) = (W(ni) + (W(ci) % mod)) % mod\n }\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = readLine().split(\" \").map(_.toInt)\n val (n, m, s, t) = (line(0), line(1), line(2), line(3))\n\n\n val A = Array.fill[Long](n+1)(inf)\n val B = Array.fill[Long](n+1)(inf)\n val W1 = Array.fill[Long](n+1)(0)\n val W2 = Array.fill[Long](n+1)(0)\n\n val adj1 = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val adj2 = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val e = new ListBuffer[(Int, Int, Int)]\n\n val t1 = System.currentTimeMillis\n\n (1 to m).foreach { _ =>\n line = readLine().split(\" \").map(_.toInt)\n adj1(line(0)) += ((line(1), line(2)))\n adj2(line(1)) += ((line(0), line(2)))\n e += ((line(0), line(1), line(2)))\n }\n\n val t2 = System.currentTimeMillis\n\n bfs(s, adj1, A, W1)\n bfs(t, adj2, B, W2)\n\n\n val dist = A(t)\n\n val t3 = System.currentTimeMillis\n\n val sb = new StringBuilder\n\n// if (e.head._1 == 8360) println((t2-t1) + \" ... \" + (t3-t2))\n\n e.foreach { case(from, to, d) =>\n val rest = A(from) + B(to)\n if (rest + d == dist && (W1(from) * W2(to))%mod == W1(t)) sb.append(\"YES\\n\")\n else if (rest < dist - 1 && dist > 1) sb.append(\"CAN \" + (rest + d + 1 - dist) + \"\\n\")\n else sb.append(\"NO\\n\")\n }\n\n print(sb)\n\n }\n\n}\n"}], "negative_code": [{"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n val inf = 10000000000007L\n\n def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[Long]): Unit = {\n val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)\n\n pq.enqueue((0, start))\n D(start) = 0\n W(start) = 1\n while (pq.nonEmpty) {\n val (cd, ci) = pq.dequeue()\n if (cd <= D(ci)) {\n for ((ni, nd) <- adj(ci)) {\n if (D(ci) + nd < D(ni)) {\n D(ni) = D(ci) + nd\n pq.enqueue((D(ni), ni))\n W(ni) = W(ci)\n } else if (D(ci) + nd == D(ni)) W(ni) += W(ci)\n }\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = readLine().split(\" \").map(_.toInt)\n val (n, m, s, t) = (line(0), line(1), line(2), line(3))\n\n\n val A = Array.fill[Long](n+1)(inf)\n val B = Array.fill[Long](n+1)(inf)\n val W1 = Array.fill[Long](n+1)(0)\n val W2 = Array.fill[Long](n+1)(0)\n\n val adj1 = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val adj2 = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val e = new ListBuffer[(Int, Int, Int)]\n\n val t1 = System.currentTimeMillis\n\n (1 to m).foreach { _ =>\n line = readLine().split(\" \").map(_.toInt)\n adj1(line(0)) += ((line(1), line(2)))\n adj2(line(1)) += ((line(0), line(2)))\n e += ((line(0), line(1), line(2)))\n }\n\n val t2 = System.currentTimeMillis\n\n bfs(s, adj1, A, W1)\n bfs(t, adj2, B, W2)\n\n\n val dist = A(t)\n\n val t3 = System.currentTimeMillis\n\n val sb = new StringBuilder\n\n// if (e.head._1 == 8360) println((t2-t1) + \" ... \" + (t3-t2))\n\n e.foreach { case(from, to, d) =>\n val rest = A(from) + B(to)\n if (rest + d == dist && W1(from) * W2(to) == W1(t)) sb.append(\"YES\\n\")\n else if (rest < dist - 1 && dist > 1) sb.append(\"CAN \" + (rest + d + 1 - dist) + \"\\n\")\n else sb.append(\"NO\\n\")\n }\n\n print(sb)\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n val inf = 10000000000007L\n\n def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[BigInt]): Unit = {\n val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)\n\n pq.enqueue((0, start))\n D(start) = 0\n W(start) = 1\n while (pq.nonEmpty) {\n val (cd, ci) = pq.dequeue()\n if (cd <= D(ci)) {\n for ((ni, nd) <- adj(ci)) {\n if (D(ci) + nd < D(ni)) {\n D(ni) = D(ci) + nd\n pq.enqueue((D(ni), ni))\n W(ni) = W(ci)\n } else if (D(ci) + nd == D(ni)) W(ni) += W(ci)\n }\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = readLine().split(\" \").map(_.toInt)\n val (n, m, s, t) = (line(0), line(1), line(2), line(3))\n\n\n val A = Array.fill[Long](n+1)(inf)\n val B = Array.fill[Long](n+1)(inf)\n val W1 = Array.fill[BigInt](n+1)(0)\n val W2 = Array.fill[BigInt](n+1)(0)\n\n val adj = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val pre = Array.fill(n+1)(new ListBuffer[Int])\n val e = new ListBuffer[(Int, Int, Int)]\n\n (1 to m).foreach { _ =>\n line = readLine().split(\" \").map(_.toInt)\n adj(line(0)) += ((line(1), line(2)))\n adj(line(1)) += ((line(0), line(2)))\n e += ((line(0), line(1), line(2)))\n }\n\n bfs(s, adj, A, W1)\n bfs(t, adj, B, W2)\n\n\n val dist = A(t)\n\n e.foreach { case(i, j, d) =>\n val (from, to) = if (A(i) + B(j) > A(j) + B(i)) (j,i) else (i,j)\n if (A(from) + B(to) + d == dist && W1(from) * W2(to) == W1(t)) println(\"YES\")\n else if (A(from) + B(to) < dist - 1 && dist > 1) println(\"CAN \" + (A(from) + B(to) + d + 1 - dist))\n else println(\"NO\")\n }\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n val inf = 10000000000007L\n\n def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[BigInt]): Unit = {\n val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)\n\n pq.enqueue((0, start))\n D(start) = 0\n W(start) = 1\n while (pq.nonEmpty) {\n val (cd, ci) = pq.dequeue()\n if (cd <= D(ci)) {\n for ((ni, nd) <- adj(ci)) {\n if (D(ci) + nd < D(ni)) {\n D(ni) = D(ci) + nd\n pq.enqueue((D(ni), ni))\n W(ni) = W(ci)\n } else if (D(ci) + nd == D(ni)) W(ni) += W(ci)\n }\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = readLine().split(\" \").map(_.toInt)\n val (n, m, s, t) = (line(0), line(1), line(2), line(3))\n\n\n val A = Array.fill[Long](n+1)(inf)\n val B = Array.fill[Long](n+1)(inf)\n val W1 = Array.fill[BigInt](n+1)(0)\n val W2 = Array.fill[BigInt](n+1)(0)\n\n val adj = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val pre = Array.fill(n+1)(new ListBuffer[Int])\n val e = new ListBuffer[(Int, Int, Int)]\n\n (1 to m).foreach { _ =>\n line = readLine().split(\" \").map(_.toInt)\n adj(line(0)) += ((line(1), line(2)))\n adj(line(1)) += ((line(0), line(2)))\n e += ((line(0), line(1), line(2)))\n }\n\n bfs(s, adj, A, W1)\n bfs(t, adj, B, W2)\n\n\n val dist = A(t)\n\n e.foreach { case(i, j, d) =>\n val (from, to) = if (A(i) + B(j) > A(j) + B(i)) (j,i) else (i,j)\n if (A(from) + B(to) + d == dist) {\n if (W1(from) * W2(to) != W1(t)) println(\"CAN 1\")\n else println(\"YES\")\n }\n else if (A(from) + B(to) < dist && dist > 1) println(\"CAN \" + (A(from) + B(to) + d + 1 - dist))\n else println(\"NO\")\n }\n\n }\n\n}\n"}, {"source_code": "import io.StdIn._\nimport scala.collection.mutable\nimport scala.collection.mutable._\n\nobject Solution {\n\n val inf = 10000000000007L\n val mod = 1000000007\n\n def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[Long]): Unit = {\n val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)\n\n pq.enqueue((0, start))\n D(start) = 0\n W(start) = 1\n while (pq.nonEmpty) {\n val (cd, ci) = pq.dequeue()\n if (cd <= D(ci)) {\n for ((ni, nd) <- adj(ci)) {\n if (D(ci) + nd < D(ni)) {\n D(ni) = D(ci) + nd\n pq.enqueue((D(ni), ni))\n W(ni) = W(ci) % mod\n } else if (D(ci) + nd == D(ni)) W(ni) = (W(ni) + (W(ci) % mod)) % mod\n }\n }\n }\n }\n\n def main(args: Array[String]) {\n var line = readLine().split(\" \").map(_.toInt)\n val (n, m, s, t) = (line(0), line(1), line(2), line(3))\n\n\n val A = Array.fill[Long](n+1)(inf)\n val B = Array.fill[Long](n+1)(inf)\n val W1 = Array.fill[Long](n+1)(0)\n val W2 = Array.fill[Long](n+1)(0)\n\n val adj1 = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val adj2 = Array.fill(n+1)(new ListBuffer[(Int, Int)])\n val e = new ListBuffer[(Int, Int, Int)]\n\n val t1 = System.currentTimeMillis\n\n (1 to m).foreach { _ =>\n line = readLine().split(\" \").map(_.toInt)\n adj1(line(0)) += ((line(1), line(2)))\n adj2(line(1)) += ((line(0), line(2)))\n e += ((line(0), line(1), line(2)))\n }\n\n val t2 = System.currentTimeMillis\n\n bfs(s, adj1, A, W1)\n bfs(t, adj2, B, W2)\n\n\n val dist = A(t)\n\n val t3 = System.currentTimeMillis\n\n val sb = new StringBuilder\n\n// if (e.head._1 == 8360) println((t2-t1) + \" ... \" + (t3-t2))\n\n e.foreach { case(from, to, d) =>\n val rest = A(from) + B(to)\n if (rest + d == dist && (W1(from) * W2(to))%mod == W1(t)) sb.append(\"YES\\n\")\n else if (rest < dist - 1 && dist > 1) sb.append(\"CAN \" + (rest + d + 1 - dist) + \"\\n\")\n else sb.append(\"NO\\n\")\n }\n\n print(sb)\n\n }\n\n}\n"}], "src_uid": "d818876d0bb7a22b7aebfca5b77d2cd5"} {"nl": {"description": "Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.", "input_spec": "The first line contains one integer n\u00a0\u2014 the number of vertices in the tree (3\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000). Each of the next n\u2009-\u20091 lines contains one integer pi (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the index of the parent of the i\u2009+\u20091-th vertex (1\u2009\u2264\u2009pi\u2009\u2264\u2009i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.", "output_spec": "Print \"Yes\" if the tree is a spruce and \"No\" otherwise.", "sample_inputs": ["4\n1\n1\n1", "7\n1\n1\n1\n2\n2\n2", "8\n1\n1\n1\n1\n3\n3\n3"], "sample_outputs": ["Yes", "No", "Yes"], "notes": "NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:"}, "positive_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 = (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"}, {"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"} {"nl": {"description": "This is the easy version of this problem. The only difference is the constraint on $$$k$$$ \u2014 the number of gifts in the offer. In this version: $$$k=2$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky\u00a0\u2014 today the offer \"$$$k$$$ of goods for the price of one\" is held in store. Remember, that in this problem $$$k=2$$$.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$\u00a0\u2014 the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \\ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$). Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \\ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the test. The next lines contain a description of $$$t$$$ test cases. The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le p \\le 2\\cdot10^9$$$, $$$k=2$$$)\u00a0\u2014 the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^4$$$)\u00a0\u2014 the prices of goods. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \\cdot 10^5$$$. It is guaranteed that in this version of the problem $$$k=2$$$ for all test cases.", "output_spec": "For each test case in a separate line print one integer $$$m$$$\u00a0\u2014 the maximum number of goods that Vasya can buy.", "sample_inputs": ["6\n5 6 2\n2 4 3 5 7\n5 11 2\n2 4 3 5 7\n2 10000 2\n10000 10000\n2 9999 2\n10000 10000\n5 13 2\n8 2 8 2 5\n3 18 2\n1 2 3"], "sample_outputs": ["3\n4\n2\n0\n4\n3"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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": [], "src_uid": "b9bafdc49709b4fc4b5fe786d5aa99a3"} {"nl": {"description": "There are some beautiful girls in Arpa\u2019s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i,\u2009j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) such that , where is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.", "input_spec": "First line contains two integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009x\u2009\u2264\u2009105)\u00a0\u2014 the number of elements in the array and the integer x. Second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105)\u00a0\u2014 the elements of the array.", "output_spec": "Print a single integer: the answer to the problem.", "sample_inputs": ["2 3\n1 2", "6 1\n5 1 2 3 4 1"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample there is only one pair of i\u2009=\u20091 and j\u2009=\u20092. so the answer is 1.In the second sample the only two pairs are i\u2009=\u20093, j\u2009=\u20094 (since ) and i\u2009=\u20091, j\u2009=\u20095 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR."}, "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 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"}, {"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"} {"nl": {"description": "The new \"Die Hard\" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A \"Die Hard\" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 \u2014 the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.", "output_spec": "Print \"YES\" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print \"NO\".", "sample_inputs": ["4\n25 25 50 50", "2\n25 100", "4\n50 50 25 25"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_code": [{"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}"}, {"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\") > 2){m(\"25\") -= 3} else yesOrNo = \"NO\"}\n case _ => {yesOrNo = \"NO\"}\n }\n }\n println(yesOrNo)\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}"}], "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"} {"nl": {"description": "George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi\u2009\u2264\u2009qi). Your task is to count how many rooms has free place for both George and Alex.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of rooms. The i-th of the next n lines contains two integers pi and qi (0\u2009\u2264\u2009pi\u2009\u2264\u2009qi\u2009\u2264\u2009100) \u2014 the number of people who already live in the i-th room and the room's capacity.", "output_spec": "Print a single integer \u2014 the number of rooms where George and Alex can move in.", "sample_inputs": ["3\n1 1\n2 2\n3 3", "3\n1 10\n0 10\n10 10"], "sample_outputs": ["0", "2"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1\u2009\u2264\u2009d\u2009<\u2009l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.The car can enter Bercouver at any speed.", "input_spec": "The first line of the input file contains two integer numbers a and v (1\u2009\u2264\u2009a,\u2009v\u2009\u2264\u200910000). The second line contains three integer numbers l, d and w (2\u2009\u2264\u2009l\u2009\u2264\u200910000; 1\u2009\u2264\u2009d\u2009<\u2009l; 1\u2009\u2264\u2009w\u2009\u2264\u200910000).", "output_spec": "Print the answer with at least five digits after the decimal point.", "sample_inputs": ["1 1\n2 1 3", "5 70\n200 170 40"], "sample_outputs": ["2.500000000000", "8.965874696353"], "notes": null}, "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 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 //\u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0432 \u043b\u044e\u0431\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u0440\u0430\u0437\u0433\u043e\u043d \u0434\u043e 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"} {"nl": {"description": "Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?", "input_spec": "The first line contains the only integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of cookie bags Anna and Maria have. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the number of cookies in the i-th bag.", "output_spec": "Print in the only line the only number \u2014 the sought number of ways. If there are no such ways print 0.", "sample_inputs": ["1\n1", "10\n1 2 2 3 4 4 4 2 2 2", "11\n2 2 2 2 2 2 2 2 2 2 99"], "sample_outputs": ["1", "8", "1"], "notes": "NoteIn the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies \u2014 5\u2009+\u20093\u2009=\u20098 ways in total.In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2\u2009*\u20099\u2009+\u200999\u2009=\u2009117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies."}, "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": "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"}, {"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"} {"nl": {"description": "Vasya plays the Geometry Horse.The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci\u00b7f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t\u2009+\u20091, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i\u2009+\u20091 after destruction of pi (1\u2009\u2264\u2009i\u2009\u2264\u2009t) figures, so the (pi\u2009+\u20091)-th figure to be destroyed is considered with factor equal to i\u2009+\u20091.Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.", "input_spec": "The first line contains the only integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of figure types. Each of the following n lines contains two integer numbers ki and ci (1\u2009\u2264\u2009ki\u2009\u2264\u2009109,\u20090\u2009\u2264\u2009ci\u2009\u2264\u20091000), separated with space \u2014 the number of figures of the i-th type and the cost of one i-type figure, correspondingly. The next line contains the only integer number t (1\u2009\u2264\u2009t\u2009\u2264\u2009100) \u2014 the number that describe the factor's changes. The next line contains t integer numbers pi (1\u2009\u2264\u2009p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009pt\u2009\u2264\u20091012), separated with spaces. Please, do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specificator.", "output_spec": "Print the only number \u2014 the maximum number of points Vasya can get.", "sample_inputs": ["1\n5 10\n2\n3 6", "2\n3 8\n5 10\n1\n20"], "sample_outputs": ["70", "74"], "notes": "NoteIn the first example Vasya destroys three figures first and gets 3\u00b71\u00b710\u2009=\u200930 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2\u00b72\u00b710\u2009=\u200940 points. As a result Vasya will get 70 points.In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3\u00b78\u2009+\u20095\u00b710)\u00b71\u2009=\u200974 points."}, "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 (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"}, {"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"} {"nl": {"description": "Find the number of k-divisible numbers on the segment [a,\u2009b]. In other words you need to find the number of such integer values x that a\u2009\u2264\u2009x\u2009\u2264\u2009b and x is divisible by k.", "input_spec": "The only line contains three space-separated integers k, a and b (1\u2009\u2264\u2009k\u2009\u2264\u20091018;\u2009-\u20091018\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u20091018).", "output_spec": "Print the required number.", "sample_inputs": ["1 1 10", "2 -4 4"], "sample_outputs": ["10", "5"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Your program fails again. This time it gets \"Wrong answer on test 233\".This is the easier version of the problem. In this version $$$1 \\le n \\le 2000$$$. You can hack this problem only if you solve and lock both problems.The problem is about a test containing $$$n$$$ one-choice-questions. Each of the questions contains $$$k$$$ options, and only one of them is correct. The answer to the $$$i$$$-th question is $$$h_{i}$$$, and if your answer of the question $$$i$$$ is $$$h_{i}$$$, you earn $$$1$$$ point, otherwise, you earn $$$0$$$ points for this question. The values $$$h_1, h_2, \\dots, h_n$$$ are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the $$$n$$$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question $$$i$$$ to the question $$$i \\bmod n + 1$$$. So it moves the answer for the question $$$1$$$ to question $$$2$$$, the answer for the question $$$2$$$ to the question $$$3$$$, ..., the answer for the question $$$n$$$ to the question $$$1$$$.We call all the $$$n$$$ answers together an answer suit. There are $$$k^n$$$ possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $$$1$$$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $$$998\\,244\\,353$$$.For example, if $$$n = 5$$$, and your answer suit is $$$a=[1,2,3,4,5]$$$, it will submitted as $$$a'=[5,1,2,3,4]$$$ because of a mistake. If the correct answer suit is $$$h=[5,2,2,3,4]$$$, the answer suit $$$a$$$ earns $$$1$$$ point and the answer suite $$$a'$$$ earns $$$4$$$ points. Since $$$4 > 1$$$, the answer suit $$$a=[1,2,3,4,5]$$$ should be counted.", "input_spec": "The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \\le n \\le 2000$$$, $$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the number of questions and the number of possible answers to each question. The following line contains $$$n$$$ integers $$$h_1, h_2, \\dots, h_n$$$, ($$$1 \\le h_{i} \\le k)$$$\u00a0\u2014 answers to the questions.", "output_spec": "Output one integer: the number of answers suits satisfying the given condition, modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["3 3\n1 3 1", "5 5\n1 1 4 2 2"], "sample_outputs": ["9", "1000"], "notes": "NoteFor the first example, valid answer suits are $$$[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 998244353\n\n def solve(): Unit = {\n val N, K = ni()\n val H = na(N)\n\n if (K == 1) {\n out.println(0)\n return\n }\n\n var best, next = Array.ofDim[Long](2 * N + 1)\n best(N) = 1\n REP(N) { i =>\n import java.util\n util.Arrays.fill(next, 0)\n if (H(i) == H((i + 1)%N)) {\n REP(next.length) { j =>\n next(j) = best(j) * K % MOD\n }\n } else {\n REP(next.length) { j =>\n next(j) += best(j) * (K - 2)\n if (j > 0) next(j) += best(j - 1)\n if (j < next.length - 1) next(j) += best(j + 1)\n next(j) %= MOD\n }\n }\n val t = best\n best = next\n next = t\n }\n var ans = 0L\n TO(N + 1, 2 * N) { i =>\n ans += best(i)\n }\n out.println(ans % MOD)\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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 998244353\n\n def solve(): Unit = {\n val N, K = ni()\n val H = na(N)\n\n if (K == 1) {\n out.println(1)\n return\n }\n\n var best, next = Array.fill[Long](2 * N + 1)(0)\n best(N) = 1\n REP(N) { i =>\n import java.util\n util.Arrays.fill(next, 0)\n if (H(i) == H((i + 1)%N)) {\n REP(next.length) { j =>\n next(j) = best(j) * K % MOD\n }\n } else {\n REP(next.length) { j =>\n next(j) += best(j) * (K - 2)\n if (j > 0) next(j) += best(j - 1)\n if (j < next.length - 1) next(j) += best(j + 1)\n next(j) %= MOD\n }\n }\n val t = best\n best = next\n next = t\n }\n var ans = 0L\n TO(N + 1, 2 * N) { i =>\n ans += best(i)\n ans %= MOD\n }\n out.println(ans)\n }\n}"}], "src_uid": "3a4b815bcc0983bca9789ec8e76e0ea0"} {"nl": {"description": "Mishka wants to buy some food in the nearby shop. Initially, he has $$$s$$$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $$$1 \\le x \\le s$$$, buy food that costs exactly $$$x$$$ burles and obtain $$$\\lfloor\\frac{x}{10}\\rfloor$$$ burles as a cashback (in other words, Mishka spends $$$x$$$ burles and obtains $$$\\lfloor\\frac{x}{10}\\rfloor$$$ back). The operation $$$\\lfloor\\frac{a}{b}\\rfloor$$$ means $$$a$$$ divided by $$$b$$$ rounded down.It is guaranteed that you can always buy some food that costs $$$x$$$ for any possible value of $$$x$$$.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has $$$s=19$$$ burles then the maximum number of burles he can spend is $$$21$$$. Firstly, he can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback. Now he has $$$s=10$$$ burles, so can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback and spend it too.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line and consists of one integer $$$s$$$ ($$$1 \\le s \\le 10^9$$$) \u2014 the number of burles Mishka initially has.", "output_spec": "For each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.", "sample_inputs": ["6\n1\n10\n19\n9876\n12345\n1000000000"], "sample_outputs": ["1\n11\n21\n10973\n13716\n1111111111"], "notes": null}, "positive_code": [{"source_code": "import java.io.PrintWriter\nimport util.control.Breaks._\n\nobject Solution {\n val reader = scala.io.StdIn\n def readInt = reader.readLine().toInt\n\n def main(args: Array[String]) {\n val c = new Array[Int](10)\n c(0) = 1\n for (i <- 1 to 9) c(i) = c(i-1) * 10\n var t = readInt\n while (t > 0) {\n var s = readInt\n var rs = 0\n for (i <- 9 to 0 by -1) {\n while (s >= c(i)){\n s -= c(i)\n s += c(i) / 10\n rs += c(i)\n }\n }\n\n println(rs)\n t-= 1\n }\n }\n}\n"}], "negative_code": [], "src_uid": "0beecbd62aa072a2f3aab542eeb56373"} {"nl": {"description": "You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to form $$$k$$$ teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than $$$k$$$ (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than $$$5$$$. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).It is possible that some students not be included in any team at all.Your task is to report the maximum possible total number of students in no more than $$$k$$$ (and at least one) non-empty balanced teams.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 5000$$$) \u2014 the number of students and the maximum number of teams, correspondingly. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is a programming skill of the $$$i$$$-th student.", "output_spec": "Print one integer \u2014 the maximum possible total number of students in no more than $$$k$$$ (and at least one) non-empty balanced teams.", "sample_inputs": ["5 2\n1 2 15 15 15", "6 1\n36 4 1 25 9 16", "4 4\n1 10 100 1000"], "sample_outputs": ["5", "2", "4"], "notes": null}, "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 sort(A)\n\n val dp = Array.fill[Int](N + 1, K + 1)(-1)\n dp(0)(0) = 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 val len = r - l + 1\n REP(K + 1) { k =>\n if (dp(l)(k) != -1) {\n dp(l + 1)(k) = max(dp(l + 1)(k), dp(l)(k)) // \u30b9\u30ad\u30c3\u30d7\n if (k < K) dp(r + 1)(k + 1) = max(dp(r + 1)(k + 1), dp(l)(k) + len)\n }\n }\n DEBUG {\n debug(\"DUMP\")\n REP(N + 1) { i =>\n debug(dp(i))\n }\n }\n }\n\n val ans = dp(N).max\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 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": "0135818c10fae9fc9efcc724fa43181f"} {"nl": {"description": "Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a \"domino show\".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to \"L\", if the i-th domino has been pushed to the left; \"R\", if the i-th domino has been pushed to the right; \".\", if the i-th domino has not been pushed. It is guaranteed that if si\u2009=\u2009sj\u2009=\u2009\"L\" and i\u2009<\u2009j, then there exists such k that i\u2009<\u2009k\u2009<\u2009j and sk\u2009=\u2009\"R\"; if si\u2009=\u2009sj\u2009=\u2009\"R\" and i\u2009<\u2009j, then there exists such k that i\u2009<\u2009k\u2009<\u2009j and sk\u2009=\u2009\"L\".", "output_spec": "Output a single integer, the number of the dominoes that remain vertical at the end of the process.", "sample_inputs": ["14\n.L.R...LR..L..", "5\nR....", "1\n."], "sample_outputs": ["4", "0", "1"], "notes": "NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction."}, "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}"}, {"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"}], "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"} {"nl": {"description": "You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \\le n \\le 100$$$, $$$0 \\le x \\le 100$$$, $$$1 \\le a, b \\le n$$$, $$$a \\neq b$$$) \u2014 the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.", "output_spec": "For each test case print one integer \u2014 the maximum distance between two rivaling students which you can obtain.", "sample_inputs": ["3\n5 1 3 2\n100 33 100 1\n6 0 2 3"], "sample_outputs": ["2\n99\n1"], "notes": "NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "negative_code": [], "src_uid": "1fd2619aabf4557093a59da804fd0e7b"} {"nl": {"description": "Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,\u2009o,\u2009i} and Igor has the set of letters {i,\u2009m,\u2009o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,\u2009o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,\u2009m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s\u2009=\u2009s1s2...sm is called lexicographically smaller than a string t\u2009=\u2009t1t2...tm (where s\u2009\u2260\u2009t) if si\u2009<\u2009ti where i is the smallest index such that si\u2009\u2260\u2009ti. (so sj\u2009=\u2009tj for all j\u2009<\u2009i)", "input_spec": "The first line of input contains a string s of length n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.", "output_spec": "The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.", "sample_inputs": ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"], "sample_outputs": ["fzfsirk", "xxxxxx", "ioi"], "notes": "NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx."}, "positive_code": [{"source_code": "object C extends App {\n\n val st = readLine()\n val n = st.length\n val st1 = st.sorted.take( (n+1)/2 )\n val st2 = readLine().sorted.reverse.take( n/2 )\n\n var s1 = 0\n var s2 = 0\n var f1 = st1.length - 1\n var f2 = st2.length - 1\n\n def orderIsOk = (s1 > f1) || (s2 > f2) || (st1(s1) < st2(s2))\n\n var ans = new Array[Char](n)\n var s3 = 0\n var f3 = n-1\n\n for (i <- 1 to n) {\n (orderIsOk, (i % 2) == 1) match {\n case (true, true) =>\n ans(s3) = st1(s1)\n s3 += 1\n s1 += 1\n case (true, false) =>\n ans(s3) = st2(s2)\n s3 += 1\n s2 += 1\n case (false, true) =>\n ans(f3) = st1(f1)\n f3 -= 1\n f1 -= 1\n case (false, false) =>\n ans(f3) = st2(f2)\n f3 -= 1\n f2 -= 1\n }\n }\n\n println(ans.mkString)\n}\n"}], "negative_code": [], "src_uid": "bc3d0d902ef457560e444ec0128f0688"} {"nl": {"description": "Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) \u00a0\u2014 the length of the given permutation. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ ($$$1 \\leq a_{i} \\leq n$$$) \u00a0\u2014 the initial permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.", "sample_inputs": ["2\n\n5\n\n1 2 3 4 5\n\n7\n\n3 2 4 5 1 6 7"], "sample_outputs": ["0\n2"], "notes": "NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least $$$2$$$ exchanges to sort the second permutation.$$$[3, 2, 4, 5, 1, 6, 7]$$$Perform special exchange on range ($$$1, 5$$$)$$$[4, 1, 2, 3, 5, 6, 7]$$$Perform special exchange on range ($$$1, 4$$$)$$$[1, 2, 3, 4, 5, 6, 7]$$$"}, "positive_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(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}"}, {"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"} {"nl": {"description": "Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing \"Cat's Cradle\" so now she wants to try a different game \u2014 \"Snakes and Ladders\". Unfortunately, she already killed all the snakes, so there are only ladders left now. The game is played on a $$$10 \\times 10$$$ board as follows: At the beginning of the game, the player is at the bottom left square. The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends. The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path. During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is $$$r$$$. If the Goal is less than $$$r$$$ squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly $$$r$$$ squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player chooses whether or not to climb up that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn. Some squares have a ladder in them. Ladders are only placed vertically \u2014 each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the square containing the top of the ladder also contains the bottom of another ladder, she is not allowed to use that second ladder. The numbers on the faces of the dice are 1, 2, 3, 4, 5, and 6, with each number having the same probability of being shown. Please note that: it is possible for ladders to overlap, but the player cannot switch to the other ladder while in the middle of climbing the first one; it is possible for ladders to go straight to the top row, but not any higher; it is possible for two ladders to lead to the same tile; it is possible for a ladder to lead to a tile that also has a ladder, but the player will not be able to use that second ladder if she uses the first one; the player can only climb up ladders, not climb down. Hyakugoku wants to finish the game as soon as possible. Thus, on each turn she chooses whether to climb the ladder or not optimally. Help her to determine the minimum expected number of turns the game will take.", "input_spec": "Input will consist of ten lines. The $$$i$$$-th line will contain 10 non-negative integers $$$h_{i1}, h_{i2}, \\dots, h_{i10}$$$. If $$$h_{ij}$$$ is $$$0$$$, then the tile at the $$$i$$$-th row and $$$j$$$-th column has no ladder. Otherwise, the ladder at that tile will have a height of $$$h_{ij}$$$, i.e. climbing it will lead to the tile $$$h_{ij}$$$ rows directly above. It is guaranteed that $$$0 \\leq h_{ij} < i$$$. Also, the first number of the first line and the first number of the last line always contain $$$0$$$, i.e. the Goal and the starting tile never have ladders.", "output_spec": "Print only one line containing a single floating-point number \u2014 the minimum expected number of turns Hyakugoku can take to finish the game. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$.", "sample_inputs": ["0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 3 0 0 0 4 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 4 0 0 0\n0 0 3 0 0 0 0 0 0 0\n0 0 4 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 9", "0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 6 6 6 6 6 6 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0"], "sample_outputs": ["33.0476190476", "20.2591405923", "15.9047592939"], "notes": "NoteA visualization of the path and the board from example 2 is as follows: The tile with an 'S' is the starting tile and the tile with an 'E' is the Goal.For the first example, there are no ladders.For the second example, the board looks like the one in the right part of the image (the ladders have been colored for clarity).It is possible for ladders to overlap, as is the case with the red and yellow ladders and green and blue ladders. It is also possible for ladders to go straight to the top, as is the case with the black and blue ladders. However, it is not possible for ladders to go any higher (outside of the board). It is also possible that two ladders lead to the same tile, as is the case with the red and yellow ladders. Also, notice that the red and yellow ladders lead to the tile with the orange ladder. So if the player chooses to climb either of the red and yellow ladders, they will not be able to climb the orange ladder. Finally, notice that the green ladder passes through the starting tile of the blue ladder. The player cannot transfer from the green ladder to the blue ladder while in the middle of climbing the green ladder."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val g = nm(10, 10).reverse\n val inf = 1e9\n val dp = Array.fill[Double](100, 2)(inf)\n def dfs(p: Int, canUseLadder: Int): Double = {\n if (p == 99) return 0\n if (p >= 100) return inf\n\n if (dp(p)(canUseLadder) == inf) {\n val nexts = for {\n np <- 1 + p to 6 + p\n } yield dfs(np, 1)\n\n val actives = nexts.filter(_ != inf).map(_ + 1)\n// debug(actives.mkString(\" \"))\n var res = (actives.sum + 6 - actives.length) / actives.length\n// debug(s\"dfs($p)=$res\")\n\n val r = p / 10\n val c = if (r % 2 == 0) p % 10 else 9 - p % 10\n if (canUseLadder == 1 && g(r)(c) != 0) {\n val nr = r + g(r)(c)\n val np = nr * 10 + (if (nr % 2 == 0) c else 9 - c)\n debug(s\"($r, $c), ${g(r)(c)}, ($nr, $c)=$np\")\n res = min(res, dfs(np, 0))\n }\n dp(p)(canUseLadder) = res\n }\n dp(p)(canUseLadder)\n }\n out.println(f\"${dfs(0, 1)}%.10f\")\n }\n}"}], "negative_code": [], "src_uid": "4aec5810e9942ae2fbe3ecd4fff3b468"} {"nl": {"description": "The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \\le l_j \\le r_j \\le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\\max\\limits_{i=1}^{n}b_i - \\min\\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 300, 0 \\le m \\le 300$$$) \u2014 the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^6 \\le a_i \\le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \\le l_j \\le r_j \\le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.", "output_spec": "In the first line of the output print one integer $$$d$$$ \u2014 the maximum possible value $$$\\max\\limits_{i=1}^{n}b_i - \\min\\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \\le q \\le m$$$) \u2014 the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \\dots, c_q$$$ in any order ($$$1 \\le c_k \\le m$$$) \u2014 indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\\max\\limits_{i=1}^{n}b_i - \\min\\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.", "sample_inputs": ["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"], "sample_outputs": ["6\n2\n1 4", "7\n2\n3 2", "0\n0"], "notes": "NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$."}, "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 // \u6700\u521d\u306fsegment\u304c\u5168\u90e8\u9069\u7528\u3055\u308c\u3066\u3044\u308b\u72b6\u614b\u306b\u3059\u308b\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 \u9593\u306b\u5408\u3046\u304b\uff1fBIT\u3060\u3068min\u3068\u308b\u64cd\u4f5c\u304c\u3060\u3081\u3060\u3063\u305f\u306e\u3067\u3079\u305f\u914d\u5217\n REP(N) { i =>\n val O = open(i)\n val C = close(i)\n\n // i\u304c\u6700\u5927\u306b\u306a\u3063\u305f\u3068\u4eee\u5b9a\u3057\u3066\u3001i\u304c\u542b\u307e\u308c\u308b\u30bb\u30b0\u30e1\u30f3\u30c8\u304c\u9078\u3070\u308c\u308b\u3053\u3068\u306f\u306a\u3044\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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 // \u6700\u521d\u306fsegment\u304c\u5168\u90e8\u9069\u7528\u3055\u308c\u3066\u3044\u308b\u72b6\u614b\u306b\u3059\u308b\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 \u9593\u306b\u5408\u3046\u304b\uff1fBIT\u3060\u3068min\u3068\u308b\u64cd\u4f5c\u304c\u3060\u3081\u3060\u3063\u305f\u306e\u3067\u3079\u305f\u914d\u5217\n REP(N) { i =>\n val O = open(i)\n val C = close(i)\n\n // i\u304c\u6700\u5927\u306b\u306a\u3063\u305f\u3068\u4eee\u5b9a\u3057\u3066\u3001i\u304c\u542b\u307e\u308c\u308b\u30bb\u30b0\u30e1\u30f3\u30c8\u304c\u9078\u3070\u308c\u308b\u3053\u3068\u306f\u306a\u3044\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 // \u6700\u521d\u306fsegment\u304c\u5168\u90e8\u9069\u7528\u3055\u308c\u3066\u3044\u308b\u72b6\u614b\u306b\u3059\u308b\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\u306e\u30b3\u30b9\u30c8\u304c\u6016\u3044\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 \u9593\u306b\u5408\u3046\u304b\uff1fBIT\u3060\u3068min\u3068\u308b\u64cd\u4f5c\u304c\u3060\u3081\u3060\u3063\u305f\u306e\u3067\u3079\u305f\u914d\u5217\n REP(N) { i =>\n val O = open(i)\n val C = close(i)\n\n // i\u304c\u6700\u5927\u306b\u306a\u3063\u305f\u3068\u4eee\u5b9a\u3057\u3066\u3001i\u304c\u542b\u307e\u308c\u308b\u30bb\u30b0\u30e1\u30f3\u30c8\u304c\u9078\u3070\u308c\u308b\u3053\u3068\u306f\u306a\u3044\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"} {"nl": {"description": "You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \\dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".", "input_spec": "The first line contains the single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5$$$, $$$-10^9 \\le x \\le 10^9$$$) \u2014 the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \\in \\{\\text{0}, \\text{1}\\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.", "sample_inputs": ["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"], "sample_outputs": ["3\n0\n1\n-1"], "notes": "NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$."}, "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 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 x = in.nextInt()\n val text = in.next()\n val a = text.scanLeft(0)((p,c) => {\n c match {\n case '1' => p-1\n case '0' => p+1\n case _ => 0\n }\n }\n )\n val S = a.last\n if(S == 0){\n if(a.contains(x)){\n sb.append(-1).append(System.lineSeparator())\n }else{\n sb.append(0).append(System.lineSeparator())\n }\n }else{\n val res = a.tail.count(y => {\n val k = (x-y)/S\n k >= 0 && k*S==(x-y)\n\n })\n\n val realRes = res + (if(x == 0) 1 else 0)\n sb.append(realRes).append(System.lineSeparator())\n }\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": "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 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 x = in.nextInt()\n val text = in.next()\n val a = text.scanLeft(0)((p,c) => {\n c match {\n case '1' => p-1\n case '0' => p+1\n case _ => 0\n }\n }\n )\n val S = a.last\n if(S == 0){\n if(a.contains(-x)){\n sb.append(-1).append(System.lineSeparator())\n }else{\n sb.append(0).append(System.lineSeparator())\n }\n }else{\n val res = a.tail.count(y => {\n val k = (x-y)/S\n k >= 0 && k*S==(x-y)\n\n })\n\n val realRes = res + (if(x == 0) 1 else 0)\n sb.append(realRes).append(System.lineSeparator())\n }\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}"}, {"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 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 x = in.nextInt()\n val text = in.next()\n val a = text.scanLeft(0)((p,c) => {\n c match {\n case '1' => p-1\n case '0' => p+1\n case _ => 0\n }\n }\n )\n val S = a.last\n if(S == 0){\n if(a.contains(-x)){\n sb.append(-1).append(System.lineSeparator())\n }else{\n sb.append(0).append(System.lineSeparator())\n }\n }else{\n val res = a.tail.count(y => {\n val k = (x-y)/S\n k >= 0 && k*S==(x-y)\n\n })\n\n val realRes = res + (if(x == 0) 1 else 0)\n sb.append(realRes).append(System.lineSeparator())\n }\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}"}], "src_uid": "389be6455476db86a8a5d9d5343ee35a"} {"nl": {"description": "The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k\u2009\u00d7\u2009d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.", "input_spec": "The first output line contains two space-separated integers n and l (1\u2009\u2264\u2009n,\u2009l\u2009\u2264\u2009100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1\u2009\u2264\u2009ai\u2009\u2264\u2009100).", "output_spec": "Print the single number \u2014 the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.", "sample_inputs": ["4 2\n1 2 3 4", "5 3\n5 5 7 3 1", "2 3\n1 2"], "sample_outputs": ["8", "15", "0"], "notes": "NoteIn the first sample test the required window is 2\u2009\u00d7\u20094 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves."}, "positive_code": [{"source_code": "object P038C extends App {\n val param = readLine.split(' ').map(_.toInt)\n val a = readLine.split(' ').map(_.toInt)\n val sol = new collection.mutable.ArrayBuffer[Int]()\n val maxLen = a.max\n for (i <- param(1) to maxLen) {\n sol += a.map(_/i).fold(0)(_+_) * i\n }\n println(if (sol.size == 0) 0 else sol max)\n}\n"}], "negative_code": [{"source_code": "object P038C extends App {\n val param = readLine.split(' ').map(_.toInt)\n val a = readLine.split(' ').map(_.toInt)\n println(a.map(_/param(1)).fold(0)(_+_) * param(1))\n}\n"}], "src_uid": "991516fa6f3ed5a71c547a3a50ea1a2b"} {"nl": {"description": "There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0\u2009\u2264\u2009ai\u2009\u2264\u20091\u2009000\u2009000, 1\u2009\u2264\u2009bi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai\u2009\u2260\u2009aj if i\u2009\u2260\u2009j.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of beacons that could be destroyed if exactly one beacon is added.", "sample_inputs": ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"], "sample_outputs": ["1", "3"], "notes": "NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns \u2013 starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x,\u2009y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1,\u2009y1), (x2,\u2009y2), ..., (xr,\u2009yr), that: r\u2009\u2265\u20092; for any integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009r\u2009-\u20091) the following equation |xi\u2009-\u2009xi\u2009+\u20091|\u2009+\u2009|yi\u2009-\u2009yi\u2009+\u20091|\u2009=\u20091 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.", "input_spec": "The first line contains three space-separated integers n,\u2009m,\u2009k (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009300; 2\u2009\u2264\u20092k\u2009\u2264\u2009n\u00b7m) \u2014 the number of rows, the number of columns and the number of tubes, correspondingly. ", "output_spec": "Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1,\u2009yi1,\u2009xi2,\u2009yi2,\u2009...,\u2009xiri,\u2009yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists. ", "sample_inputs": ["3 3 3", "2 3 1"], "sample_outputs": ["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"], "notes": "NotePicture for the first sample: Picture for the second sample: "}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a,\u2009b,\u2009x,\u2009y) such that 1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009<\u2009x\u2009\u2264\u2009y\u2009\u2264\u2009|s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, \"abacaba\", \"z\", \"abba\" are palindromes.A substring s[i... j] (1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009|s|) of string s = s1s2... s|s| is a string sisi\u2009+\u20091... sj. For example, substring s[2...4] of string s = \"abacaba\" equals \"bac\".", "input_spec": "The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.", "output_spec": "Output a single number \u2014 the quantity of pairs of non-overlapping palindromic substrings of s. Please do not use the %lld format specifier to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d format specifier.", "sample_inputs": ["aa", "aaa", "abacaba"], "sample_outputs": ["1", "5", "36"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "A continued fraction of height n is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height n. Check if they are equal.", "input_spec": "The first line contains two space-separated integers p,\u2009q (1\u2009\u2264\u2009q\u2009\u2264\u2009p\u2009\u2264\u20091018) \u2014 the numerator and the denominator of the first fraction. The second line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200990) \u2014 the height of the second fraction. The third line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091018) \u2014 the continued fraction. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print \"YES\" if these fractions are equal and \"NO\" otherwise.", "sample_inputs": ["9 4\n2\n2 4", "9 4\n3\n2 3 1", "9 4\n3\n1 2 4"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first sample .In the second sample .In the third sample ."}, "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}"}, {"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\")))\u2192\u7b54\u3048\u304c\u65e2\u7d04\u306b\u306a\u3063\u3066\u306a\u3044\uff01\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}"}], "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\")))\u2192\u7b54\u3048\u304c\u65e2\u7d04\u306b\u306a\u3063\u3066\u306a\u3044\uff01\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"} {"nl": {"description": "You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have $$$26$$$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the $$$i$$$-th hit deals $$$a_i$$$ units of damage to the opponent's character. To perform the $$$i$$$-th hit you have to press the button $$$s_i$$$ on your gamepad. Hits are numbered from $$$1$$$ to $$$n$$$.You know that if you press some button more than $$$k$$$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $$$a_i$$$ over all $$$i$$$ for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the damage of the $$$i$$$-th hit. The third line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters \u2014 the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).", "output_spec": "Print one integer $$$dmg$$$ \u2014 the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.", "sample_inputs": ["7 3\n1 5 16 18 7 2 10\nbaaaaca", "5 5\n2 4 1 3 1000\naaaaa", "5 4\n2 4 1 3 1000\naaaaa", "8 1\n10 15 2 1 4 8 15 16\nqqwweerr", "6 3\n14 18 9 19 2 15\ncccccc", "2 1\n10 10\nqq"], "sample_outputs": ["54", "1010", "1009", "41", "52", "10"], "notes": "NoteIn the first example you can choose hits with numbers $$$[1, 3, 4, 5, 6, 7]$$$ with the total damage $$$1 + 16 + 18 + 7 + 2 + 10 = 54$$$.In the second example you can choose all hits so the total damage is $$$2 + 4 + 1 + 3 + 1000 = 1010$$$.In the third example you can choose all hits expect the third one so the total damage is $$$2 + 4 + 3 + 1000 = 1009$$$.In the fourth example you can choose hits with numbers $$$[2, 3, 6, 8]$$$. Only this way you can reach the maximum total damage $$$15 + 2 + 8 + 16 = 41$$$.In the fifth example you can choose only hits with numbers $$$[2, 4, 6]$$$ with the total damage $$$18 + 19 + 15 = 52$$$.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $$$10$$$."}, "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": "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}"}, {"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"} {"nl": {"description": "You are given the string s of length n and the numbers p,\u2009q. Split the string s to pieces of length p and q.For example, the string \"Hello\" for p\u2009=\u20092, q\u2009=\u20093 can be split to the two strings \"Hel\" and \"lo\" or to the two strings \"He\" and \"llo\".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).", "input_spec": "The first line contains three positive integers n,\u2009p,\u2009q (1\u2009\u2264\u2009p,\u2009q\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.", "output_spec": "If it's impossible to split the string s to the strings of length p and q print the only number \"-1\". Otherwise in the first line print integer k \u2014 the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s \u2014 from left to right. If there are several solutions print any of them.", "sample_inputs": ["5 2 3\nHello", "10 9 5\nCodeforces", "6 4 5\nPrivet", "8 1 1\nabacabac"], "sample_outputs": ["2\nHe\nllo", "2\nCodef\norces", "-1", "8\na\nb\na\nc\na\nb\na\nc"], "notes": null}, "positive_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\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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "You are given a set of points $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ on the number line.Two points $$$i$$$ and $$$j$$$ can be matched with each other if the following conditions hold: neither $$$i$$$ nor $$$j$$$ is matched with any other point; $$$|x_i - x_j| \\ge z$$$. What is the maximum number of pairs of points you can match with each other?", "input_spec": "The first line contains two integers $$$n$$$ and $$$z$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le z \\le 10^9$$$) \u2014 the number of points and the constraint on the distance between matched points, respectively. The second line contains $$$n$$$ integers $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ ($$$1 \\le x_i \\le 10^9$$$).", "output_spec": "Print one integer \u2014 the maximum number of pairs of points you can match with each other.", "sample_inputs": ["4 2\n1 3 3 7", "5 5\n10 9 5 8 7"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example, you may match point $$$1$$$ with point $$$2$$$ ($$$|3 - 1| \\ge 2$$$), and point $$$3$$$ with point $$$4$$$ ($$$|7 - 3| \\ge 2$$$).In the second example, you may match point $$$1$$$ with point $$$3$$$ ($$$|5 - 10| \\ge 5$$$)."}, "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.util.Sorting\n\n // toInt\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, Z = ni()\n val A = na(N)\n sort(A)\n def test(x: Int): Boolean = {\n debug(s\"test($x)\")\n REP(x) { i =>\n val d = abs(A(N - x + i) - A(i))\n debug(s\"i:$i d:$d\")\n if (d < Z) return false\n }\n true\n }\n\n val ans = findMax(test, 0, N/2)\n out.println(ans)\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 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}"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, Z = ni()\n val A = na(N)\n sort(A)\n\n var ans = 0\n var r = 0\n val used = Array.ofDim[Boolean](N)\n REP(N) { l =>\n if (!used(l)) {\n r = max(l + 1, r)\n while (r < N && A(r) - A(l) < Z) {\n r += 1\n }\n if (r < N && A(r) - A(l) >= Z) {\n debug(s\"matched A($l):${A(l)} A($r):${A(r)}\")\n used(l) = true\n used(r) = true\n ans += 1\n r += 1 // (l, r)\u3067\u30de\u30c3\u30c1\u3057\u305f\u306e\u3067\u3053\u306er\u306f\u3082\u3046\u4f7f\u3048\u306a\u3044\n }\n }\n }\n\n out.println(ans)\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, Z = ni()\n val A = na(N)\n sort(A)\n\n var ans = 0\n var r = 0\n REP(N) { l =>\n r = max(l + 1, r)\n while(r < N && A(r) - A(l) < Z) {\n r += 1\n }\n if (r < N && A(r) - A(l) >= Z) {\n ans += 1\n r += 1 // (l, r)\u3067\u30de\u30c3\u30c1\u3057\u305f\u306e\u3067\u3053\u306er\u306f\u3082\u3046\u4f7f\u3048\u306a\u3044\n }\n }\n\n out.println(ans)\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}"}], "src_uid": "b063660572a78f25525656332a1782a8"} {"nl": {"description": "We'll call an array of n non-negative integers a[1],\u2009a[2],\u2009...,\u2009a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as \"&\", in Pascal \u2014 as \"and\".", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n, 0\u2009\u2264\u2009qi\u2009<\u2009230) describing the i-th limit.", "output_spec": "If the interesting array exists, in the first line print \"YES\" (without the quotes) and in the second line print n integers a[1],\u2009a[2],\u2009...,\u2009a[n] (0\u2009\u2264\u2009a[i]\u2009<\u2009230)\u00a0decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print \"NO\" (without the quotes) in the single line.", "sample_inputs": ["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"], "sample_outputs": ["YES\n3 3 3", "NO"], "notes": null}, "positive_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 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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.Help Luba to determine the minimum number of day when she finishes reading.It is guaranteed that the answer doesn't exceed n.Remember that there are 86400 seconds in a day.", "input_spec": "The first line contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009t\u2009\u2264\u2009106) \u2014 the number of days and the time required to read the book. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u200986400) \u2014 the time Luba has to spend on her work during i-th day.", "output_spec": "Print the minimum day Luba can finish reading the book. It is guaranteed that answer doesn't exceed n.", "sample_inputs": ["2 2\n86400 86398", "2 86400\n0 86400"], "sample_outputs": ["2", "1"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Bessie and the cows have recently been playing with \"cool\" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help!A pair (x,\u2009y) of positive integers is \"cool\" if x can be expressed as the sum of y consecutive integers (not necessarily positive). A sequence (a1,\u2009a2,\u2009...,\u2009an) is \"cool\" if the pairs (a1,\u2009a2),\u2009(a2,\u2009a3),\u2009...,\u2009(an\u2009-\u20091,\u2009an) are all cool. The cows have a sequence of n positive integers, a1,\u2009a2,\u2009...,\u2009an. In one move, they may replace some ai with any other positive integer (there are no other limits on the new value of ai). Determine the smallest number of moves needed to make the resulting sequence cool.", "input_spec": "The first line contains a single integer, n (2\u2009\u2264\u2009n\u2009\u2264\u20095000). The next line contains n space-separated integers, a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091015). Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "A single integer, the minimum number of ai that must be changed to make the sequence cool.", "sample_inputs": ["3\n6 4 1", "4\n20 6 3 4"], "sample_outputs": ["0", "2"], "notes": "NoteIn the first sample, the sequence is already cool, so we don't need to change any elements. In the second sample, we can change a2 to 5 and a3 to 10 to make (20, 5, 10, 4) which is cool. This changes 2 elements."}, "positive_code": [{"source_code": "object A extends App {\n val n = readInt\n val a = readLine split ' ' map (_.toLong)\n val dp = new Array[Int](n)\n val two = new Array[Int](n)\n\n for (i <- 0 until n) {\n var c = 0\n while (a(i) % 2 == 0) {\n c += 1\n a(i) /= 2\n }\n\n two(i) = c\n dp(i) = 1\n for (j <- 0 until i)\n if (a(j) % a(i) == 0 && (two(j)+(i-j) == two(i) || two(i) < i-j))\n dp(i) = Math.max(dp(i), dp(j) + 1)\n }\n println(n - (0 /: dp)(Math.max(_, _)))\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n val n = readInt\n val a = readLine split ' ' map (_.toLong)\n val dp = new Array[Int](n)\n val two = new Array[Int](n)\n\n for (i <- 0 until n) {\n var c = 0\n while (a(i) % 2 == 0) {\n c += 1\n a(i) /= 2\n }\n\n two(i) = c\n dp(i) = 1\n for (j <- 0 until i)\n if (a(i) % a(j) == 0 && (two(j)+(i-j) == two(i) || two(i) < i-j))\n dp(i) = Math.max(dp(i), dp(j) + 1)\n }\n println((0 /: dp)(Math.max(_, _)))\n}\n"}], "src_uid": "d796dda520a95898d57951fbac4a8366"} {"nl": {"description": "A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to $$$x$$$. Its rating is constant. There are $$$n$$$ accounts except hers, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th account's initial rating is $$$a_i$$$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these $$$n$$$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain the descriptions of all test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$2 \\le n \\le 10^3$$$, $$$-4000 \\le x \\le 4000$$$)\u00a0\u2014 the number of accounts on Codeforces and the rating of Killjoy's account. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(-4000 \\le a_i \\le 4000)$$$\u00a0\u2014 the ratings of other accounts.", "output_spec": "For each test case output the minimal number of contests needed to infect all accounts.", "sample_inputs": ["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"], "sample_outputs": ["1\n0\n2"], "notes": "NoteIn the first test case it's possible to make all ratings equal to $$$69$$$. First account's rating will increase by $$$1$$$, and second account's rating will decrease by $$$1$$$, so the sum of all changes will be equal to zero.In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to $$$4$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph() build a graph G with n vertices and 0 edges repeat swapped = false for i = 1 to n - 1 inclusive do: if a[i] > a[i + 1] then add an undirected edge in G between a[i] and a[i + 1] swap( a[i], a[i + 1] ) swapped = true end if end for until not swapped /* repeat the algorithm as long as swapped value is true. */ end procedureFor a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n distinct integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n).", "output_spec": "Output a single integer \u2014 the answer to the problem. ", "sample_inputs": ["3\n3 1 2"], "sample_outputs": ["2"], "notes": "NoteConsider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]."}, "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 @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}"}, {"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 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}"}], "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"} {"nl": {"description": "John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.", "input_spec": "A single line contains an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009105) \u2014 the number of cycles of length 3 in the required graph.", "output_spec": "In the first line print integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of vertices in the found graph. In each of next n lines print n characters \"0\" and \"1\": the i-th character of the j-th line should equal \"0\", if vertices i and j do not have an edge between them, otherwise it should equal \"1\". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal \"0\" for all i.", "sample_inputs": ["1", "10"], "sample_outputs": ["3\n011\n101\n110", "5\n01111\n10111\n11011\n11101\n11110"], "notes": null}, "positive_code": [{"source_code": "object Cycles3 extends App {\n val k = Console.readLine() toInt\n var a: Array[Array[Int]] = null \n\n \n def fullsq(n:Int) = n*(n-1)*(n-2)/6\n def numvert(n:Int) = n*(n-1)/2\n \n def leastFull():Int = {\n val seq = for {\n i <- Range(0,90)\n if fullsq(i) > k\n } yield i-1\n seq(0)\n }\n \n def maxlessvert(n:Int, kk:Int):Int = \n if (numvert(n) > kk) n-1\n else maxlessvert(n+1, kk)\n \n def fillfull(n:Int) = \n for {\n i <- 0 until n\n j <- 0 until i\n } {\n a(i)(j) = 1\n a(j)(i) = 1\n }\n \n def filladd(n:Int, start:Int) = \n for (i <- 0 until n) {\n a(i)(start) = 1\n a(start)(i) = 1\n }\n \n def printresult(d:Int) {\n println(d)\n for (i <- 0 until d) {\n val s = ((a(i) toList) take d) mkString \"\"\n println(s)\n }\n }\n \n var d0 = leastFull()\n val d = d0 + 10\n //println(\"d0,d = \" + d0 + \" \" + d)\n a = Array.fill(d,d)(0)\n fillfull(d0)\n var o = k - fullsq(d0)\n //println(\"o = \" + o)\n while (o > 0) {\n val b = maxlessvert(0, o)\n //println(\"b = \" + b)\n o = o - numvert(b)\n filladd(b, d0)\n d0 = d0 + 1\n }\n printresult(d0)\n}"}], "negative_code": [{"source_code": "object Cycles3 extends App {\n val k = Console.readLine() toInt\n var a: Array[Array[Int]] = null \n\n \n def fullsq(n:Int) = n*(n-1)*(n-2)/6\n def numvert(n:Int) = n*(n-1)/2\n \n def leastFull():Int = {\n val seq = for {\n i <- Range(0,90)\n if fullsq(i) > k\n } yield i-1\n seq(0)\n }\n \n def maxlessvert(n:Int, kk:Int):Int = \n if (numvert(n) > kk) n-1\n else maxlessvert(n+1, kk)\n \n def fillfull(n:Int) = \n for {\n i <- 0 until n\n j <- 0 until i\n } {\n a(i)(j) = 1\n a(j)(i) = 1\n }\n \n def filladd(n:Int, start:Int) = \n for (i <- 0 until n) {\n a(i)(start) = 1\n a(start)(i) = 1\n }\n \n def printresult(d:Int) {\n println(d)\n for (i <- 0 until d) {\n val s = ((a(i) toList) take d) mkString \" \"\n println(s)\n }\n }\n \n var d0 = leastFull()\n val d = d0 + 10\n //println(\"d0,d = \" + d0 + \" \" + d)\n a = Array.fill(d,d)(0)\n fillfull(d0)\n var o = k - fullsq(d0)\n //println(\"o = \" + o)\n while (o > 0) {\n val b = maxlessvert(0, o)\n //println(\"b = \" + b)\n o = o - numvert(b)\n filladd(b, d0)\n d0 = d0 + 1\n }\n printresult(d0)\n}"}], "src_uid": "d3f4c7fedd6148c28d8780142b6594f4"} {"nl": {"description": "You still have partial information about the score during the historic football match. You are given a set of pairs $$$(a_i, b_i)$$$, indicating that at some point during the match the score was \"$$$a_i$$$: $$$b_i$$$\". It is known that if the current score is \u00ab$$$x$$$:$$$y$$$\u00bb, then after the goal it will change to \"$$$x+1$$$:$$$y$$$\" or \"$$$x$$$:$$$y+1$$$\". What is the largest number of times a draw could appear on the scoreboard?The pairs \"$$$a_i$$$:$$$b_i$$$\" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10000$$$) \u2014 the number of known moments in the match. Each of the next $$$n$$$ lines contains integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \\le a_i, b_i \\le 10^9$$$), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team). All moments are given in chronological order, that is, sequences $$$x_i$$$ and $$$y_j$$$ are non-decreasing. The last score denotes the final result of the match.", "output_spec": "Print the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.", "sample_inputs": ["3\n2 0\n3 1\n3 4", "3\n0 0\n0 0\n0 0", "1\n5 4"], "sample_outputs": ["2", "1", "5"], "notes": "NoteIn the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4."}, "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 // \u70b9\u6570\u304c\u52d5\u3044\u305f\u6642\u3060\u3051\u8003\u616e\u3059\u308c\u3070\u3044\u3044\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 // \u524d\u56de\u30c9\u30ed\u30fc\u3060\u3068\uff12\u56de\u8db3\u3057\u3066\u3057\u307e\u3046\u306e\u3067\u5f15\u304b\u306a\u3044\u3068\u3044\u3051\u306a\u3044\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}"}, {"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"}], "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 // \u70b9\u6570\u304c\u52d5\u3044\u305f\u6642\u3060\u3051\u8003\u616e\u3059\u308c\u3070\u3044\u3044\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 // \u3084\u3079\u3048\u3046\u307e\u304f\u3044\u304b\u306a\u3044\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"} {"nl": {"description": "You are given a system of pipes. It consists of two rows, each row consists of $$$n$$$ pipes. The top left pipe has the coordinates $$$(1, 1)$$$ and the bottom right \u2014 $$$(2, n)$$$.There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: Types of pipes You can turn each of the given pipes $$$90$$$ degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types $$$1$$$ and $$$2$$$ can become each other and types $$$3, 4, 5, 6$$$ can become each other).You want to turn some pipes in a way that the water flow can start at $$$(1, 0)$$$ (to the left of the top left pipe), move to the pipe at $$$(1, 1)$$$, flow somehow by connected pipes to the pipe at $$$(2, n)$$$ and flow right to $$$(2, n + 1)$$$.Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes: Examples of connected pipes Let's describe the problem using some example: The first example input And its solution is below: The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $$$(1, 2)$$$ $$$90$$$ degrees clockwise, the pipe at $$$(2, 3)$$$ $$$90$$$ degrees, the pipe at $$$(1, 6)$$$ $$$90$$$ degrees, the pipe at $$$(1, 7)$$$ $$$180$$$ degrees and the pipe at $$$(2, 7)$$$ $$$180$$$ degrees. Then the flow of water can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. Each query consists of exactly three lines. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of $$$n$$$ digits from $$$1$$$ to $$$6$$$ without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding cell. See the problem statement to understand which digits correspond to which types of pipes. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For the $$$i$$$-th query print the answer for it \u2014 \"YES\" (without quotes) if it is possible to turn some pipes in a way that the water flow can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$, and \"NO\" otherwise.", "sample_inputs": ["6\n7\n2323216\n1615124\n1\n3\n4\n2\n13\n24\n2\n12\n34\n3\n536\n345\n2\n46\n54"], "sample_outputs": ["YES\nYES\nYES\nNO\nYES\nNO"], "notes": "NoteThe first query from the example is described in the problem statement."}, "positive_code": [{"source_code": "object _1234C 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 n = io.read[Int]\n val pipes = io.read[Vector, String](2)\n\n def isL(p: Int, i: Int) = pipes(p)(i) >= '3'\n\n @tailrec\n def isValid(p: Int, i: Int): Boolean =\n if (i == n) {\n p == 1\n } else if (isL(p, i)) {\n isL(1 - p, i) && isValid(1 - p, i + 1)\n } else {\n isValid(p, i + 1)\n }\n\n val ans = isValid(0, 0)\n io.writeLine(ans.toEnglish.toUpperCase())\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"}], "negative_code": [{"source_code": "object _1234C 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 n = io.read[Int]\n val pipes = io.read[Vector, String](2)\n\n @tailrec\n def isValid(p: Int, i: Int): Boolean = {\n if (i == n) {\n p == 1\n } else {\n pipes(p)(i) match {\n case c if c <= '2' => isValid(p, i + 1)\n case _ => (pipes(1 - p)(i) >= 3) && isValid(1 - p, i + 1)\n }\n }\n }\n val ans = isValid(0, 0)\n io.writeLine(ans.toEnglish.toUpperCase())\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 _1234C 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 n = io.read[Int]\n val pipes = io.read[Vector, String](2)\n\n def isL(p: Int, i: Int) = pipes(p)(i) >= '3'\n\n @tailrec\n def isValid(p: Int, i: Int): Boolean =\n if (i == n) {\n p == 1\n } else if (isL(p, i)) {\n isValid(1 - p, i + 1)\n } else {\n isValid(p, i + 1)\n }\n\n val ans = isValid(0, 0)\n io.writeLine(ans.toEnglish.toUpperCase())\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": "f34cff4302e047b1e3bfc2c79aa57be3"} {"nl": {"description": "Lunar New Year is approaching, and you bought a matrix with lots of \"crosses\".This matrix $$$M$$$ of size $$$n \\times n$$$ contains only 'X' and '.' (without quotes). The element in the $$$i$$$-th row and the $$$j$$$-th column $$$(i, j)$$$ is defined as $$$M(i, j)$$$, where $$$1 \\leq i, j \\leq n$$$. We define a cross appearing in the $$$i$$$-th row and the $$$j$$$-th column ($$$1 < i, j < n$$$) if and only if $$$M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $$$ 'X'.The following figure illustrates a cross appearing at position $$$(2, 2)$$$ in a $$$3 \\times 3$$$ matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix $$$M$$$. Two crosses are different if and only if they appear in different rows or columns.", "input_spec": "The first line contains only one positive integer $$$n$$$ ($$$1 \\leq n \\leq 500$$$), denoting the size of the matrix $$$M$$$. The following $$$n$$$ lines illustrate the matrix $$$M$$$. Each line contains exactly $$$n$$$ characters, each of them is 'X' or '.'. The $$$j$$$-th element in the $$$i$$$-th line represents $$$M(i, j)$$$, where $$$1 \\leq i, j \\leq n$$$.", "output_spec": "Output a single line containing only one integer number $$$k$$$ \u2014 the number of crosses in the given matrix $$$M$$$.", "sample_inputs": ["5\n.....\n.XXX.\n.XXX.\n.XXX.\n.....", "2\nXX\nXX", "6\n......\nX.X.X.\n.X.X.X\nX.X.X.\n.X.X.X\n......"], "sample_outputs": ["1", "0", "4"], "notes": "NoteIn the first sample, a cross appears at $$$(3, 3)$$$, so the answer is $$$1$$$.In the second sample, no crosses appear since $$$n < 3$$$, so the answer is $$$0$$$.In the third sample, crosses appear at $$$(3, 2)$$$, $$$(3, 4)$$$, $$$(4, 3)$$$, $$$(4, 5)$$$, so the answer is $$$4$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "3270260030fc56dda3e375af4dad9330"} {"nl": {"description": "The Squareland national forest is divided into equal $$$1 \\times 1$$$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $$$(x, y)$$$ of its south-west corner.Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $$$A, B, C$$$ in the forest. Initially, all plots in the forest (including the plots $$$A, B, C$$$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $$$A, B, C$$$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side. For example, $$$A=(0,0)$$$, $$$B=(1,1)$$$, $$$C=(2,2)$$$. The minimal number of plots to be cleared is $$$5$$$. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.", "input_spec": "The first line contains two integers $$$x_A$$$ and $$$y_A$$$\u00a0\u2014 coordinates of the plot $$$A$$$ ($$$0 \\leq x_A, y_A \\leq 1000$$$). The following two lines describe coordinates $$$(x_B, y_B)$$$ and $$$(x_C, y_C)$$$ of plots $$$B$$$ and $$$C$$$ respectively in the same format ($$$0 \\leq x_B, y_B, x_C, y_C \\leq 1000$$$). It is guaranteed that all three plots are distinct.", "output_spec": "On the first line print a single integer $$$k$$$\u00a0\u2014 the smallest number of plots needed to be cleaned from trees. The following $$$k$$$ lines should contain coordinates of all plots needed to be cleaned. All $$$k$$$ plots should be distinct. You can output the plots in any order. If there are multiple solutions, print any of them.", "sample_inputs": ["0 0\n1 1\n2 2", "0 0\n2 0\n1 1"], "sample_outputs": ["5\n0 0\n1 0\n1 1\n1 2\n2 2", "4\n0 0\n1 0\n1 1\n2 0"], "notes": "NoteThe first example is shown on the picture in the legend.The second example is illustrated with the following image: "}, "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 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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 // \u6642\u8a08\u56de\u308a\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 // \u91cd\u8907\u90e8\u5206\u3042\u308a\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 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}"}], "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 // \u6642\u8a08\u56de\u308a\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 // \u91cd\u8907\u90e8\u5206\u3042\u308a\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 // \u6642\u8a08\u56de\u308a\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 // \u91cd\u8907\u90e8\u5206\u3042\u308a\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"} {"nl": {"description": "The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $$$n$$$ haybale piles on the farm. The $$$i$$$-th pile contains $$$a_i$$$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) such that $$$|i-j|=1$$$ and $$$a_i>0$$$ and apply $$$a_i = a_i - 1$$$, $$$a_j = a_j + 1$$$. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile $$$1$$$ (i.e. to maximize $$$a_1$$$), and she only has $$$d$$$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $$$1$$$ if she acts optimally!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain a description of test cases \u00a0\u2014 two lines per test case. The first line of each test case contains integers $$$n$$$ and $$$d$$$ ($$$1 \\le n,d \\le 100$$$) \u2014 the number of haybale piles and the number of days, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 100$$$) \u00a0\u2014 the number of haybales in each pile.", "output_spec": "For each test case, output one integer: the maximum number of haybales that may be in pile $$$1$$$ after $$$d$$$ days if Bessie acts optimally.", "sample_inputs": ["3\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0"], "sample_outputs": ["3\n101\n0"], "notes": "NoteIn the first test case of the sample, this is one possible way Bessie can end up with $$$3$$$ haybales in pile $$$1$$$: On day one, move a haybale from pile $$$3$$$ to pile $$$2$$$ On day two, move a haybale from pile $$$3$$$ to pile $$$2$$$ On day three, move a haybale from pile $$$2$$$ to pile $$$1$$$ On day four, move a haybale from pile $$$2$$$ to pile $$$1$$$ On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $$$2$$$ to pile $$$1$$$ on the second day."}, "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 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}"}, {"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"} {"nl": {"description": "Game \"Minesweeper 1D\" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 \u2014 the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with \"*\" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play \"Minesweeper 1D\". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.", "input_spec": "The first line contains sequence of characters without spaces s1s2... sn (1\u2009\u2264\u2009n\u2009\u2264\u2009106), containing only characters \"*\", \"?\" and digits \"0\", \"1\" or \"2\". If character si equals \"*\", then the i-th cell of the field contains a bomb. If character si equals \"?\", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.", "output_spec": "Print a single integer \u2014 the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["?01???", "?", "**12", "1"], "sample_outputs": ["4", "2", "0", "0"], "notes": "NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10."}, "positive_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\n\n/**\n * Created by hama_du on 2014/03/20.\n */\nobject ProblemD extends App {\n val MOD = 1000000007L\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val c = in.nextLine().toCharArray\n\n out.println(solve())\n out.flush()\n\n def solve(): Long = {\n val n = c.length\n val dp = Array.ofDim[Long](6,n+1)\n dp(5)(0) = 1\n def add(i: Int, ai: Int, base: Long) {\n if (c(i) == '?') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n } else {\n if (ai == 0) {\n if (c(i) == '0') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n } else if (ai == 1 || ai == 2) {\n if (c(i) == '1') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n } else if (ai == 3) {\n if (c(i) == '2') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n } else {\n if (c(i) == '*') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n }\n }\n }\n\n // 0:0\n // 1:1/left\n // 2:1/right\n // 3:2\n // 4:bomb\n for (i <- 0 until n) {\n for (j <- 0 until 6) {\n val base = dp(j)(i)\n if (j == 0) {\n add(i, 0, base)\n add(i, 2, base)\n } else if (j == 1) {\n add(i, 0, base)\n add(i, 2, base)\n } else if (j == 2) {\n add(i, 4, base)\n } else if (j == 3) {\n add(i, 4, base)\n } else if (j == 4) {\n add(i, 1, base)\n add(i, 3, base)\n add(i, 4, base)\n } else {\n add(i, 0, base)\n add(i, 2, base)\n add(i, 4, base)\n }\n }\n }\n (dp(0)(n) + dp(1)(n) + dp(4)(n)) % MOD\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport java.io.PrintWriter\n\n/**\n * Created by hama_du on 2014/03/20.\n */\nobject ProblemD extends App {\n val MOD = 1000000007\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val c = in.nextLine().toCharArray\n\n out.println(solve())\n out.flush()\n\n def solve(): Long = {\n val n = c.length\n val dp = Array.ofDim[Long](6,n+1)\n dp(5)(0) = 1\n def add(i: Int, ai: Int, base: Long) {\n if (c(i) == '?') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n } else {\n if (ai == 0) {\n if (c(i) == '0') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n } else if (ai == 1 || ai == 2) {\n if (c(i) == '1') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n } else if (ai == 3) {\n if (c(i) == '2') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n } else {\n if (c(i) == '*') {\n dp(ai)(i+1) += base\n dp(ai)(i+1) %= MOD\n }\n }\n }\n }\n\n // 0:0\n // 1:1/left\n // 2:1/right\n // 3:2\n // 4:bomb\n for (i <- 0 until n) {\n for (j <- 0 until 6) {\n val base = dp(j)(i)\n if (j == 0) {\n add(i, 0, base)\n add(i, 2, base)\n } else if (j == 1) {\n add(i, 0, base)\n add(i, 2, base)\n } else if (j == 2) {\n add(i, 4, base)\n } else if (j == 3) {\n add(i, 4, base)\n } else if (j == 4) {\n add(i, 1, base)\n add(i, 2, base)\n add(i, 4, base)\n } else {\n add(i, 0, base)\n add(i, 2, base)\n add(i, 4, base)\n }\n }\n }\n (dp(0)(n) + dp(1)(n) + dp(4)(n)) % MOD\n }\n}"}], "src_uid": "c16c49baf7b2d179764871204475036e"} {"nl": {"description": "Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?", "input_spec": "The only line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910100\u2009000).", "output_spec": "Print the n-th even-length palindrome number.", "sample_inputs": ["1", "10"], "sample_outputs": ["11", "1001"], "notes": "NoteThe first 10 even-length palindrome numbers are 11,\u200922,\u200933,\u2009... ,\u200988,\u200999 and 1001."}, "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": "object B {\n def main(args: Array[String]) {\n val n = readLine\n println(n + n.reverse)\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"} {"nl": {"description": "A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of testcases. The description of each test consists of one line containing one string consisting of six digits.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output \"YES\" if the given ticket is lucky, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["5\n213132\n973894\n045207\n000000\n055776"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteIn the first test case, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is \"YES\".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is \"NO\".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is \"YES\"."}, "positive_code": [{"source_code": "object Lucky {\n def main(args: Array[String]) = {\n val num = io.StdIn.readInt\n for (_ <- 1 to num) {\n println(goodNum(io.StdIn.readLine) match {\n case true => \"YES\"\n case false => \"NO\"\n })\n }\n }\n def goodNum(num: String) = {\n val firstPart: String = num.substring(0, 3)\n val secondPart: String = num.substring(3, 6)\n val sums: List[Int] = List(firstPart, secondPart).map { s =>\n s.foldLeft(0) { (total, char) => \n total + Integer.parseInt(char.toString)\n }\n }\n sums(0) == sums(1)\n }\n}\n\n\n"}], "negative_code": [], "src_uid": "c7a5b4a015e28dd3759569bbdc130e93"} {"nl": {"description": "Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.", "input_spec": "The first line contains a single integer $$$l$$$ ($$$2 \\le l \\le 100\\,000$$$)\u00a0\u2014 the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.", "output_spec": "Print a single integer\u00a0\u2014 the smallest number Dima can obtain.", "sample_inputs": ["7\n1234567", "3\n101"], "sample_outputs": ["1801", "11"], "notes": "NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into \"1\" and \"01\" since the numbers can't start with zeros."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "negative_code": [], "src_uid": "08bce37778b7bfe478340d5c222ae362"} {"nl": {"description": "You are given a sequence $$$a_1, a_2, \\dots, a_n$$$ consisting of $$$n$$$ pairwise distinct positive integers.Find $$$\\left\\lfloor \\frac n 2 \\right\\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that: $$$x \\neq y$$$; $$$x$$$ and $$$y$$$ appear in $$$a$$$; $$$x~mod~y$$$ doesn't appear in $$$a$$$. Note that some $$$x$$$ or $$$y$$$ can belong to multiple pairs.$$$\\lfloor x \\rfloor$$$ denotes the floor function\u00a0\u2014 the largest integer less than or equal to $$$x$$$. $$$x~mod~y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the sequence. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$). All numbers in the sequence are pairwise distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "The answer for each testcase should contain $$$\\left\\lfloor \\frac n 2 \\right\\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that $$$x \\neq y$$$, $$$x$$$ and $$$y$$$ appear in $$$a$$$ and $$$x~mod~y$$$ doesn't appear in $$$a$$$. Print the pairs one after another. You can print the pairs in any order. However, the order of numbers in the pair should be exactly such that the first number is $$$x$$$ and the second number is $$$y$$$. All pairs should be pairwise distinct. If there are multiple solutions, print any of them.", "sample_inputs": ["4\n2\n1 4\n4\n2 8 3 4\n5\n3 8 5 9 7\n6\n2 7 5 3 4 8"], "sample_outputs": ["4 1\n8 2\n8 4\n9 5\n7 5\n8 7\n4 3\n5 2"], "notes": "NoteIn the first testcase there are only two pairs: $$$(1, 4)$$$ and $$$(4, 1)$$$. $$$\\left\\lfloor \\frac 2 2 \\right\\rfloor=1$$$, so we have to find one pair. $$$1~mod~4=1$$$, and $$$1$$$ appears in $$$a$$$, so that pair is invalid. Thus, the only possible answer is a pair $$$(4, 1)$$$.In the second testcase, we chose pairs $$$8~mod~2=0$$$ and $$$8~mod~4=0$$$. $$$0$$$ doesn't appear in $$$a$$$, so that answer is valid. There are multiple possible answers for that testcase.In the third testcase, the chosen pairs are $$$9~mod~5=4$$$ and $$$7~mod~5=2$$$. Neither $$$4$$$, nor $$$2$$$, appears in $$$a$$$, so that answer is valid."}, "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 arr = new Array[Int](n+1)\n var mn = 1000001\n for (i <- 1 to n) {\n arr(i) = readInt()\n mn = min(mn, arr(i))\n }\n var cnt = (n/2).toInt\n for (i <- 1 to n) {\n if (arr(i) != mn) {\n if (cnt > 0) {\n cnt -= 1\n writer.println(arr(i) + \" \" + mn)\n }\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": "6d5ecac49fe1320eef1391b6d5cf5f0d"} {"nl": {"description": "Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). Each gray cell has an even number of gray neighbours. There are exactly $$$n$$$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $$$n$$$. Help him, and provide any example of a beautiful picture.To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $$$(0, 0)$$$, axes $$$0x$$$ and $$$0y$$$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.", "input_spec": "The only line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 500$$$)\u00a0\u2014 the number of gray cells with all gray neighbours in a beautiful picture.", "output_spec": "In the first line, print a single integer $$$k$$$\u00a0\u2014 the number of gray cells in your picture. For technical reasons, $$$k$$$ should not exceed $$$5 \\cdot 10^5$$$. Each of the following $$$k$$$ lines should contain two integers\u00a0\u2014 coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $$$10^9$$$ by absolute value. One can show that there exists an answer satisfying all requirements with a small enough $$$k$$$.", "sample_inputs": ["4"], "sample_outputs": ["12\n1 0\n2 0\n0 1\n1 1\n2 1\n3 1\n0 2\n1 2\n2 2\n3 2\n1 3\n2 3"], "notes": "NoteThe answer for the sample is pictured below: "}, "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 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"}, {"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"} {"nl": {"description": "The Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.", "input_spec": "The only line of the input contains three integers a,\u2009b,\u2009c (\u2009-\u20091000\u2009\u2264\u2009a,\u2009b,\u2009c\u2009\u2264\u20091000) \u2014 the coefficients of ax2\u2009+\u2009bx\u2009+\u2009c\u2009=\u20090 equation.", "output_spec": "In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10\u2009-\u20096.", "sample_inputs": ["1 30 200"], "sample_outputs": ["-10.000000000000000\n-20.000000000000000"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "2d4ad39d42b349765435b351897403da"} {"nl": {"description": "You are given $$$n$$$ chips on a number line. The $$$i$$$-th chip is placed at the integer coordinate $$$x_i$$$. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: Move the chip $$$i$$$ by $$$2$$$ to the left or $$$2$$$ to the right for free (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 2$$$ or with $$$x_i + 2$$$); move the chip $$$i$$$ by $$$1$$$ to the left or $$$1$$$ to the right and pay one coin for this move (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 1$$$ or with $$$x_i + 1$$$). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate (i.e. all $$$x_i$$$ should be equal after some sequence of moves).", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of chips. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$1 \\le x_i \\le 10^9$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th chip.", "output_spec": "Print one integer \u2014 the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate.", "sample_inputs": ["3\n1 2 3", "5\n2 2 2 3 3"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example you need to move the first chip by $$$2$$$ to the right and the second chip by $$$1$$$ to the right or move the third chip by $$$2$$$ to the left and the second chip by $$$1$$$ to the left so the answer is $$$1$$$.In the second example you need to move two chips with coordinate $$$3$$$ by $$$1$$$ to the left so the answer is $$$2$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "This problem is an extension of the problem \"Wonderful Coloring - 1\". It has quite many differences, so you should read this statement completely.Recently, Paul and Mary have found a new favorite sequence of integers $$$a_1, a_2, \\dots, a_n$$$. They want to paint it using pieces of chalk of $$$k$$$ colors. The coloring of a sequence is called wonderful if the following conditions are met: each element of the sequence is either painted in one of $$$k$$$ colors or isn't painted; each two elements which are painted in the same color are different (i.\u2009e. there's no two equal values painted in the same color); let's calculate for each of $$$k$$$ colors the number of elements painted in the color \u2014 all calculated numbers must be equal; the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E.\u2009g. consider a sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. One of the wonderful colorings of the sequence is shown in the figure. The example of a wonderful coloring of the sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence $$$a$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first one contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$, $$$1 \\le k \\le n$$$) \u2014 the length of a given sequence and the number of colors, respectively. The second one contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Output $$$t$$$ lines, each of them must contain a description of a wonderful coloring for the corresponding test case. Each wonderful coloring must be printed as a sequence of $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$0 \\le c_i \\le k$$$) separated by spaces where $$$c_i=0$$$, if $$$i$$$-th element isn't painted; $$$c_i>0$$$, if $$$i$$$-th element is painted in the $$$c_i$$$-th color. Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.", "sample_inputs": ["6\n10 3\n3 1 1 1 1 10 3 10 10 2\n4 4\n1 1 1 1\n1 1\n1\n13 1\n3 1 4 1 5 9 2 6 5 3 5 8 9\n13 2\n3 1 4 1 5 9 2 6 5 3 5 8 9\n13 3\n3 1 4 1 5 9 2 6 5 3 5 8 9"], "sample_outputs": ["1 1 0 2 3 2 2 1 3 3\n4 2 1 3\n1\n0 0 1 1 0 1 1 1 0 1 1 1 0\n2 1 2 2 1 1 1 1 2 1 0 2 2\n1 1 3 2 1 3 3 1 2 2 3 2 0"], "notes": "NoteIn the first test case, the answer is shown in the figure in the statement. The red color has number $$$1$$$, the blue color \u2014 $$$2$$$, the green \u2014 $$$3$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "Lunar New Year is approaching, and Bob is planning to go for a famous restaurant \u2014 \"Alice's\".The restaurant \"Alice's\" serves $$$n$$$ kinds of food. The cost for the $$$i$$$-th kind is always $$$c_i$$$. Initially, the restaurant has enough ingredients for serving exactly $$$a_i$$$ dishes of the $$$i$$$-th kind. In the New Year's Eve, $$$m$$$ customers will visit Alice's one after another and the $$$j$$$-th customer will order $$$d_j$$$ dishes of the $$$t_j$$$-th kind of food. The $$$(i + 1)$$$-st customer will only come after the $$$i$$$-th customer is completely served.Suppose there are $$$r_i$$$ dishes of the $$$i$$$-th kind remaining (initially $$$r_i = a_i$$$). When a customer orders $$$1$$$ dish of the $$$i$$$-th kind, the following principles will be processed. If $$$r_i > 0$$$, the customer will be served exactly $$$1$$$ dish of the $$$i$$$-th kind. The cost for the dish is $$$c_i$$$. Meanwhile, $$$r_i$$$ will be reduced by $$$1$$$. Otherwise, the customer will be served $$$1$$$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $$$1$$$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $$$0$$$.If the customer doesn't leave after the $$$d_j$$$ dishes are served, the cost for the customer will be the sum of the cost for these $$$d_j$$$ dishes.Please determine the total cost for each of the $$$m$$$ customers.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^5$$$), representing the number of different kinds of food and the number of customers, respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^7$$$), where $$$a_i$$$ denotes the initial remain of the $$$i$$$-th kind of dishes. The third line contains $$$n$$$ positive integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\leq c_i \\leq 10^6$$$), where $$$c_i$$$ denotes the cost of one dish of the $$$i$$$-th kind. The following $$$m$$$ lines describe the orders of the $$$m$$$ customers respectively. The $$$j$$$-th line contains two positive integers $$$t_j$$$ and $$$d_j$$$ ($$$1 \\leq t_j \\leq n$$$, $$$1 \\leq d_j \\leq 10^7$$$), representing the kind of food and the number of dishes the $$$j$$$-th customer orders, respectively.", "output_spec": "Print $$$m$$$ lines. In the $$$j$$$-th line print the cost for the $$$j$$$-th customer.", "sample_inputs": ["8 5\n8 6 2 1 4 5 7 5\n6 3 3 2 6 2 3 2\n2 8\n1 4\n4 7\n3 4\n6 10", "6 6\n6 6 6 6 6 6\n6 66 666 6666 66666 666666\n1 6\n2 6\n3 6\n4 6\n5 6\n6 66", "6 6\n6 6 6 6 6 6\n6 66 666 6666 66666 666666\n1 6\n2 13\n3 6\n4 11\n5 6\n6 6"], "sample_outputs": ["22\n24\n14\n10\n39", "36\n396\n3996\n39996\n399996\n0", "36\n11058\n99996\n4333326\n0\n0"], "notes": "NoteIn the first sample, $$$5$$$ customers will be served as follows. Customer $$$1$$$ will be served $$$6$$$ dishes of the $$$2$$$-nd kind, $$$1$$$ dish of the $$$4$$$-th kind, and $$$1$$$ dish of the $$$6$$$-th kind. The cost is $$$6 \\cdot 3 + 1 \\cdot 2 + 1 \\cdot 2 = 22$$$. The remain of the $$$8$$$ kinds of food will be $$$\\{8, 0, 2, 0, 4, 4, 7, 5\\}$$$. Customer $$$2$$$ will be served $$$4$$$ dishes of the $$$1$$$-st kind. The cost is $$$4 \\cdot 6 = 24$$$. The remain will be $$$\\{4, 0, 2, 0, 4, 4, 7, 5\\}$$$. Customer $$$3$$$ will be served $$$4$$$ dishes of the $$$6$$$-th kind, $$$3$$$ dishes of the $$$8$$$-th kind. The cost is $$$4 \\cdot 2 + 3 \\cdot 2 = 14$$$. The remain will be $$$\\{4, 0, 2, 0, 4, 0, 7, 2\\}$$$. Customer $$$4$$$ will be served $$$2$$$ dishes of the $$$3$$$-rd kind, $$$2$$$ dishes of the $$$8$$$-th kind. The cost is $$$2 \\cdot 3 + 2 \\cdot 2 = 10$$$. The remain will be $$$\\{4, 0, 0, 0, 4, 0, 7, 0\\}$$$. Customer $$$5$$$ will be served $$$7$$$ dishes of the $$$7$$$-th kind, $$$3$$$ dishes of the $$$1$$$-st kind. The cost is $$$7 \\cdot 3 + 3 \\cdot 6 = 39$$$. The remain will be $$$\\{1, 0, 0, 0, 4, 0, 0, 0\\}$$$.In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $$$6$$$ dishes of the second kind, so the cost is $$$66 \\cdot 6 = 396$$$.In the third sample, some customers may not be served what they order. For example, the second customer is served $$$6$$$ dishes of the second kind, $$$6$$$ of the third and $$$1$$$ of the fourth, so the cost is $$$66 \\cdot 6 + 666 \\cdot 6 + 6666 \\cdot 1 = 11058$$$."}, "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.util.Comparator\n val N, M = ni()\n val A, C = na(N)\n val cheap = Array.ofDim[Integer](N)\n REP(N) { i =>\n cheap(i) = i\n }\n\n java.util.Arrays.sort(cheap, new Comparator[Integer] {\n override def compare(o1: Integer, o2: Integer): Int = {\n if (C(o1) == C(o2)) Integer.compare(o1, o2)\n else Integer.compare(C(o1), C(o2))\n }\n })\n var ptr = 0\n\n // debug(cheap.mkString(\" \"))\n\n REP(M) { _ =>\n var cost = 0L\n val t = ni() - 1\n var d = ni()\n\n def eat(t: Int): Unit = {\n val num = min(d, A(t))\n // debug(s\"eat $t $num\")\n cost += num.toLong * C(t)\n d -= num\n A(t) -= num\n }\n\n eat(t)\n\n while (d > 0 && ptr < N) {\n eat(cheap(ptr))\n if (A(cheap(ptr)) == 0) ptr += 1\n }\n\n // debug(A)\n if (d > 0) out.println(0)\n else out.println(cost)\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}"}], "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.Comparator\n val N, M = ni()\n val A, C = na(N)\n val cheap = Array.ofDim[Integer](N)\n REP(N) { i =>\n cheap(i) = i\n }\n\n java.util.Arrays.sort(cheap, new Comparator[Integer] {\n override def compare(o1: Integer, o2: Integer): Int = {\n if (C(o1) == C(o2)) Integer.compare(o1, o2)\n else Integer.compare(C(o1), C(o2))\n }\n })\n var ptr = 0\n\n// debug(cheap.mkString(\" \"))\n\n REP(M) { _ =>\n var cost = 0L\n val t = ni() - 1\n var d = ni()\n\n def eat(t: Int): Unit = {\n val num = min(d, A(t))\n// debug(s\"eat $t $num\")\n cost += num * C(t)\n d -= num\n A(t) -= num\n }\n\n eat(t)\n\n while (d > 0 && ptr < N) {\n eat(cheap(ptr))\n if (A(cheap(ptr)) == 0) ptr += 1\n }\n\n// debug(A)\n if (d > 0) out.println(0)\n else out.println(cost)\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": "2553ffea6d74fded12128e9db0db85dc"} {"nl": {"description": "In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array $$$a[1 \\ldots n] = [a_1, a_2, \\ldots, a_n]$$$.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[3, 4, 4]$$$ currently in the deque, adding an element $$$1$$$ to the beginning will produce the sequence $$$[\\color{red}{1}, 3, 4, 4]$$$, and adding the same element to the end will produce $$$[3, 4, 4, \\color{red}{1}]$$$.The elements of the array are sequentially added to the initially empty deque, starting with $$$a_1$$$ and finishing with $$$a_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array $$$a = [3, 7, 5, 5]$$$, one of the possible sequences of actions looks like this: $$$\\quad$$$ 1.add $$$3$$$ to the beginning of the deque:deque has a sequence $$$[\\color{red}{3}]$$$ in it;$$$\\quad$$$ 2.add $$$7$$$ to the end of the deque:deque has a sequence $$$[3, \\color{red}{7}]$$$ in it;$$$\\quad$$$ 3.add $$$5$$$ to the end of the deque:deque has a sequence $$$[3, 7, \\color{red}{5}]$$$ in it;$$$\\quad$$$ 4.add $$$5$$$ to the beginning of the deque:deque has a sequence $$$[\\color{red}{5}, 3, 7, 5]$$$ in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence $$$d$$$ is a pair of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$d_i > d_j$$$. For example, the array $$$d = [5, 3, 7, 5]$$$ has exactly two inversions\u00a0\u2014 $$$(1, 2)$$$ and $$$(3, 4)$$$, since $$$d_1 = 5 > 3 = d_2$$$ and $$$d_3 = 7 > 5 = d_4$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 array size. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \\le a_i \\le 10^9$$$)\u00a0\u2014 elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer\u00a0\u2014 the minimal possible number of inversions in the deque after executing the described algorithm.", "sample_inputs": ["6\n4\n3 7 5 5\n3\n3 2 1\n3\n3 1 2\n4\n-1 2 2 -1\n4\n4 5 1 3\n5\n1 3 1 3 2"], "sample_outputs": ["2\n0\n1\n0\n1\n2"], "notes": "NoteOne of the ways to get the sequence $$$[5, 3, 7, 5]$$$ in the deque, containing only two inversions, from the initial array $$$[3, 7, 5, 5]$$$ (the first sample test case) is described in the problem statement. Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence $$$[3, 7, 5, 5]$$$, also containing exactly two inversions, will be in the deque as-is."}, "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 value: Int, var ind: Int)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n return value.compareTo(that.value)\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 pa = new Array[pair](n)\n val arr = new Array[Int](n)\n for (i <- 0 until n) {\n arr(i) = readInt()\n pa(i) = pair(value = arr(i), ind = i)\n }\n quickSort(pa)\n val ind = new Array[Int](n)\n var cnt = 1\n for (i <- 0 until n) {\n if (i > 0 && pa(i).value != pa(i-1).value)\n cnt += 1\n ind(pa(i).ind) = cnt\n }\n val sum = fenwick(n)\n var ans = 0L\n for (i <- 0 until n) {\n val l = sum.query(ind(i)-1)\n val r = i - sum.query(ind(i))\n ans += min(l, r)\n sum.update(ind(i), 1L)\n }\n writer.println(ans)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "aa78a750cac45117f7b4313928c50f76"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ of positive integers, with length $$$n$$$ and $$$m$$$ respectively. Let $$$c$$$ be an $$$n \\times m$$$ matrix, where $$$c_{i,j} = a_i \\cdot b_j$$$. You need to find a subrectangle of the matrix $$$c$$$ such that the sum of its elements is at most $$$x$$$, and its area (the total number of elements) is the largest possible.Formally, you need to find the largest number $$$s$$$ such that it is possible to choose integers $$$x_1, x_2, y_1, y_2$$$ subject to $$$1 \\leq x_1 \\leq x_2 \\leq n$$$, $$$1 \\leq y_1 \\leq y_2 \\leq m$$$, $$$(x_2 - x_1 + 1) \\times (y_2 - y_1 + 1) = s$$$, and $$$$$$\\sum_{i=x_1}^{x_2}{\\sum_{j=y_1}^{y_2}{c_{i,j}}} \\leq x.$$$$$$", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 2000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 2000$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \\ldots, b_m$$$ ($$$1 \\leq b_i \\leq 2000$$$). The fourth line contains a single integer $$$x$$$ ($$$1 \\leq x \\leq 2 \\cdot 10^{9}$$$).", "output_spec": "If it is possible to choose four integers $$$x_1, x_2, y_1, y_2$$$ such that $$$1 \\leq x_1 \\leq x_2 \\leq n$$$, $$$1 \\leq y_1 \\leq y_2 \\leq m$$$, and $$$\\sum_{i=x_1}^{x_2}{\\sum_{j=y_1}^{y_2}{c_{i,j}}} \\leq x$$$, output the largest value of $$$(x_2 - x_1 + 1) \\times (y_2 - y_1 + 1)$$$ among all such quadruplets, otherwise output $$$0$$$.", "sample_inputs": ["3 3\n1 2 3\n1 2 3\n9", "5 1\n5 4 2 4 5\n2\n5"], "sample_outputs": ["4", "1"], "notes": "NoteMatrix from the first sample and the chosen subrectangle (of blue color): Matrix from the second sample and the chosen subrectangle (of blue color): "}, "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"}, {"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"}], "negative_code": [], "src_uid": "b100573dfd15cf99842996d91bf26f5f"} {"nl": {"description": "Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$=\"abac\", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: \"ab\", \"ba\", \"ac\". Therefore, the string $$$b$$$=\"abbaac\".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.", "input_spec": "The first line contains a single positive integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \\le |b| \\le 100$$$)\u00a0\u2014 the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.", "output_spec": "Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.", "sample_inputs": ["4\nabbaac\nac\nbccddaaf\nzzzzzzzzzz"], "sample_outputs": ["abac\nac\nbcdaf\nzzzzzz"], "notes": "NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$=\"ac\", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$=\"bcdaf\", substrings of length $$$2$$$ of string $$$a$$$ are: \"bc\", \"cd\", \"da\", \"af\", so the string $$$b$$$=\"bccddaaf\"."}, "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": "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"}, {"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"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. Each of $$$a_i$$$ has between $$$3$$$ and $$$5$$$ divisors. Consider $$$a = \\prod a_i$$$\u00a0\u2014 the product of all input integers. Find the number of divisors of $$$a$$$. As this number may be very large, print it modulo prime number $$$998244353$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 500$$$)\u00a0\u2014 the number of numbers. Each of the next $$$n$$$ lines contains an integer $$$a_i$$$ ($$$1 \\leq a_i \\leq 2\\cdot 10^{18}$$$). It is guaranteed that the number of divisors of each $$$a_i$$$ is between $$$3$$$ and $$$5$$$.", "output_spec": "Print a single integer $$$d$$$\u00a0\u2014 the number of divisors of the product $$$a_1 \\cdot a_2 \\cdot \\dots \\cdot a_n$$$ modulo $$$998244353$$$. Hacks input For hacks, the input needs to be provided in a special format. The first line contains an integer $$$n$$$\u00a0($$$1 \\leq n \\leq 500$$$)\u00a0\u2014 the number of numbers. Each of the next $$$n$$$ lines contains a prime factorization of $$$a_i$$$. The line contains an integer $$$k_i$$$\u00a0($$$2 \\leq k_i \\leq 4$$$)\u00a0\u2014 the number of prime factors of $$$a_i$$$ and $$$k_i$$$ integers $$$p_{i,j}$$$\u00a0($$$2 \\leq p_{i,j} \\leq 2 \\cdot 10^{18}$$$) where $$$p_{i,j}$$$ is the $$$j$$$-th prime factor of $$$a_i$$$. Before supplying the input to the contestant, $$$a_i = \\prod p_{i,j}$$$ are calculated. Note that each $$$p_{i,j}$$$ must be prime, each computed $$$a_i$$$ must satisfy $$$a_i \\leq 2\\cdot10^{18}$$$ and must have between $$$3$$$ and $$$5$$$ divisors. The contestant will be given only $$$a_i$$$, and not its prime factorization. For example, you need to use this test to get the first sample: 32 3 32 3 52 11 13", "sample_inputs": ["3\n9\n15\n143", "1\n7400840699802997", "8 \n4606061759128693\n4606066102679989\n4606069767552943\n4606063116488033\n4606063930903637\n4606064745319241\n4606063930904021\n4606065559735517", "3\n4\n8\n16"], "sample_outputs": ["32", "4", "1920", "10"], "notes": "NoteIn the first case, $$$a = 19305$$$. Its divisors are $$$1, 3, 5, 9, 11, 13, 15, 27, 33, 39, 45, 55, 65, 99, 117, 135, 143, 165, 195, 297, 351, 429, 495, 585, 715, 1287, 1485, 1755, 2145, 3861, 6435, 19305$$$\u00a0\u2014 a total of $$$32$$$.In the second case, $$$a$$$ has four divisors: $$$1$$$, $$$86028121$$$, $$$86028157$$$, and $$$7400840699802997 $$$.In the third case $$$a = 202600445671925364698739061629083877981962069703140268516570564888699 375209477214045102253766023072401557491054453690213483547$$$.In the fourth case, $$$a=512=2^9$$$, so answer equals to $$$10$$$."}, "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 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"}, {"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"} {"nl": {"description": "You are given a chessboard of size $$$n \\times n$$$. It is filled with numbers from $$$1$$$ to $$$n^2$$$ in the following way: the first $$$\\lceil \\frac{n^2}{2} \\rceil$$$ numbers from $$$1$$$ to $$$\\lceil \\frac{n^2}{2} \\rceil$$$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $$$n^2 - \\lceil \\frac{n^2}{2} \\rceil$$$ numbers from $$$\\lceil \\frac{n^2}{2} \\rceil + 1$$$ to $$$n^2$$$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $$$\\lceil\\frac{x}{y}\\rceil$$$ means division $$$x$$$ by $$$y$$$ rounded up.For example, the left board on the following picture is the chessboard which is given for $$$n=4$$$ and the right board is the chessboard which is given for $$$n=5$$$. You are given $$$q$$$ queries. The $$$i$$$-th query is described as a pair $$$x_i, y_i$$$. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n \\le 10^9$$$, $$$1 \\le q \\le 10^5$$$) \u2014 the size of the board and the number of queries. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th line contains two integers $$$x_i, y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$) \u2014 description of the $$$i$$$-th query.", "output_spec": "For each query from $$$1$$$ to $$$q$$$ print the answer to this query. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Queries are numbered from $$$1$$$ to $$$q$$$ in order of the input.", "sample_inputs": ["4 5\n1 1\n4 4\n4 3\n3 2\n2 4", "5 4\n2 1\n4 2\n3 3\n3 4"], "sample_outputs": ["1\n8\n16\n13\n4", "16\n9\n7\n20"], "notes": "NoteAnswers to the queries from examples are on the board in the picture from the problem statement."}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"}, {"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"}], "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"} {"nl": {"description": "Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.In his favorite math class, the teacher taught him the following interesting definitions.A parenthesis sequence is a string, containing only characters \"(\" and \")\".A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, parenthesis sequences \"()()\", \"(())\" are correct (the resulting expressions are: \"(1+1)+(1+1)\", \"((1+1)+1)\"), while \")(\" and \")\" are not. Note that the empty string is a correct parenthesis sequence by definition.We define that $$$|s|$$$ as the length of string $$$s$$$. A strict prefix $$$s[1\\dots l]$$$ $$$(1\\leq l< |s|)$$$ of a string $$$s = s_1s_2\\dots s_{|s|}$$$ is string $$$s_1s_2\\dots s_l$$$. Note that the empty string and the whole string are not strict prefixes of any string by the definition.Having learned these definitions, he comes up with a new problem. He writes down a string $$$s$$$ containing only characters \"(\", \")\" and \"?\". And what he is going to do, is to replace each of the \"?\" in $$$s$$$ independently by one of \"(\" and \")\" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.", "input_spec": "The first line contains a single integer $$$|s|$$$ ($$$1\\leq |s|\\leq 3 \\cdot 10^5$$$), the length of the string. The second line contains a string $$$s$$$, containing only \"(\", \")\" and \"?\".", "output_spec": "A single line contains a string representing the answer. If there are many solutions, any of them is acceptable. If there is no answer, print a single line containing \":(\" (without the quotes).", "sample_inputs": ["6\n(?????", "10\n(???(???(?"], "sample_outputs": ["(()())", ":("], "notes": "NoteIt can be proved that there is no solution for the second sample, so print \":(\"."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "You are given $$$n$$$ segments on a coordinate axis $$$OX$$$. The $$$i$$$-th segment has borders $$$[l_i; r_i]$$$. All points $$$x$$$, for which $$$l_i \\le x \\le r_i$$$ holds, belong to the $$$i$$$-th segment.Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.Two segments $$$[l_i; r_i]$$$ and $$$[l_j; r_j]$$$ are non-intersecting if they have no common points. For example, segments $$$[1; 2]$$$ and $$$[3; 4]$$$, $$$[1; 3]$$$ and $$$[5; 5]$$$ are non-intersecting, while segments $$$[1; 2]$$$ and $$$[2; 3]$$$, $$$[1; 2]$$$ and $$$[2; 2]$$$ are intersecting.The segment $$$[l_i; r_i]$$$ lies inside the segment $$$[l_j; r_j]$$$ if $$$l_j \\le l_i$$$ and $$$r_i \\le r_j$$$. For example, segments $$$[2; 2]$$$, $$$[2, 3]$$$, $$$[3; 4]$$$ and $$$[2; 4]$$$ lie inside the segment $$$[2; 4]$$$, while $$$[2; 5]$$$ and $$$[1; 4]$$$ are not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 3000$$$) \u2014 the number of segments. The next $$$n$$$ lines describe segments. The $$$i$$$-th segment is given as two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le 2 \\cdot 10^5$$$), where $$$l_i$$$ is the left border of the $$$i$$$-th segment and $$$r_i$$$ is the right border of the $$$i$$$-th segment. Additional constraint on the input: there are no duplicates in the list of segments. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3000$$$ ($$$\\sum n \\le 3000$$$).", "output_spec": "For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.", "sample_inputs": ["4\n4\n1 5\n2 4\n2 3\n3 4\n5\n1 5\n2 3\n2 5\n3 5\n2 2\n3\n1 3\n2 4\n2 3\n7\n1 10\n2 8\n2 5\n3 4\n4 4\n6 8\n7 7"], "sample_outputs": ["3\n4\n2\n7"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contests._1399\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject YetAnotherSegmentsSubset {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val input: Array[Array[Int]] = new Array[Array[Int]](n) // l and r\n input.indices.foreach(input(_) = io.StdIn.readLine.split(\" \").map(_.toInt))\n\n val pairs = {\n val sorted = input.sortWith { (first, second) => // in place\n val fr = first(1)\n val sr = second(1)\n if (fr == sr) {\n val fl = first(0)\n val sl = second(0)\n fl >= sl\n } else fr < sr\n }\n\n val result = new Array[(Int, Int, Int)](n)\n (0 until n).foreach(i => result(i) = (sorted(i)(0), sorted(i)(1), i))\n result\n }\n\n val subSegments: Array[Array[(Int, Int, Int)]] = {\n val subs = Array.fill[ArrayBuffer[(Int, Int, Int)]](n)(ArrayBuffer.empty)\n\n for (i <- 0 until n) {\n val fi = pairs(i)._1\n var j = i - 1\n while (j >= 0 && pairs(j)._2 >= fi) {\n if (pairs(j)._1 >= fi) subs(i) += pairs(j)\n j -= 1\n }\n }\n\n subs.map(_.toArray.reverse)\n }\n\n val cache = Array.fill[Int](n + 1)(-1) // sub-segment result for each interval\n\n def solveAndCacheAtIdx(seq: Array[(Int, Int, Int)], idx: Int): Int = {\n if (seq.isEmpty) 0\n else if (cache(idx) != -1) cache(idx)\n else {\n val dp = new Array[Int](seq.length)\n for (i <- seq.indices) {\n val pos = seq(i)._3\n dp(i) = 1 + solveAndCacheAtIdx(subSegments(pos), pos) + {\n\n val key = seq(i)._1\n\n var l = 0\n var j = i - 1\n\n while (l <= j) {\n val m = (l + j) / 2\n if (seq(m)._2 >= key) j = m - 1\n else l = m + 1\n }\n\n if (j >= 0) dp(j) else 0\n }\n\n dp(i) = dp(i) max (if (i > 0) dp(i - 1) else 0)\n }\n val result = dp.max\n cache(idx) = result\n result\n }\n }\n\n println(solveAndCacheAtIdx(pairs, n))\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1399\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject YetAnotherSegmentsSubset {\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val input: Array[Array[Int]] = new Array[Array[Int]](n) // l and r\n input.indices.foreach(input(_) = io.StdIn.readLine.split(\" \").map(_.toInt))\n\n val pairs = {\n val sorted = input.sortWith { (first, second) =>\n val fr = first(1)\n val sr = second(1)\n if (fr == sr) {\n val fl = first(0)\n val sl = second(0)\n fl >= sl\n } else fr < sr\n }\n\n val result = new Array[(Int, Int, Int)](n)\n (0 until n).foreach(i => result(i) = (sorted(i)(0), sorted(i)(1), i))\n result\n }\n\n val subSegments: Array[Array[(Int, Int, Int)]] = {\n val subs = Array.fill[ArrayBuffer[(Int, Int, Int)]](n)(ArrayBuffer.empty)\n\n for (i <- 0 until n) {\n val fi = pairs(i)._1\n var j = i - 1\n while (j >= 0 && pairs(j)._2 >= fi) {\n if (pairs(j)._1 >= fi) subs(i) += pairs(j)\n j -= 1\n }\n }\n\n subs.map(_.toArray.reverse)\n }\n\n val cache = Array.fill[Int](n + 1)(-1) // sub-segment result for each interval\n\n def solveAndCache(seq: Array[(Int, Int, Int)], idx: Int): Int = {\n if (seq.isEmpty) 0\n else if (cache(idx) != -1) cache(idx)\n else {\n val dp = new Array[Int](seq.length)\n for (i <- seq.indices) {\n val l = seq(i)._1\n val pos = seq(i)._3\n dp(i) = 1 + solveAndCache(subSegments(pos), pos) + {\n var j = i - 1\n while (j >= 0 && seq(j)._2 >= l) j -= 1\n if (j >= 0) dp(j) else 0\n }\n }\n val result = dp.max\n cache(idx) = result\n result\n }\n }\n\n println(solveAndCache(pairs, n))\n }\n }\n}\n"}], "src_uid": "0aa7c678bc06b0a305155b4a31176366"} {"nl": {"description": "There are three sticks with integer lengths $$$l_1, l_2$$$ and $$$l_3$$$.You are asked to break exactly one of them into two pieces in such a way that: both pieces have positive (strictly greater than $$$0$$$) integer length; the total length of the pieces is equal to the original length of the stick; it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle.Determine if it's possible to do that.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains three integers $$$l_1, l_2, l_3$$$ ($$$1 \\le l_i \\le 10^8$$$)\u00a0\u2014 the lengths of the sticks.", "output_spec": "For each testcase, print \"YES\" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print \"NO\". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).", "sample_inputs": ["4\n6 1 5\n2 5 2\n2 4 2\n5 5 4"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteIn the first testcase, the first stick can be broken into parts of length $$$1$$$ and $$$5$$$. We can construct a rectangle with opposite sides of length $$$1$$$ and $$$5$$$.In the second testcase, breaking the stick of length $$$2$$$ can only result in sticks of lengths $$$1, 1, 2, 5$$$, which can't be made into a rectangle. Breaking the stick of length $$$5$$$ can produce results $$$2, 3$$$ or $$$1, 4$$$ but neither of them can't be put into a rectangle.In the third testcase, the second stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$2$$$ (which is a square).In the fourth testcase, the third stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$5$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "You are given a forest \u2014 an undirected graph with $$$n$$$ vertices such that each its connected component is a tree.The diameter (aka \"longest shortest path\") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.If there are multiple correct answers, print any of them.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 1000$$$, $$$0 \\le m \\le n - 1$$$) \u2014 the number of vertices of the graph and the number of edges, respectively. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \\le v, u \\le n$$$, $$$v \\ne u$$$) \u2014 the descriptions of the edges. It is guaranteed that the given graph is a forest.", "output_spec": "In the first line print the diameter of the resulting tree. Each of the next $$$(n - 1) - m$$$ lines should contain two integers $$$v$$$ and $$$u$$$ ($$$1 \\le v, u \\le n$$$, $$$v \\ne u$$$) \u2014 the descriptions of the added edges. The resulting graph should be a tree and its diameter should be minimal possible. For $$$m = n - 1$$$ no edges are added, thus the output consists of a single integer \u2014 diameter of the given tree. If there are multiple correct answers, print any of them.", "sample_inputs": ["4 2\n1 2\n2 3", "2 0", "3 2\n1 3\n2 3"], "sample_outputs": ["2\n4 2", "1\n1 2", "2"], "notes": "NoteIn the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.Edge (1, 2) is the only option you have for the second example. The diameter is 1.You can't add any edges in the third example. The diameter is already 2."}, "positive_code": [{"source_code": "import java.util\nimport java.util.Collections\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, M = ni()\n val (from, to) = na2(M, -1)\n val g = packUGraph(N, from, to)\n\n // \u534a\u5f84\u304c\u4e00\u756a\u3067\u304b\u3044\u306e\u306b\u5168\u90e8\u3064\u306a\u3052\u308b\u306e\u304c\u304a\u3068\u304f\n val trees = centersOfForest(g).toArray\n Sorting.quickSort(trees)(Ordering.by(-_._2))\n\n val t1 = trees.head\n val newEdges = trees.drop(1) map { t2 =>\n t1._1.head -> t2._1.head\n }\n\n val newFrom, newTo = Array.ofDim[Int](N - 1)\n System.arraycopy(from, 0, newFrom, 0, M)\n System.arraycopy(to, 0, newTo, 0, M)\n REP(N - 1 - M) { i =>\n newFrom(i + M) = newEdges(i)._1\n newTo(i + M) = newEdges(i)._2\n }\n val newTree = packUGraph(N, newFrom, newTo)\n val (_, d, _) = centerOfTree(newTree)\n out.println(d)\n newEdges.foreach { case (u, v) =>\n out.println(s\"${u+1} ${v+1}\")\n }\n }\n\n /**\n * \u3059\u3067\u306b\u76f4\u5f84\u3001\u76f4\u5f84\u306e\u30ce\u30fc\u30c9\u304c\u308f\u304b\u3063\u3066\u3044\u308b\u5834\u5408\u306f\u3001\u76f4\u5f84\u306e\u534a\u5206\u3060\u3051\u89aa\u3092\u305f\u3069\u308c\u3070\u3044\u3044\u306e\u3067\u3082\u3063\u3068\u697d\u306b\u3067\u304d\u308b\n * todo *\u6ce8\u610f* \u30a8\u30c3\u30b8\u304c\u7a7a\u306e\u3068\u304d\u306b\u52d5\u304b\u306a\u3044\n * @return (\u6728\u306e\u4e2d\u5fc3\uff11\u3053or\uff12\u500b, \u76f4\u5f84, \u534a\u5f84)\n */\n def centerOfTree(t: Array[Array[Int]]): (Array[Int], Int, Int) = {\n val n = t.length\n\n var cur = 0\n var p = 0\n val queue = Array.ofDim[Int](n)\n val degree = Array.ofDim[Int](n)\n val lvl = Array.ofDim[Int](n)\n REP(n) { i =>\n degree(i) = t(i).length\n if (degree(i) == 1) {\n queue(p) = i\n p += 1\n }\n }\n\n while(cur < p) {\n val v = queue(cur)\n cur += 1\n REP(t(v).length) { i =>\n val u = t(v)(i)\n\n // parent\u3092\u63a2\u3059\n if (degree(u) > 0) {\n degree(u) -= 1\n if (degree(u) == 1) {\n lvl(u) = lvl(v) + 1\n queue(p) = u\n p += 1\n }\n }\n }\n degree(v) -= 1\n }\n\n val c1 = queue(n - 1)\n if (n >= 2 && lvl(c1) == lvl(queue(n - 2))) {\n val c2 = queue(n - 2)\n (Array(c1, c2), lvl(c1) * 2 + 1, lvl(c1) + 1)\n } else {\n (Array(c1), lvl(c1) * 2, lvl(c1))\n }\n }\n\n /**\n * @param n \u30ce\u30fc\u30c9\u6570\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 // (centers, redius)\n type Tree = (Array[Int], Int)\n\n def centersOfForest(g: Array[Array[Int]]): ArrayBuffer[Tree] = {\n val n = g.length\n\n var cur = 0\n var p = 0\n val queue = Array.ofDim[Int](n)\n val degree = Array.ofDim[Int](n)\n val lvl = Array.ofDim[Int](n)\n val last = Array.ofDim[Int](n) // \u6700\u5f8c\u306b\u30a8\u30c3\u30b8\u3092\u524a\u9664\u3057\u305f\u3068\u304d\u306e\u5bfe\u306b\u306a\u308b\u30ce\u30fc\u30c9\n val res = ArrayBuffer[Tree]()\n\n REP(n) { i =>\n degree(i) = g(i).length\n if (degree(i) == 1) {\n queue(p) = i\n p += 1\n\n // \u3069\u3053\u3068\u3082\u3064\u306a\u304c\u3063\u3066\u3044\u306a\u3044\u30ce\u30fc\u30c9\u3082\u30c4\u30ea\u30fc\u3068\u307f\u306a\u3059\n } else if (degree(i) == 0) {\n res += ((Array(i), 0))\n }\n }\n\n while(cur < p) {\n val v = queue(cur)\n cur += 1\n var parent = -1\n REP(g(v).length) { i =>\n val u = g(v)(i)\n // parent\u3092\u63a2\u3059\n if (degree(u) > 0) parent = u\n }\n if (parent != -1) {\n val u = parent\n degree(u) -= 1\n if (degree(u) == 1) {\n lvl(u) = lvl(v) + 1\n queue(p) = u\n last(u) = v\n p += 1\n }\n } else {\n val c1 = v\n if (n >= 2 && lvl(c1) == lvl(last(v))) {\n val c2 = last(v)\n res += ((Array(c1, c2), lvl(c1) + 1))\n } else {\n res += ((Array(c1), lvl(c1)))\n }\n }\n degree(v) -= 1\n }\n\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[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": "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, M = ni()\n val (from, to) = na2(M, -1)\n val g = packUGraph(N, from, to)\n\n val centers = centersOfForest(g)\n val newEdges = centers zip centers.drop(1) map { case (t1, t2) =>\n t1._1.head -> t2._1.head\n }\n\n val newFrom, newTo = Array.ofDim[Int](N - 1)\n System.arraycopy(from, 0, newFrom, 0, M)\n System.arraycopy(to, 0, newTo, 0, M)\n REP(N - 1 - M) { i =>\n newFrom(i + M) = newEdges(i)._1\n newTo(i + M) = newEdges(i)._2\n }\n val newTree = packUGraph(N, newFrom, newTo)\n val (_, d, _) = centerOfTree(newTree)\n out.println(d)\n newEdges.foreach { case (u, v) =>\n out.println(s\"${u+1} ${v+1}\")\n }\n }\n\n /**\n * \u3059\u3067\u306b\u76f4\u5f84\u3001\u76f4\u5f84\u306e\u30ce\u30fc\u30c9\u304c\u308f\u304b\u3063\u3066\u3044\u308b\u5834\u5408\u306f\u3001\u76f4\u5f84\u306e\u534a\u5206\u3060\u3051\u89aa\u3092\u305f\u3069\u308c\u3070\u3044\u3044\u306e\u3067\u3082\u3063\u3068\u697d\u306b\u3067\u304d\u308b\n * todo *\u6ce8\u610f* \u30a8\u30c3\u30b8\u304c\u7a7a\u306e\u3068\u304d\u306b\u52d5\u304b\u306a\u3044\n * @return (\u6728\u306e\u4e2d\u5fc3\uff11\u3053or\uff12\u500b, \u76f4\u5f84, \u534a\u5f84)\n */\n def centerOfTree(t: Array[Array[Int]]): (Array[Int], Int, Int) = {\n val n = t.length\n\n var cur = 0\n var p = 0\n val queue = Array.ofDim[Int](n)\n val degree = Array.ofDim[Int](n)\n val lvl = Array.ofDim[Int](n)\n REP(n) { i =>\n degree(i) = t(i).length\n if (degree(i) == 1) {\n queue(p) = i\n p += 1\n }\n }\n\n while(cur < p) {\n val v = queue(cur)\n cur += 1\n REP(t(v).length) { i =>\n val u = t(v)(i)\n\n // parent\u3092\u63a2\u3059\n if (degree(u) > 0) {\n degree(u) -= 1\n if (degree(u) == 1) {\n lvl(u) = lvl(v) + 1\n queue(p) = u\n p += 1\n }\n }\n }\n degree(v) -= 1\n }\n\n val c1 = queue(n - 1)\n if (n >= 2 && lvl(c1) == lvl(queue(n - 2))) {\n val c2 = queue(n - 2)\n (Array(c1, c2), lvl(c1) * 2 + 1, lvl(c1) + 1)\n } else {\n (Array(c1), lvl(c1) * 2, lvl(c1))\n }\n }\n\n /**\n * @param n \u30ce\u30fc\u30c9\u6570\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 type Tree = (Array[Int], Int)\n\n def centersOfForest(g: Array[Array[Int]]): ArrayBuffer[Tree] = {\n val n = g.length\n\n var cur = 0\n var p = 0\n val queue = Array.ofDim[Int](n)\n val degree = Array.ofDim[Int](n)\n val lvl = Array.ofDim[Int](n)\n val last = Array.ofDim[Int](n) // \u6700\u5f8c\u306b\u30a8\u30c3\u30b8\u3092\u524a\u9664\u3057\u305f\u3068\u304d\u306e\u5bfe\u306b\u306a\u308b\u30ce\u30fc\u30c9\n val res = ArrayBuffer[Tree]()\n\n REP(n) { i =>\n degree(i) = g(i).length\n if (degree(i) == 1) {\n queue(p) = i\n p += 1\n\n // \u3069\u3053\u3068\u3082\u3064\u306a\u304c\u3063\u3066\u3044\u306a\u3044\u30ce\u30fc\u30c9\u3082\u30c4\u30ea\u30fc\u3068\u307f\u306a\u3059\n } else if (degree(i) == 0) {\n res += ((Array(i), 0))\n }\n }\n\n while(cur < p) {\n val v = queue(cur)\n cur += 1\n var parent = -1\n REP(g(v).length) { i =>\n val u = g(v)(i)\n // parent\u3092\u63a2\u3059\n if (degree(u) > 0) parent = u\n }\n if (parent != -1) {\n val u = parent\n degree(u) -= 1\n if (degree(u) == 1) {\n lvl(u) = lvl(v) + 1\n queue(p) = u\n last(u) = v\n p += 1\n }\n } else {\n val c1 = v\n if (n >= 2 && lvl(c1) == lvl(last(v))) {\n val c2 = last(v)\n res += ((Array(c1, c2), lvl(c1) * 2 + 1))\n } else {\n res += ((Array(c1), lvl(c1) * 2))\n }\n }\n degree(v) -= 1\n }\n\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[Long](as.length + 1)\n REP(as.length) { i =>\n cum(i + 1) = cum(i) + as(i)\n }\n cum\n }\n}"}], "src_uid": "90cf88fde1c23b6f3a85ee75d3a6a3ec"} {"nl": {"description": "There are n cities and n\u2009-\u20091 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can\u2019t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000)\u00a0\u2014 number of cities. Then n\u2009-\u20091 lines follow. The i-th line of these lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi)\u00a0\u2014 the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads.", "output_spec": "Print a number\u00a0\u2014 the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["4\n1 2\n1 3\n2 4", "5\n1 2\n1 3\n3 4\n2 5"], "sample_outputs": ["1.500000000000000", "2.000000000000000"], "notes": "NoteIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2."}, "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"}, {"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"}], "negative_code": [], "src_uid": "adaae163882b064bf7257e82e8832ffb"} {"nl": {"description": "Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form \"abab...\", namely there are letters 'a' on odd positions and letters 'b' on even positions.Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.Let's call a sequence of positions i,\u2009i\u2009+\u20091,\u2009...,\u2009i\u2009+\u2009m\u2009-\u20091 as occurrence of string t in s, if 1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u2009m\u2009+\u20091 and t1\u2009=\u2009si,\u2009t2\u2009=\u2009si\u2009+\u20091,\u2009...,\u2009tm\u2009=\u2009si\u2009+\u2009m\u2009-\u20091.The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the length of s. The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only. The third line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.", "output_spec": "Print the only integer\u00a0\u2014 the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.", "sample_inputs": ["5\nbb?a?\n1", "9\nab??ab???\n3"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.In the second sample using two replacements we can make string equal to \"aba?aba??\". It is impossible to get more than two occurrences."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n val n = StdIn.readInt()\n val s = StdIn.readLine()\n val m = StdIn.readInt()\n val dp = Array.ofDim[Tuple2[Int, Int]](n + 2, 2);\n val ans = Array.ofDim[Tuple2[Int, Int]](n + 2);\n val suf = Array.ofDim[Int](n + 2);\n dp(n)(0) = (0,0)\n dp(n)(1) = (0,0)\n dp(n + 1)(0) = (0,0)\n dp(n + 1)(1) = (0,0)\n ans(n) = (0,0)\n ans(n + 1) = (0,0)\n suf(n) = 0\n suf(n + 1) = 0\n\n for (i <- n - 1 to 0 by -1) {\n suf(i) = suf(i + 1)\n if(s(i) == '?')\n suf(i) += 1\n s(i) match {\n case '?' => {dp(i)(0) = (dp(i + 2)(0)._1 + 1, dp(i + 2)(0)._2 + 1); dp(i)(1) = (dp(i + 2)(1)._1 + 1, dp(i + 2)(1)._2 + 1);}\n case 'a' => {dp(i)(0) = (dp(i + 2)(0)._1 + 1, dp(i + 2)(0)._2); dp(i)(1) = (0, 0);}\n case 'b' => {dp(i)(0) = (0, 0); dp(i)(1) = (dp(i + 2)(1)._1 + 1, dp(i + 2)(1)._2);}\n }\n// println(i + \" : \" + dp(i)(0) + \" : \" + dp(i)(0))\n }\n val cnta = (m / 2) + (m % 2)\n val cntb = m - cnta\n\n for (i <- n - 1 to 0 by -1) {\n// println(i)\n ans(i) = ans(i + 1)\n// printf(dp(i)(0)._1 + \" : \" + dp(i + 1)(1)._1 + \" : \" + cnta + \" : \" + cntb)\n if(dp(i)(0)._1 >= cnta && dp(i + 1)(1)._1 >= cntb) {\n val otherAns = (1 + ans(i + m)._1, suf(i) - suf(i + m) + ans(i + m)._2)\n// println(\"other : \" + otherAns)\n if(otherAns._1 > ans(i)._1)\n ans(i) = otherAns\n else if(otherAns._1 == ans(i)._1 && otherAns._2 < ans(i)._2)\n ans(i) = otherAns\n }\n// println(\"\\n i : \" + ans(i))\n }\n println(ans(0)._2)\n}\n"}], "negative_code": [], "src_uid": "944ab87c148df0fc59ec0263d6fd8b9f"} {"nl": {"description": "You are given two arrays of integers $$$a_1, a_2, \\ldots, a_n$$$ and $$$b_1, b_2, \\ldots, b_n$$$.Let's define a transformation of the array $$$a$$$: Choose any non-negative integer $$$k$$$ such that $$$0 \\le k \\le n$$$. Choose $$$k$$$ distinct array indices $$$1 \\le i_1 < i_2 < \\ldots < i_k \\le n$$$. Add $$$1$$$ to each of $$$a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$$$, all other elements of array $$$a$$$ remain unchanged. Permute the elements of array $$$a$$$ in any order. Is it possible to perform some transformation of the array $$$a$$$ exactly once, so that the resulting array is equal to $$$b$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Descriptions of test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the size of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-100 \\le a_i \\le 100$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$-100 \\le b_i \\le 100$$$).", "output_spec": "For each test case, print \"YES\" (without quotes) if it is possible to perform a transformation of the array $$$a$$$, so that the resulting array is equal to $$$b$$$. Print \"NO\" (without quotes) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n3\n-1 1 0\n0 0 2\n1\n0\n2\n5\n1 2 3 4 5\n1 2 3 4 5"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteIn the first test case, we can make the following transformation: Choose $$$k = 2$$$. Choose $$$i_1 = 1$$$, $$$i_2 = 2$$$. Add $$$1$$$ to $$$a_1$$$ and $$$a_2$$$. The resulting array is $$$[0, 2, 0]$$$. Swap the elements on the second and third positions. In the second test case there is no suitable transformation.In the third test case we choose $$$k = 0$$$ and do not change the order of elements."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a string $$$s$$$. You need to find two non-empty strings $$$a$$$ and $$$b$$$ such that the following conditions are satisfied: Strings $$$a$$$ and $$$b$$$ are both subsequences of $$$s$$$. For each index $$$i$$$, character $$$s_i$$$ of string $$$s$$$ must belong to exactly one of strings $$$a$$$ or $$$b$$$. String $$$a$$$ is lexicographically minimum possible; string $$$b$$$ may be any possible string. Given string $$$s$$$, print any valid $$$a$$$ and $$$b$$$.Reminder:A string $$$a$$$ ($$$b$$$) is a subsequence of a string $$$s$$$ if $$$a$$$ ($$$b$$$) can be obtained from $$$s$$$ by deletion of several (possibly, zero) elements. For example, \"dores\", \"cf\", and \"for\" are subsequences of \"codeforces\", while \"decor\" and \"fork\" are not.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \\ne y$$$; in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$. ", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first and only line of each test case contains one string $$$s$$$ ($$$2 \\le |s| \\le 100$$$ where $$$|s|$$$ means the length of $$$s$$$). String $$$s$$$ consists of lowercase Latin letters.", "output_spec": "For each test case, print the strings $$$a$$$ and $$$b$$$ that satisfy the given conditions. If there are multiple answers, print any.", "sample_inputs": ["3\nfc\naaaa\nthebrightboiler"], "sample_outputs": ["c f\na aaa\nb therightboiler"], "notes": "NoteIn the first test case, there are only two choices: either $$$a =$$$ f and $$$b = $$$ c or $$$a = $$$ c and $$$b = $$$ f. And $$$a = $$$c is lexicographically smaller than $$$a = $$$ f.In the second test case, a is the only character in the string.In the third test case, it can be proven that b is the lexicographically smallest subsequence of $$$s$$$. The second string can be of two variants; one of them is given here."}, "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 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 s = readString()\n var a = (65535).toChar\n var ind = -1\n for (i <- 0 until s.length) {\n if (s(i) < a) {\n a = s(i)\n ind = i\n }\n }\n val b = s.substring(0, ind) + s.substring(ind+1, s.length)\n writer.println(a + \" \" + b)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "4a58039c5171597ecf78837e9db1d71d"} {"nl": {"description": "Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \\lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$. For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.", "input_spec": "Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Each test case contains exactly one line. The line consists of four integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$ ($$$0 \\le x \\lt y \\le 10^9$$$, $$$1 \\le a,b \\le 10^9$$$) \u2014 the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.", "output_spec": "For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position. If the two rabbits will never be at the same position simultaneously, print $$$-1$$$.", "sample_inputs": ["5\n0 10 2 3\n0 10 3 3\n900000000 1000000000 1 9999999\n1 2 1 1\n1 3 1 1"], "sample_outputs": ["2\n-1\n10\n-1\n1"], "notes": "NoteThe first case is explained in the description.In the second case, each rabbit will be at position $$$3$$$ and $$$7$$$ respectively at the $$$1$$$-st second. But in the $$$2$$$-nd second they will be at $$$6$$$ and $$$4$$$ respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main extends App {\n\n private val getSec: (Int, Int, Int, Int) => Int =\n (x, y, a, b) => {\n if ((y - x) % (a + b) == 0)\n (y - x) / (a + b)\n else\n -1\n }\n\n var n: Int = StdIn.readLine().toInt\n\n while (n != 0) {\n val line = StdIn.readLine().split(\"\\\\s\")\n\n val x = line(0).toInt\n val y = line(1).toInt\n val a = line(2).toInt\n val b = line(3).toInt\n\n println(getSec(x, y, a, b))\n\n n -= 1\n }\n\n}"}], "negative_code": [], "src_uid": "9afcf090806cc9c3b87120b1b61f8f17"} {"nl": {"description": "NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $$$\\operatorname{or} z$$$. Can you solve this problem too?You are given a 1-indexed array of $$$n$$$ integers, $$$a$$$, and an integer $$$z$$$. You can do the following operation any number (possibly zero) of times: Select a positive integer $$$i$$$ such that $$$1\\le i\\le n$$$. Then, simutaneously set $$$a_i$$$ to $$$(a_i\\operatorname{or} z)$$$ and set $$$z$$$ to $$$(a_i\\operatorname{and} z)$$$. In other words, let $$$x$$$ and $$$y$$$ respectively be the current values of $$$a_i$$$ and $$$z$$$. Then set $$$a_i$$$ to $$$(x\\operatorname{or}y)$$$ and set $$$z$$$ to $$$(x\\operatorname{and}y)$$$. Here $$$\\operatorname{or}$$$ and $$$\\operatorname{and}$$$ denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in $$$a$$$ after any number (possibly zero) of operations.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$z$$$ ($$$1\\le n\\le 2000$$$, $$$0\\le z<2^{30}$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$,$$$a_2$$$,$$$\\ldots$$$,$$$a_n$$$ ($$$0\\le a_i<2^{30}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case, print one integer \u2014 the answer to the problem.", "sample_inputs": ["5\n\n2 3\n\n3 4\n\n5 5\n\n0 2 4 6 8\n\n1 9\n\n10\n\n5 7\n\n7 15 30 29 27\n\n3 39548743\n\n10293834 10284344 13635445"], "sample_outputs": ["7\n13\n11\n31\n48234367"], "notes": "NoteIn the first test case of the sample, one optimal sequence of operations is: Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\\operatorname{or}3)=3$$$ and $$$z$$$ becomes $$$(3\\operatorname{and}3)=3$$$. Do the operation with $$$i=2$$$. Now $$$a_2$$$ becomes $$$(4\\operatorname{or}3)=7$$$ and $$$z$$$ becomes $$$(4\\operatorname{and}3)=0$$$. Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\\operatorname{or}0)=3$$$ and $$$z$$$ becomes $$$(3\\operatorname{and}0)=0$$$. After these operations, the sequence $$$a$$$ becomes $$$[3,7]$$$, and the maximum value in it is $$$7$$$. We can prove that the maximum value in $$$a$$$ can never exceed $$$7$$$, so the answer is $$$7$$$.In the fourth test case of the sample, one optimal sequence of operations is: Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(7\\operatorname{or}7)=7$$$ and $$$z$$$ becomes $$$(7\\operatorname{and}7)=7$$$. Do the operation with $$$i=3$$$. Now $$$a_3$$$ becomes $$$(30\\operatorname{or}7)=31$$$ and $$$z$$$ becomes $$$(30\\operatorname{and}7)=6$$$. Do the operation with $$$i=5$$$. Now $$$a_5$$$ becomes $$$(27\\operatorname{or}6)=31$$$ and $$$z$$$ becomes $$$(27\\operatorname{and}6)=2$$$. "}, "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 var cou = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n val z = tokenizer.nextToken().toInt\r\n val A = new Array[Long](n)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until n) {\r\n A(i) = (tokenizer.nextToken().toInt | z)\r\n }\r\n println(A.max)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "bb6168528e04156f68bde2ffc1ba828f"} {"nl": {"description": "A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle\u00a0\u2014 a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the total number of islands. The second line contains n space-separated integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the statue currently placed on the i-th island. If ai\u2009=\u20090, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0\u2009\u2264\u2009bi\u2009\u2264\u2009n\u2009-\u20091) \u2014 the desired statues of the ith island. Once again, bi\u2009=\u20090 indicates the island desires no statue. It is guaranteed that the bi are distinct.", "output_spec": "Print \"YES\" (without quotes) if the rearrangement can be done in the existing network, and \"NO\" otherwise.", "sample_inputs": ["3\n1 0 2\n2 0 1", "2\n1 0\n0 1", "4\n1 2 3 0\n0 3 2 1"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position."}, "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, 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}"}, {"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"} {"nl": {"description": "Kolya got an integer array $$$a_1, a_2, \\dots, a_n$$$. The array can contain both positive and negative integers, but Kolya doesn't like $$$0$$$, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be $$$0$$$. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $$$0$$$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $$$0$$$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 200\\,000$$$) \u2014 the number of elements in Kolya's array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^{9} \\le a_i \\le 10^{9}, a_i \\neq 0$$$) \u2014 the description of Kolya's array.", "output_spec": "Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.", "sample_inputs": ["4\n1 -5 3 2", "5\n4 -2 3 -9 2", "9\n-1 1 -1 1 -1 1 1 -1 -1", "8\n16 -5 -11 -15 10 5 4 -4"], "sample_outputs": ["1", "0", "6", "3"], "notes": "NoteConsider the first example. There is only one subsegment with the sum $$$0$$$. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer $$$1$$$ between second and third elements of the array.There are no subsegments having sum $$$0$$$ in the second example so you don't need to do anything."}, "positive_code": [{"source_code": "//package codeforces.contests._1426\n\nobject NonZeroSegments {\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val arr = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val prefix = arr.scanLeft(0L)(_ + _)\n val groups = collection.mutable.Map((0 to n).groupBy(prefix).toSeq: _*)\n val result = {\n (1 to n).foldLeft((0, 0)) { case ((acc, lastIndex), i) =>\n\n val sum = prefix(i)\n val indices = groups.getOrElse(sum, IndexedSeq.empty)\n\n val x = lastIndex - 1\n val y = i - 1\n\n @scala.annotation.tailrec\n def binarySearch(l: Int, r: Int): Boolean = {\n if (l > r) false else {\n val m = (l + r) / 2\n val key = indices(m)\n if (x <= key && key <= y) true\n else if (key < x) binarySearch(m + 1, r)\n else binarySearch(l, m - 1)\n }\n }\n\n if (binarySearch(0, indices.length - 1))\n (acc + 1, i)\n else\n (acc, lastIndex)\n\n }._1\n }\n println(result)\n }\n}\n"}], "negative_code": [], "src_uid": "05548be393d794bf106708627220b9a3"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$, both consisting only of lowercase Latin letters.The substring $$$s[l..r]$$$ is the string which is obtained by taking characters $$$s_l, s_{l + 1}, \\dots, s_r$$$ without changing the order.Each of the occurrences of string $$$a$$$ in a string $$$b$$$ is a position $$$i$$$ ($$$1 \\le i \\le |b| - |a| + 1$$$) such that $$$b[i..i + |a| - 1] = a$$$ ($$$|a|$$$ is the length of string $$$a$$$).You are asked $$$q$$$ queries: for the $$$i$$$-th query you are required to calculate the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.", "input_spec": "The first line contains three integer numbers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \\le n, m \\le 10^3$$$, $$$1 \\le q \\le 10^5$$$) \u2014 the length of string $$$s$$$, the length of string $$$t$$$ and the number of queries, respectively. The second line is a string $$$s$$$ ($$$|s| = n$$$), consisting only of lowercase Latin letters. The third line is a string $$$t$$$ ($$$|t| = m$$$), consisting only of lowercase Latin letters. Each of the next $$$q$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) \u2014 the arguments for the $$$i$$$-th query.", "output_spec": "Print $$$q$$$ lines \u2014 the $$$i$$$-th line should contain the answer to the $$$i$$$-th query, that is the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.", "sample_inputs": ["10 3 4\ncodeforces\nfor\n1 3\n3 10\n5 6\n5 7", "15 2 3\nabacabadabacaba\nba\n1 15\n3 4\n2 14", "3 5 2\naaa\nbaaab\n1 3\n1 1"], "sample_outputs": ["0\n1\n0\n1", "4\n0\n3", "0\n0"], "notes": "NoteIn the first example the queries are substrings: \"cod\", \"deforces\", \"fo\" and \"for\", respectively."}, "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 \u5feb\u901f\u5e42\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"}, {"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"}], "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"} {"nl": {"description": "Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $$$a$$$ and $$$b$$$ using the following algorithm: If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length. The numbers are processed from right to left (that is, from the least significant digits to the most significant). In the first step, she adds the last digit of $$$a$$$ to the last digit of $$$b$$$ and writes their sum in the answer. At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer. For example, the numbers $$$a = 17236$$$ and $$$b = 3465$$$ Tanya adds up as follows:$$$$$$ \\large{ \\begin{array}{r} + \\begin{array}{r} 17236\\\\ 03465\\\\ \\end{array} \\\\ \\hline \\begin{array}{r} 1106911 \\end{array} \\end{array}} $$$$$$ calculates the sum of $$$6 + 5 = 11$$$ and writes $$$11$$$ in the answer. calculates the sum of $$$3 + 6 = 9$$$ and writes the result to the left side of the answer to get $$$911$$$. calculates the sum of $$$2 + 4 = 6$$$ and writes the result to the left side of the answer to get $$$6911$$$. calculates the sum of $$$7 + 3 = 10$$$, and writes the result to the left side of the answer to get $$$106911$$$. calculates the sum of $$$1 + 0 = 1$$$ and writes the result to the left side of the answer and get $$$1106911$$$. As a result, she gets $$$1106911$$$.You are given two positive integers $$$a$$$ and $$$s$$$. Find the number $$$b$$$ such that by adding $$$a$$$ and $$$b$$$ as described above, Tanya will get $$$s$$$. Or determine that no suitable $$$b$$$ exists.", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Each test case consists of a single line containing two positive integers $$$a$$$ and $$$s$$$ ($$$1 \\le a \\lt s \\le 10^{18}$$$) separated by a space.", "output_spec": "For each test case print the answer on a separate line. If the solution exists, print a single positive integer $$$b$$$. The answer must be written without leading zeros. If multiple answers exist, print any of them. If no suitable number $$$b$$$ exists, output -1.", "sample_inputs": ["6\n17236 1106911\n1 5\n108 112\n12345 1023412\n1 11\n1 20"], "sample_outputs": ["3465\n4\n-1\n90007\n10\n-1"], "notes": "NoteThe first test case is explained in the main part of the statement.In the third test case, we cannot choose $$$b$$$ that satisfies the problem statement."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given array a with n integers and m queries. The i-th query is given with three integers li,\u2009ri,\u2009xi.For the i-th query find any position pi (li\u2009\u2264\u2009pi\u2009\u2264\u2009ri) so that api\u2009\u2260\u2009xi.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of elements in a and the number of queries. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the elements of the array a. Each of the next m lines contains three integers li,\u2009ri,\u2009xi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009106) \u2014 the parameters of the i-th query.", "output_spec": "Print m lines. On the i-th line print integer pi \u2014 the position of any number not equal to xi in segment [li,\u2009ri] or the value \u2009-\u20091 if there is no such number.", "sample_inputs": ["6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2"], "sample_outputs": ["2\n6\n-1\n4"], "notes": null}, "positive_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\nimport java.util.StringTokenizer\nimport scala.collection.mutable.StringBuilder\n\nobject ER_7_C { \n \n \n def main(args: Array[String]): Unit = {\n\n //COMMENT ME !\n// is = new ByteArrayInputStream(Test.big().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 m = line1.int\n \n val line2 = readLine\n val arr = new Array[Int](n + 1)\n for (i <- 1 to n) {\n arr(i) = line2.int \n }\n val arrNext = new Array[Int](n + 1)\n var next = n + 1\n var nextVal = arr(n)\n for (i <- n to 1 by -1) {\n if (nextVal != arr(i)) {\n next = i + 1\n nextVal = arr(i)\n }\n arrNext(i) = next\n }\n// db(arrNext.mkString(\",\"))\n \n val result = new StringBuilder()\n \n for (i <- 1 to m) {\n val qqLine = readLine()\n val l = qqLine.int\n val r = qqLine.int\n val x = qqLine.int\n if (arr(l) != x) {\n printRes(l)\n } else {\n val next = arrNext(l) \n if (next > n || next > r) {\n printRes(-1)\n } else {\n printRes(next)\n }\n }\n }\n \n def printRes(r:Int) = {\n result.append(r + \"\\n\")\n //println(r) \n }\n println(result.toString())\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 = \"\"\"\n6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2\n\"\"\"\n\ndef big() = {\n val n = 200000\n val m = 200000\n val res = new StringBuilder(n + \" \" + m + \"\\n\");\n for (i <- 0 to n) {\n res.append(\"1 \")\n }\n res.append(\"\\n\")\n for (i <- 0 to m) {\n res.append(\"1 200000 1\\n\")\n }\n res.toString()\n} \n\n}\n\n}\n"}], "negative_code": [], "src_uid": "dcf7988c35bb34973e7b60afa7a0e68c"} {"nl": {"description": "Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).", "input_spec": "The first line contains one integer t \u2014 the number of test cases to solve (1\u2009\u2264\u2009t\u2009\u2264\u20091000). Then t test cases follow. The first line of each test case contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of students. Then n lines follow. Each line contains two integer li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u20095000) \u2014 the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li\u2009-\u20091\u2009\u2264\u2009li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t\u2009=\u20091.", "output_spec": "For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.", "sample_inputs": ["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"], "sample_outputs": ["1 2 \n1 0 2"], "notes": "NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea. "}, "positive_code": [{"source_code": "object CF920B extends App{\n val sc = new java.util.Scanner(System.in)\n val t = sc.nextInt\n tea(t)\n def tea(tt: Int): Unit ={\n val n = sc.nextInt\n val lr = Seq.fill[(Int, Int)](n)(sc.nextInt, sc.nextInt)\n println(teapod(lr, 1, Seq.empty) mkString \" \")\n if(tt != 1) tea(tt-1)\n }\n\n def teapod(lr: Seq[(Int,Int)], time: Int, result:Seq[Int] ): Seq[Int] = {\n val (l,r) = lr.head\n //println(l, r, time, (if (time > r) 0 else if (time < l) l else time))\n val newtime = (if (time > r) 0 else Math.max(l, time))\n val newresult = result :+ newtime\n if(lr.length == 1) return newresult else teapod(lr.tail, if(newtime==0) time else newtime + 1, newresult)\n }\n}"}], "negative_code": [{"source_code": "object CF920B extends App{\n val sc = new java.util.Scanner(System.in)\n val t = sc.nextInt\n tea(t)\n def tea(tt: Int): Unit ={\n val n = sc.nextInt\n val lr = Seq.fill[(Int, Int)](n)(sc.nextInt, sc.nextInt)\n println(teapod(lr, 1, Seq.empty) mkString \" \")\n if(tt != 1) tea(tt-1)\n }\n\n def teapod(lr: Seq[(Int,Int)], time: Int, result:Seq[Int] ): Seq[Int] = {\n val (l,r) = lr.head\n //println(l, r, time, (if (time >= r) 0 else if (time < l) l else time))\n val newtime = (if (time >= r) 0 else Math.max(l, time))\n val newresult = result :+ newtime\n if(lr.length == 1) return newresult else teapod(lr.tail, newtime + 1, newresult)\n }\n}"}, {"source_code": "object CF920B extends App{\n val sc = new java.util.Scanner(System.in)\n val t = sc.nextInt\n tea(t)\n def tea(tt: Int): Unit ={\n val n = sc.nextInt\n val lr = Seq.fill[(Int, Int)](n)(sc.nextInt, sc.nextInt)\n println(teapod(lr, 1, Seq.empty) mkString \" \")\n if(tt != 1) tea(tt-1)\n }\n\n def teapod(lr: Seq[(Int,Int)], time: Int, result:Seq[Int] ): Seq[Int] = {\n val (l,r) = lr.head\n //println(l, r, time, (if (time >= r) 0 else if (time < l) l else time))\n val newtime = (if (time > r) 0 else Math.max(l, time))\n val newresult = result :+ newtime\n if(lr.length == 1) return newresult else teapod(lr.tail, newtime + 1, newresult)\n }\n}"}], "src_uid": "471f80e349e70339eedd20d45b16e253"} {"nl": {"description": "Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.", "input_spec": "The first line of the input contains n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of bishops. Each of next n lines contains two space separated integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u20091000)\u00a0\u2014 the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.", "output_spec": "Output one integer\u00a0\u2014 the number of pairs of bishops which attack each other. ", "sample_inputs": ["5\n1 1\n1 5\n3 3\n5 1\n5 5", "3\n1 1\n2 3\n3 5"], "sample_outputs": ["6", "0"], "notes": "NoteIn the first sample following pairs of bishops attack each other: (1,\u20093), (1,\u20095), (2,\u20093), (2,\u20094), (3,\u20094) and (3,\u20095). Pairs (1,\u20092), (1,\u20094), (2,\u20095) and (4,\u20095) do not attack each other because they do not share the same diagonal."}, "positive_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 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": "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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:There are two arrays of integers $$$a$$$ and $$$b$$$ of length $$$n$$$. It turned out that array $$$a$$$ contains only elements from the set $$$\\{-1, 0, 1\\}$$$.Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $$$(i, j)$$$ such that $$$1 \\le i < j \\le n$$$. It is possible to choose the same pair $$$(i, j)$$$ more than once. Add $$$a_i$$$ to $$$a_j$$$. In other words, $$$j$$$-th element of the array becomes equal to $$$a_i + a_j$$$. For example, if you are given array $$$[1, -1, 0]$$$, you can transform it only to $$$[1, -1, -1]$$$, $$$[1, 0, 0]$$$ and $$$[1, -1, 1]$$$ by one operation.Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $$$a$$$ so that it becomes equal to array $$$b$$$. Can you help him?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u00a0\u2014 the length of arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-1 \\le a_i \\le 1$$$) \u00a0\u2014 elements of array $$$a$$$. There can be duplicates among elements. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$-10^9 \\le b_i \\le 10^9$$$) \u00a0\u2014 elements of array $$$b$$$. There can be duplicates among elements. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, output one line containing \"YES\" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing the described operations, or \"NO\" if it's impossible. You can print each letter in any case (upper or lower).", "sample_inputs": ["5\n3\n1 -1 0\n1 1 -2\n3\n0 1 1\n0 2 2\n2\n1 0\n1 41\n2\n-1 0\n-1 -41\n5\n0 1 -1 1 -1\n1 1 -1 1 -1"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteIn the first test-case we can choose $$$(i, j)=(2, 3)$$$ twice and after that choose $$$(i, j)=(1, 2)$$$ twice too. These operations will transform $$$[1, -1, 0] \\to [1, -1, -2] \\to [1, 1, -2]$$$In the second test case we can't make equal numbers on the second position.In the third test case we can choose $$$(i, j)=(1, 2)$$$ $$$41$$$ times. The same about the fourth test case.In the last lest case, it is impossible to make array $$$a$$$ equal to the array $$$b$$$."}, "positive_code": [{"source_code": "object B extends App {\n case class Case(as: List[Int], bs: List[Int])\n\n private def isPossible(c: Case): Boolean = {\n val Case(as, bs) = c\n\n val p = as.indexOf(1)\n val m = as.indexOf(-1)\n\n bs.zip(as).zipWithIndex.forall {\n case ((a, b), i) =>\n if (b == a) true\n else if (b > a) m > -1 && m < i\n else p > -1 && p < i\n }\n }\n\n val t = scala.io.StdIn.readInt()\n\n val cases = (0 until t)\n .foldLeft(List.empty[Case]) { (acc, _) =>\n scala.io.StdIn.readInt()\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n val bs = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n Case(as, bs) :: acc\n }\n .reverse\n\n val answers = cases.map(isPossible)\n\n answers.foreach(if (_) println(\"YES\") else println(\"NO\"))\n}"}], "negative_code": [], "src_uid": "e425aa498e5a7fc3e518cec25eec6304"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\ldots, a_n$$$ of positive integers. A good pair is a pair of indices $$$(i, j)$$$ with $$$1 \\leq i, j \\leq n$$$ such that, for all $$$1 \\leq k \\leq n$$$, the following equality holds:$$$$$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Find a good pair. Note that $$$i$$$ can be equal to $$$j$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single line with two space-separated indices $$$i$$$ and $$$j$$$ which form a good pair of the array. The case $$$i=j$$$ is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.", "sample_inputs": ["3\n\n3\n\n5 2 7\n\n5\n\n1 4 2 2 3\n\n1\n\n2"], "sample_outputs": ["2 3\n1 2\n1 1"], "notes": "NoteIn the first case, for $$$i = 2$$$ and $$$j = 3$$$ the equality holds true for all $$$k$$$: $$$k = 1$$$: $$$|a_2 - a_1| + |a_1 - a_3| = |2 - 5| + |5 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$, $$$k = 2$$$: $$$|a_2 - a_2| + |a_2 - a_3| = |2 - 2| + |2 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$, $$$k = 3$$$: $$$|a_2 - a_3| + |a_3 - a_3| = |2 - 7| + |7 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$. "}, "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}"}, {"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"}], "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"} {"nl": {"description": "Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $$$n$$$ of them how much effort they needed to reach red.\"Oh, I just spent $$$x_i$$$ hours solving problems\", said the $$$i$$$-th of them. Bob wants to train his math skills, so for each answer he wrote down the number of minutes ($$$60 \\cdot x_i$$$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes \u2014 for example, if some grandmaster answered that he had spent $$$2$$$ hours, Bob could write $$$000120$$$ instead of $$$120$$$.Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently: rearranged its digits, or wrote a random number. This way, Alice generated $$$n$$$ numbers, denoted $$$y_1$$$, ..., $$$y_n$$$.For each of the numbers, help Bob determine whether $$$y_i$$$ can be a permutation of a number divisible by $$$60$$$ (possibly with leading zeroes).", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 418$$$)\u00a0\u2014 the number of grandmasters Bob asked. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains a single integer $$$y_i$$$\u00a0\u2014 the number that Alice wrote down. Each of these numbers has between $$$2$$$ and $$$100$$$ digits '0' through '9'. They can contain leading zeroes.", "output_spec": "Output $$$n$$$ lines. For each $$$i$$$, output the following. If it is possible to rearrange the digits of $$$y_i$$$ such that the resulting number is divisible by $$$60$$$, output \"red\" (quotes for clarity). Otherwise, output \"cyan\".", "sample_inputs": ["6\n603\n006\n205\n228\n1053\n0000000000000000000000000000000000000000000000"], "sample_outputs": ["red\nred\ncyan\ncyan\ncyan\nred"], "notes": "NoteIn the first example, there is one rearrangement that yields a number divisible by $$$60$$$, and that is $$$360$$$.In the second example, there are two solutions. One is $$$060$$$ and the second is $$$600$$$.In the third example, there are $$$6$$$ possible rearrangments: $$$025$$$, $$$052$$$, $$$205$$$, $$$250$$$, $$$502$$$, $$$520$$$. None of these numbers is divisible by $$$60$$$.In the fourth example, there are $$$3$$$ rearrangements: $$$228$$$, $$$282$$$, $$$822$$$.In the fifth example, none of the $$$24$$$ rearrangements result in a number divisible by $$$60$$$.In the sixth example, note that $$$000\\dots0$$$ is a valid solution."}, "positive_code": [{"source_code": "object _1266A 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].map(i => i - '0')\n val z = s.indexOf(0)\n val isRed = z >= 0 &&\n s.zipWithIndex.exists({case (s, i) => s%2 == 0 && i != z}) &&\n s.sum%3 == 0\n io.write(if (isRed) \"red\" else \"cyan\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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": "5bc07d2efb7453e51f4931cc7ec3aac7"} {"nl": {"description": "Let's define $$$S(x)$$$ to be the sum of digits of number $$$x$$$ written in decimal system. For example, $$$S(5) = 5$$$, $$$S(10) = 1$$$, $$$S(322) = 7$$$.We will call an integer $$$x$$$ interesting if $$$S(x + 1) < S(x)$$$. In each test you will be given one integer $$$n$$$. Your task is to calculate the number of integers $$$x$$$ such that $$$1 \\le x \\le n$$$ and $$$x$$$ is interesting.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) for the $$$i$$$-th test case.", "output_spec": "Print $$$t$$$ integers, the $$$i$$$-th should be the answer for the $$$i$$$-th test case.", "sample_inputs": ["5\n1\n9\n10\n34\n880055535"], "sample_outputs": ["0\n1\n1\n3\n88005553"], "notes": "NoteThe first interesting number is equal to $$$9$$$."}, "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": "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"}, {"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"} {"nl": {"description": "You are given a positive integer $$$x$$$. Check whether the number $$$x$$$ is representable as the sum of the cubes of two positive integers.Formally, you need to check if there are two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b$$$) such that $$$a^3+b^3=x$$$.For example, if $$$x = 35$$$, then the numbers $$$a=2$$$ and $$$b=3$$$ are suitable ($$$2^3+3^3=8+27=35$$$). If $$$x=4$$$, then no pair of numbers $$$a$$$ and $$$b$$$ is suitable.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$x$$$ ($$$1 \\le x \\le 10^{12}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.", "output_spec": "For each test case, output on a separate line: \"YES\" if $$$x$$$ is representable as the sum of the cubes of two positive integers. \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["7\n1\n2\n4\n34\n35\n16\n703657519796"], "sample_outputs": ["NO\nYES\nNO\nNO\nYES\nYES\nYES"], "notes": "NoteThe number $$$1$$$ is not representable as the sum of two cubes.The number $$$2$$$ is represented as $$$1^3+1^3$$$.The number $$$4$$$ is not representable as the sum of two cubes.The number $$$34$$$ is not representable as the sum of two cubes.The number $$$35$$$ is represented as $$$2^3+3^3$$$.The number $$$16$$$ is represented as $$$2^3+2^3$$$.The number $$$703657519796$$$ is represented as $$$5779^3+7993^3$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\nimport util.control.Breaks._\n\nobject Main {\n def main(args: Array[String]) = {\n var num = readLine().toInt\n while(num > 0 ){\n var found = 0\n var entry = readLine().toDouble\n num -= 1\n for( x <- scala.math.cbrt(entry).toInt to 1 by -1){\n val c1 = (entry - scala.math.pow(x,3))\n breakable {\n if (c1 < 1) {\n break\n }\n var res = scala.math.round(scala.math.cbrt(c1))\n if (scala.math.pow(res,3) + scala.math.pow(x,3) == entry) {\n found = 1\n }\n }\n }\n if (found == 1) println(\"YES\") else println(\"NO\")\n }\n }\n}"}], "negative_code": [], "src_uid": "b4ca6a5ee6307ab2bcdab2ea5dd5b2b3"} {"nl": {"description": "You are a given a list of integers $$$a_1, a_2, \\ldots, a_n$$$ and $$$s$$$ of its segments $$$[l_j; r_j]$$$ (where $$$1 \\le l_j \\le r_j \\le n$$$).You need to select exactly $$$m$$$ segments in such a way that the $$$k$$$-th order statistic of the multiset of $$$a_i$$$, where $$$i$$$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $$$m$$$ segments in such a way that the multiset contains at least $$$k$$$ elements, print -1.The $$$k$$$-th order statistic of a multiset is the value of the $$$k$$$-th element after sorting the multiset in non-descending order.", "input_spec": "The first line contains four integers $$$n$$$, $$$s$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le m \\le s \\le 1500$$$, $$$1 \\le k \\le n \\le 1500$$$)\u00a0\u2014 the size of the list, the number of segments, the number of segments to choose and the statistic number. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the values of the numbers in the list. Each of the next $$$s$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$)\u00a0\u2014 the endpoints of the segments. It is possible that some segments coincide.", "output_spec": "Print exactly one integer\u00a0\u2014 the smallest possible $$$k$$$-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least $$$k$$$ elements.", "sample_inputs": ["4 3 2 2\n3 1 3 2\n1 2\n2 3\n4 4", "5 2 1 1\n1 2 3 4 5\n2 4\n1 5", "5 3 3 5\n5 5 2 1 1\n1 2\n2 3\n3 4"], "sample_outputs": ["2", "1", "-1"], "notes": "NoteIn the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the $$$2$$$-nd order statistic for the covered elements is $$$2$$$."}, "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, M, K = ni()\n val A = na(N)\n val (l, r) = na2(S, -1)\n\n val B = A.clone()\n radixSort(B)\n\n val INF = 1e5.toInt\n val rl = Array.fill[Int](N)(INF) // \u70b9\u3092\u542b\u3080\u30bb\u30b0\u30e1\u30f3\u30c8\u3067\u3001L\u304c\u4e00\u756a\u5c0f\u3055\u3044\u3082\u306e\n rep(S) { i =>\n rl(r(i)) = min(rl(r(i)), l(i))\n }\n rep_r(N - 1) { i =>\n rl(i) = min(rl(i), rl(i + 1))\n }\n\n // \u5404\u70b9\u3054\u3068\u306b\u4f7f\u3063\u305f\u30bb\u30b0\u30e1\u30f3\u30c8\u306e\u500b\u6570\u3067\u6700\u5927\u500b\u6570\u3092\u6c42\u3081\u308b\n // \u30bb\u30b0\u30e1\u30f3\u30c8\u3092\u70b9\u3067\u5206\u5272\u3059\u308b\u3068\u8003\u3048\u308b\u3068\u3001\u53f3\u5074\u306b\u65b0\u3057\u3044\u30bb\u30b0\u30e1\u30f3\u30c8\u304c\u6765\u308b\u3068\u3057\u3066\u3001\u5de6\u3067\u9078\u3076\u306e\u306fL\u304c\u4e00\u756a\u5c0f\u3055\u3044\u3082\u306e\u304c\u6700\u9069\n val dp = Array.ofDim[Int](N + 1, M + 1)\n\n // B(x)\u3088\u308a\u5c0f\u3055\u3044\u5024\u3060\u3051\u3067K\u500b\u4ee5\u4e0a\u3092\u9054\u6210\u3067\u304d\u308b\u304b\n val ix = binSearch(0, N - 1) { x =>\n val flags = map(N){ i => if (A(i) <= B(x)) 1 else 0 }\n val cum = cumSum(flags)\n\n rep(N) { i =>\n Array.copy(dp(i), 0, dp(i + 1), 0, M + 1) // \u4f55\u3082\u9078\u3070\u306a\u304b\u3063\u305f\u5834\u5408\n\n if (rl(i) <= i) { // \u3053\u306e\u70b9\u3092\u542b\u3080\u30bb\u30b0\u30e1\u30f3\u30c8\u304c\u5b58\u5728\u3059\u308b\n val prev = dp(rl(i)) // \u30bb\u30b0\u30e1\u30f3\u30c8\u306e\u5de6\u7aef\u306e\u4e00\u3064\u524d\u304b\u3089\u9077\u79fb\u3059\u308b\n val next = dp(i + 1)\n val cnt = cum(i + 1) - cum(rl(i))\n rep(M) { j =>\n next(j + 1) = max(next(j + 1), prev(j) + cnt)\n }\n }\n }\n val k = dp(N).max\n k >= K\n }\n\n if (ix == N) {\n out.println(-1)\n } else {\n out.println(B(ix))\n }\n }\n\n def binSearch(ms: Int, mx: Int)(f: Int => Boolean): Int = {\n var high = mx + 1\n var low = ms - 1\n while(abs(high - low) > 1) {\n val mid = (high + low) / 2\n if (f(mid)) high = mid\n else low = mid\n }\n high\n }\n\n /**\n * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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, offset: Int = 0)(f: Int => 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": "1a1b3c6b1cd29563aa93c145c0c2f01a"} {"nl": {"description": "Alice gave Bob two integers $$$a$$$ and $$$b$$$ ($$$a > 0$$$ and $$$b \\ge 0$$$). Being a curious boy, Bob wrote down an array of non-negative integers with $$$\\operatorname{MEX}$$$ value of all elements equal to $$$a$$$ and $$$\\operatorname{XOR}$$$ value of all elements equal to $$$b$$$.What is the shortest possible length of the array Bob wrote?Recall that the $$$\\operatorname{MEX}$$$ (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the $$$\\operatorname{XOR}$$$ of an array is the bitwise XOR of all the elements of the array.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5 \\cdot 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\leq a \\leq 3 \\cdot 10^5$$$; $$$0 \\leq b \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the $$$\\operatorname{MEX}$$$ and $$$\\operatorname{XOR}$$$ of the array, respectively.", "output_spec": "For each test case, output one (positive) integer\u00a0\u2014 the length of the shortest array with $$$\\operatorname{MEX}$$$ $$$a$$$ and $$$\\operatorname{XOR}$$$ $$$b$$$. We can show that such an array always exists.", "sample_inputs": ["5\n1 1\n2 1\n2 0\n1 10000\n2 10000"], "sample_outputs": ["3\n2\n3\n2\n3"], "notes": "NoteIn the first test case, one of the shortest arrays with $$$\\operatorname{MEX}$$$ $$$1$$$ and $$$\\operatorname{XOR}$$$ $$$1$$$ is $$$[0, 2020, 2021]$$$.In the second test case, one of the shortest arrays with $$$\\operatorname{MEX}$$$ $$$2$$$ and $$$\\operatorname{XOR}$$$ $$$1$$$ is $$$[0, 1]$$$.It can be shown that these arrays are the shortest arrays possible."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There are $$$n$$$ cats in a line, labeled from $$$1$$$ to $$$n$$$, with the $$$i$$$-th cat at position $$$i$$$. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.For example, if there are $$$3$$$ cats, this is a valid reordering: $$$[3, 1, 2]$$$. No cat is in its original position. The total distance the cats move is $$$1 + 1 + 2 = 4$$$ as cat $$$1$$$ moves one place to the right, cat $$$2$$$ moves one place to the right, and cat $$$3$$$ moves two places to the left.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the number of cats. It can be proven that under the constraints of the problem, an answer always exist. ", "output_spec": "Output $$$t$$$ answers, one for each test case. Each answer consists of $$$n$$$ integers\u00a0\u2014 a permutation with the minimum total distance. If there are multiple answers, print any.", "sample_inputs": ["2\n2\n3"], "sample_outputs": ["2 1 \n3 1 2"], "notes": "NoteFor the first test case, there is only one possible permutation that satisfies the conditions: $$$[2, 1]$$$.The second test case was described in the statement. Another possible answer is $$$[2, 3, 1]$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of points. Each of the next n lines contains two integers (xi,\u2009yi) (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109) \u2014 the coordinates of the i-th point.", "output_spec": "Print the only integer c \u2014 the number of parallelograms with the vertices at the given points.", "sample_inputs": ["4\n0 1\n1 0\n1 1\n2 0"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n val n = in.next().toInt\n val points = Array.ofDim[(Int, Int)](n)\n val map = mutable.Map.empty[(Int, Int), Int]\n (0 until n).foreach { i =>\n val Array(x, y) = in.next().split(' ').map(_.toInt)\n points(i) = (x, y)\n (0 until i).foreach { j =>\n val (x1, y1) = points(j)\n val key =\n if (x1 == x)\n (0, Math.abs(y1 - y))\n else if (x1 > x)\n (x1 - x, y1 - y)\n else\n (x - x1, y - y1)\n map += (key -> (map.getOrElse(key, 0) + 1))\n }\n }\n\n// println(map)\n// println(map.filter(_._2 > 1))\n// println(map.filter(_._2 > 1).map(i => i._2 * (i._2 - 1) / 2))\n// println(points)\n\n println(map.values.foldLeft(0l){\n case (acc, el) => acc + el * (el - 1) / 2} / 2)\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).foldLeft(Map.empty[(Int, Int), Int], List.empty[(Int, Int)]) {\n case((map, points), _) =>\n val Array(x, y) = in.next().split(' ').map(_.toInt)\n (points.foldLeft(map) { case (acc, (x1, y1)) =>\n val key = (Math.abs(x1 - x), Math.abs(y1 - y))\n acc + (key -> (map.getOrElse(key, 0) + 1))\n }, (x, y) :: points)\n }._1.values.foldLeft(0l){\n case (acc, el) => acc + el * (el - 1) / 2} / 2)\n}\n"}], "src_uid": "bd519efcfaf5b43bb737337004a1c2c0"} {"nl": {"description": "The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0,\u2009y0) of a rectangular squared field of size x\u2009\u00d7\u2009y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x\u00b7y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.", "input_spec": "The first line of the input contains four integers x, y, x0, y0 (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009500,\u20091\u2009\u2264\u2009x0\u2009\u2264\u2009x,\u20091\u2009\u2264\u2009y0\u2009\u2264\u2009y)\u00a0\u2014 the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right. The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100\u2009000 characters and only consists of characters 'L', 'R', 'U', 'D'.", "output_spec": "Print the sequence consisting of (length(s)\u2009+\u20091) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up.", "sample_inputs": ["3 4 2 2\nUURDRDRL", "2 2 2 2\nULD"], "sample_outputs": ["1 1 0 1 1 1 1 0 6", "1 1 1 1"], "notes": "NoteIn the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: ."}, "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(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.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"}, {"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"}], "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"} {"nl": {"description": "You have array a1,\u2009a2,\u2009...,\u2009an. Segment [l,\u2009r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) is good if ai\u2009=\u2009ai\u2009-\u20091\u2009+\u2009ai\u2009-\u20092, for all i (l\u2009+\u20092\u2009\u2264\u2009i\u2009\u2264\u2009r).Let's define len([l,\u2009r])\u2009=\u2009r\u2009-\u2009l\u2009+\u20091, len([l,\u2009r]) is the length of the segment [l,\u2009r]. Segment [l1,\u2009r1], is longer than segment [l2,\u2009r2], if len([l1,\u2009r1])\u2009>\u2009len([l2,\u2009r2]).Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of elements in the array. The second line contains integers: a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print the length of the longest good segment in array a.", "sample_inputs": ["10\n1 2 3 5 8 13 21 34 55 89", "5\n1 1 1 1 1"], "sample_outputs": ["10", "2"], "notes": null}, "positive_code": [{"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}"}, {"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,\u2009a2,\u2009...,\u2009an. Segment [l,\u2009r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) is good\n * if ai\u2009=\u2009ai\u2009-\u20091\u2009+\u2009ai\u2009-\u20092, for all i (l\u2009+\u20092\u2009\u2264\u2009i\u2009\u2264\u2009r).\n *\n * Let's define len([l,\u2009r])\u2009=\u2009r\u2009-\u2009l\u2009+\u20091, len([l,\u2009r]) is the length of the\n * segment [l,\u2009r]. Segment [l1,\u2009r1], is longer than segment [l2,\u2009r2], if\n * len([l1,\u2009r1])\u2009>\u2009len([l2,\u2009r2]).\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 \u2190 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 \u21d2 1\n case 2 \u21d2 2\n case _ \u21d2\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 \u2190 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 \u2190 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,\u2009a2,\u2009...,\u2009an. Segment [l,\u2009r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) is good\n * if ai\u2009=\u2009ai\u2009-\u20091\u2009+\u2009ai\u2009-\u20092, for all i (l\u2009+\u20092\u2009\u2264\u2009i\u2009\u2264\u2009r).\n *\n * Let's define len([l,\u2009r])\u2009=\u2009r\u2009-\u2009l\u2009+\u20091, len([l,\u2009r]) is the length of the\n * segment [l,\u2009r]. Segment [l1,\u2009r1], is longer than segment [l2,\u2009r2], if\n * len([l1,\u2009r1])\u2009>\u2009len([l2,\u2009r2]).\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 \u2190 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 \u21d2 1\n case 2 \u21d2 2\n case _ \u21d2\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 \u2190 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": "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}"}, {"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}"}], "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"} {"nl": {"description": "Sayaka Saeki is a member of the student council, which has $$$n$$$ other members (excluding Sayaka). The $$$i$$$-th member has a height of $$$a_i$$$ millimeters.It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is as large as possible.A pair of two consecutive members $$$u$$$ and $$$v$$$ on a line is considered photogenic if their average height is an integer, i.e. $$$\\frac{a_u + a_v}{2}$$$ is an integer.Help Sayaka arrange the other members to maximize the number of photogenic consecutive pairs.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 500$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 2000$$$) \u00a0\u2014 the number of other council members. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$) \u00a0\u2014 the heights of each of the other members in millimeters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.", "output_spec": "For each test case, output on one line $$$n$$$ integers representing the heights of the other members in the order, which gives the largest number of photogenic consecutive pairs. If there are multiple such orders, output any of them.", "sample_inputs": ["4\n3\n1 1 2\n3\n1 1 1\n8\n10 9 13 15 3 16 9 13\n2\n18 9"], "sample_outputs": ["1 1 2 \n1 1 1 \n13 9 13 15 3 9 16 10 \n9 18"], "notes": "NoteIn the first test case, there is one photogenic pair: $$$(1, 1)$$$ is photogenic, as $$$\\frac{1+1}{2}=1$$$ is integer, while $$$(1, 2)$$$ isn't, as $$$\\frac{1+2}{2}=1.5$$$ isn't integer.In the second test case, both pairs are photogenic."}, "positive_code": [{"source_code": "object cf1509a {\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 nCount = readInt()\n\t\t\tval members = readInts()\n\t\t\tval odds = members.filter(_ % 2 == 1)\n\t\t\tval even = members.filter(_ % 2 == 0)\n\t\t\tval res = if (odds.size > even.size) odds ++ even else even ++ odds\n\t\t\tprintln(res.mkString(\" \"))\n }\n }\n}"}], "negative_code": [{"source_code": "object cf1509a {\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 nCount = readInt()\n\t\t\tval members = readInts()\n\t\t\tval odds = members.filter(_ % 2 == 1)\n\t\t\tval even = members.filter(_ % 2 == 0)\n\t\t\tval res = odds.slice(0, odds.size - odds.size % 2) ++ even ++ { if (odds.size % 2 == 1) Array(odds.last) else Array.emptyIntArray }\n\t\t\tprintln(res.mkString(\" \"))\n }\n }\n}"}], "src_uid": "fe2131c9228a2ec4365fdc3d0faa413a"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to determine if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome.Recall that an array $$$b$$$ is called a subsequence of the array $$$a$$$ if $$$b$$$ can be obtained by removing some (possibly, zero) elements from $$$a$$$ (not necessarily consecutive) without changing the order of remaining elements. For example, $$$[2]$$$, $$$[1, 2, 1, 3]$$$ and $$$[2, 3]$$$ are subsequences of $$$[1, 2, 1, 3]$$$, but $$$[1, 1, 2]$$$ and $$$[4]$$$ are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $$$a$$$ of length $$$n$$$ is the palindrome if $$$a_i = a_{n - i - 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n$$$. For example, arrays $$$[1234]$$$, $$$[1, 2, 1]$$$, $$$[1, 3, 2, 2, 3, 1]$$$ and $$$[10, 100, 10]$$$ are palindromes, but arrays $$$[1, 2]$$$ and $$$[1, 2, 3, 1]$$$ are not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$3 \\le n \\le 5000$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$ ($$$\\sum n \\le 5000$$$).", "output_spec": "For each test case, print the answer \u2014 \"YES\" (without quotes) if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome and \"NO\" otherwise.", "sample_inputs": ["5\n3\n1 2 1\n5\n1 2 2 3 2\n3\n1 1 2\n4\n1 2 2 1\n10\n1 1 2 2 3 3 4 4 5 5"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO"], "notes": "NoteIn the first test case of the example, the array $$$a$$$ has a subsequence $$$[1, 2, 1]$$$ which is a palindrome.In the second test case of the example, the array $$$a$$$ has two subsequences of length $$$3$$$ which are palindromes: $$$[2, 3, 2]$$$ and $$$[2, 2, 2]$$$.In the third test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.In the fourth test case of the example, the array $$$a$$$ has one subsequence of length $$$4$$$ which is a palindrome: $$$[1, 2, 2, 1]$$$ (and has two subsequences of length $$$3$$$ which are palindromes: both are $$$[1, 2, 1]$$$).In the fifth test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes."}, "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"}, {"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"}], "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"} {"nl": {"description": "Recently, Tokitsukaze found an interesting game. Tokitsukaze had $$$n$$$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $$$m$$$ ($$$1 \\le m \\le n$$$) special items of them.These $$$n$$$ items are marked with indices from $$$1$$$ to $$$n$$$. In the beginning, the item with index $$$i$$$ is placed on the $$$i$$$-th position. Items are divided into several pages orderly, such that each page contains exactly $$$k$$$ positions and the last positions on the last page may be left empty.Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded. Consider the first example from the statement: $$$n=10$$$, $$$m=4$$$, $$$k=5$$$, $$$p=[3, 5, 7, 10]$$$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $$$3$$$ and $$$5$$$. After, the first page remains to be special. It contains $$$[1, 2, 4, 6, 7]$$$, Tokitsukaze discards the special item with index $$$7$$$. After, the second page is special (since it is the first page containing a special item). It contains $$$[9, 10]$$$, Tokitsukaze discards the special item with index $$$10$$$. Tokitsukaze wants to know the number of operations she would do in total.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n \\le 10^{18}$$$, $$$1 \\le m \\le 10^5$$$, $$$1 \\le m, k \\le n$$$)\u00a0\u2014 the number of items, the number of special items to be discarded and the number of positions in each page. The second line contains $$$m$$$ distinct integers $$$p_1, p_2, \\ldots, p_m$$$ ($$$1 \\le p_1 < p_2 < \\ldots < p_m \\le n$$$)\u00a0\u2014 the indices of special items which should be discarded.", "output_spec": "Print a single integer\u00a0\u2014 the number of operations that Tokitsukaze would do in total.", "sample_inputs": ["10 4 5\n3 5 7 10", "13 4 5\n7 8 9 10"], "sample_outputs": ["3", "1"], "notes": "NoteFor the first example: In the first operation, Tokitsukaze would focus on the first page $$$[1, 2, 3, 4, 5]$$$ and discard items with indices $$$3$$$ and $$$5$$$; In the second operation, Tokitsukaze would focus on the first page $$$[1, 2, 4, 6, 7]$$$ and discard item with index $$$7$$$; In the third operation, Tokitsukaze would focus on the second page $$$[9, 10]$$$ and discard item with index $$$10$$$. For the second example, Tokitsukaze would focus on the second page $$$[6, 7, 8, 9, 10]$$$ and discard all special items at once."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val _ = nl()\n val N = ni()\n val K = nl()\n val P = nal(N)\n REP(N) { i =>\n P(i) -= 1\n }\n\n var p = 0\n var ans = 0\n while(p < N) {\n val m = (P(p) - p) % K\n val remain = K - 1 - m\n var i = 0\n while(p + i + 1 < N && P(p + i + 1) - P(p) <= remain) {\n i += 1\n }\n debug(s\"[$p, ${p+i}]\")\n p += i + 1\n ans += 1\n }\n\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "684273a4c6711295996e520739744b0f"} {"nl": {"description": "Suppose you have two points $$$p = (x_p, y_p)$$$ and $$$q = (x_q, y_q)$$$. Let's denote the Manhattan distance between them as $$$d(p, q) = |x_p - x_q| + |y_p - y_q|$$$.Let's say that three points $$$p$$$, $$$q$$$, $$$r$$$ form a bad triple if $$$d(p, r) = d(p, q) + d(q, r)$$$.Let's say that an array $$$b_1, b_2, \\dots, b_m$$$ is good if it is impossible to choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that the points $$$(b_i, i)$$$, $$$(b_j, j)$$$ and $$$(b_k, k)$$$ form a bad triple.You are given an array $$$a_1, a_2, \\dots, a_n$$$. Calculate the number of good subarrays of $$$a$$$. A subarray of the array $$$a$$$ is the array $$$a_l, a_{l + 1}, \\dots, a_r$$$ for some $$$1 \\le l \\le r \\le n$$$.Note that, according to the definition, subarrays of length $$$1$$$ and $$$2$$$ are good.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the number of good subarrays of array $$$a$$$.", "sample_inputs": ["3\n4\n2 4 1 3\n5\n6 9 1 9 6\n2\n13 37"], "sample_outputs": ["10\n12\n3"], "notes": "NoteIn the first test case, it can be proven that any subarray of $$$a$$$ is good. For example, subarray $$$[a_2, a_3, a_4]$$$ is good since it contains only three elements and: $$$d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3$$$ $$$<$$$ $$$d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7$$$; $$$d((a_2, 2), (a_3, 3))$$$ $$$<$$$ $$$d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3))$$$; $$$d((a_3, 3), (a_4, 4))$$$ $$$<$$$ $$$d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4))$$$; In the second test case, for example, subarray $$$[a_1, a_2, a_3, a_4]$$$ is not good, since it contains a bad triple $$$(a_1, 1)$$$, $$$(a_2, 2)$$$, $$$(a_4, 4)$$$: $$$d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6$$$; $$$d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4$$$; $$$d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2$$$; So, $$$d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4))$$$."}, "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n type P = (Int, Int)\r\n\r\n def d(p: P, q: P): Int = math.abs(p._1 - q._1) + math.abs(p._2 - q._2)\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 = (0 until n).foldLeft(0) { case (count, i) =>\r\n (i until n).takeWhile {\r\n case j if i + 2 <= j =>\r\n val r = (j, an(j))\r\n\r\n (i until j).forall { k =>\r\n val p = (k, an(k))\r\n\r\n ((k + 1) until j).forall { t =>\r\n val q = (t, an(t))\r\n\r\n d(p, r) != d(p, q) + d(q, r)\r\n }\r\n }\r\n case _ => true\r\n }.length + count\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "e87ff02ce425fc3e96c09a15679aa656"} {"nl": {"description": "YouKn0wWho has an integer sequence $$$a_1, a_2, \\ldots a_n$$$. Now he will split the sequence $$$a$$$ into one or more consecutive subarrays so that each element of $$$a$$$ belongs to exactly one subarray. Let $$$k$$$ be the number of resulting subarrays, and $$$h_1, h_2, \\ldots, h_k$$$ be the lengths of the longest increasing subsequences of corresponding subarrays.For example, if we split $$$[2, 5, 3, 1, 4, 3, 2, 2, 5, 1]$$$ into $$$[2, 5, 3, 1, 4]$$$, $$$[3, 2, 2, 5]$$$, $$$[1]$$$, then $$$h = [3, 2, 1]$$$.YouKn0wWho wonders if it is possible to split the sequence $$$a$$$ in such a way that the bitwise XOR of $$$h_1, h_2, \\ldots, h_k$$$ is equal to $$$0$$$. You have to tell whether it is possible.The longest increasing subsequence (LIS) of a sequence $$$b_1, b_2, \\ldots, b_m$$$ is the longest sequence of valid indices $$$i_1, i_2, \\ldots, i_k$$$ such that $$$i_1 \\lt i_2 \\lt \\ldots \\lt i_k$$$ and $$$b_{i_1} \\lt b_{i_2} \\lt \\ldots \\lt b_{i_k}$$$. For example, the LIS of $$$[2, 5, 3, 3, 5]$$$ is $$$[2, 3, 5]$$$, which has length $$$3$$$.An array $$$c$$$ is a subarray of an array $$$b$$$ if $$$c$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$) \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"YES\" (without quotes) if it is possible to split into subarrays in the desired way, print \"NO\" (without quotes) otherwise. You can print each letter in any register (upper or lower).", "sample_inputs": ["4\n7\n1 3 4 2 2 1 5\n3\n1 3 4\n5\n1 3 2 4 2\n4\n4 3 2 1"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteIn the first test case, YouKn0wWho can split the sequence in the following way: $$$[1, 3, 4]$$$, $$$[2, 2]$$$, $$$[1, 5]$$$. This way, the LIS lengths are $$$h = [3, 1, 2]$$$, and the bitwise XOR of the LIS lengths is $$$3 \\oplus 1 \\oplus 2 = 0$$$.In the second test case, it can be shown that it is impossible to split the sequence into subarrays that will satisfy the condition."}, "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"}, {"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"}], "negative_code": [], "src_uid": "d8d33581ceb13da9bb99e90296bdd8f7"} {"nl": {"description": "A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing an integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$).", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer must begin with an integer $$$k$$$ \u2014 the minimum number of summands. Next, $$$k$$$ terms must follow, each of which is a round number, and their sum is $$$n$$$. The terms can be printed in any order. If there are several answers, print any of them.", "sample_inputs": ["5\n5009\n7\n9876\n10000\n10"], "sample_outputs": ["2\n5000 9\n1\n7 \n4\n800 70 6 9000 \n1\n10000 \n1\n10"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A\u2009=\u2009(a1,\u2009a2,\u2009...,\u2009am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B\u2009=\u2009(b1,\u2009b2,\u2009...,\u2009bk).Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7109) \u2014 the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1\u2009\u2264\u2009m,\u2009k\u2009\u2264\u20091000). The given lines only contain characters \"R\", \"S\" and \"P\". Character \"R\" stands for the rock, character \"S\" represents the scissors and \"P\" represents the paper.", "output_spec": "Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.", "sample_inputs": ["7\nRPS\nRSPP", "5\nRRRRRRRR\nR"], "sample_outputs": ["3 2", "0 0"], "notes": "NoteIn the first sample the game went like this: R - R. Draw. P - S. Nikephoros loses. S - P. Polycarpus loses. R - P. Nikephoros loses. P - R. Polycarpus loses. S - S. Draw. R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2."}, "positive_code": [{"source_code": "import java.io._\n\nobject Solution {\n def main(args: Array[String]) {\n val in = new BufferedReader(new InputStreamReader(System.in))\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 val rounds = in.readLine.toInt\n val A = in.readLine\n val B = in.readLine\n val period = lcm(A.length, B.length)\n val xa = new Array[Int](period + 1)\n val xb = new Array[Int](period + 1)\n for(i <- 1 to period) {\n val a = A((i - 1) % A.length)\n val b = B((i - 1) % B.length)\n def win(x: Char, y: Char) = if(x == 'R' && y == 'S' || x == 'S' && y == 'P' || x == 'P' && y == 'R') 1 else 0\n xa(i) = xa(i - 1) + win(b, a)\n xb(i) = xb(i - 1) + win(a, b)\n }\n val full = rounds / period\n val rest = rounds % period\n println(\"%d %d\".format(full * xa.last + xa(rest), full * xb.last + xb(rest)))\n }\n}"}], "negative_code": [], "src_uid": "9a365e26f58ecb22a1e382fad3062387"} {"nl": {"description": "Permutation p is an ordered set of integers p1,\u2009\u2009\u2009p2,\u2009\u2009\u2009...,\u2009\u2009\u2009pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,\u2009\u2009\u2009p2,\u2009\u2009\u2009...,\u2009\u2009\u2009pn.Your task is to find such permutation p of length n, that the group of numbers |p1\u2009-\u2009p2|,\u2009|p2\u2009-\u2009p3|,\u2009...,\u2009|pn\u2009-\u20091\u2009-\u2009pn| has exactly k distinct elements.", "input_spec": "The single line of the input contains two space-separated positive integers n, k (1\u2009\u2264\u2009k\u2009<\u2009n\u2009\u2264\u2009105).", "output_spec": "Print n integers forming the permutation. If there are multiple answers, print any of them.", "sample_inputs": ["3 2", "3 1", "5 2"], "sample_outputs": ["1 3 2", "1 2 3", "1 3 2 4 5"], "notes": "NoteBy |x| we denote the absolute value of number x. "}, "positive_code": [{"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 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"}, {"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 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}"}, {"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}"}], "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"} {"nl": {"description": "Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted \u2014 that is, one call connects exactly two people.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1,\u2009id2,\u2009...,\u2009idn (0\u2009\u2264\u2009idi\u2009\u2264\u2009109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.", "output_spec": "Print a single integer \u2014 the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.", "sample_inputs": ["6\n0 1 7 1 7 10", "3\n1 1 1", "1\n0"], "sample_outputs": ["2", "-1", "0"], "notes": "NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed."}, "positive_code": [{"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}"}, {"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. \u0420\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044b \u0432 Spyke\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u2014 \u0434\u0438\u0440\u0435\u043a\u0442\u043e\u0440 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438. \u0412 \u044d\u0442\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 n \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0439 VoIP-\u0441\u0438\u0441\u0442\u0435\u043c\u043e\u0439 Spyke \u0434\u043b\u044f \u0432\u0435\u0434\u0435\u043d\u0438\u044f \u043f\u0435\u0440\u0435\u0433\u043e\u0432\u043e\u0440\u043e\u0432 \u0432 \u0442\u0435\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0431\u043e\u0447\u0435\u0433\u043e \u0434\u043d\u044f. \u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e, \u043a\u043e\u0433\u0434\u0430 \u0434\u0432\u0430 \u0447\u0435\u043b\u043e\u0432\u0435\u043a\u0430 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u044e\u0442 \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u043e\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 Spyke, \u0441\u0435\u0442\u044c Spyke \u043f\u0440\u0438\u0441\u0432\u0430\u0438\u0432\u0430\u0435\u0442 \u044d\u0442\u043e\u043c\u0443 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0443 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 (\u0446\u0435\u043b\u043e\u0435 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e) \u2014 \u043d\u043e\u043c\u0435\u0440 \u0441\u0435\u0441\u0441\u0438\u0438.\n\n\u041a\u0430\u043a-\u0442\u043e \u0440\u0430\u0437 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u0430\u0445\u043e\u0442\u0435\u043b \u0443\u0437\u043d\u0430\u0442\u044c, \u043a\u0442\u043e \u0438\u0437 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u043f\u043e Spyke, \u0430 \u043a\u0442\u043e \u2014 \u043d\u0435\u0442. \u041e\u043d \u0432\u044b\u043f\u0438\u0441\u0430\u043b \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f \u043d\u043e\u043c\u0435\u0440 \u0441\u0435\u0441\u0441\u0438\u0438 \u0435\u0433\u043e \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430, \u0438\u043b\u0438 0, \u0435\u0441\u043b\u0438 \u044d\u0442\u043e\u0442 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u0441\u0435\u0439\u0447\u0430\u0441 \u043d\u0435 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u043f\u043e Spyke.\n\n\u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u043f\u043e \u044d\u0442\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u043c \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043f\u0430\u0440 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0441\u0435\u0439\u0447\u0430\u0441 \u0432\u0435\u0434\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440 \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439. \u0415\u0441\u043b\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0437\u0430\u043a\u0440\u0430\u043b\u0430\u0441\u044c \u043e\u0448\u0438\u0431\u043a\u0430, \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u043c\u043e\u0433\u043b\u0430 \u043f\u0440\u043e\u0438\u0437\u043e\u0439\u0442\u0438, \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u044c \u043e\u0431 \u044d\u0442\u043e\u043c.\n\n\u041e\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438 \u043c\u043e\u0433\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0442\u044c \u043f\u043e Spyke \u043d\u0435 \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u0440\u0443\u0433 \u0441 \u0434\u0440\u0443\u0433\u043e\u043c \u2014 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044b \u0441 \u0432\u043d\u0435\u0448\u043d\u0438\u043c\u0438 \u0441\u043e\u0431\u0435\u0441\u0435\u0434\u043d\u0438\u043a\u0430\u043c\u0438. \u0422\u0430\u043a\u0436\u0435 \u043d\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u044b \u043a\u043e\u043d\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0438 Spyke \u2014 \u0442\u043e \u0435\u0441\u0442\u044c \u0432 \u043a\u0430\u0436\u0434\u043e\u043c \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0443\u0447\u0430\u0441\u0442\u0432\u043e\u0432\u0430\u0442\u044c \u0440\u043e\u0432\u043d\u043e \u0434\u0432\u0430 \u0441\u043e\u0431\u0435\u0441\u0435\u0434\u043d\u0438\u043a\u0430.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0432 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430. \u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b n \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b: id1,\u2009id2,\u2009...,\u2009idn (0\u2009\u2264\u2009idi\u2009\u2264\u2009109). \u0427\u0438\u0441\u043b\u043e idi \u0440\u0430\u0432\u043d\u043e \u043d\u043e\u043c\u0435\u0440\u0443 \u0441\u0435\u0441\u0441\u0438\u0438 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f \u043d\u043e\u043c\u0435\u0440 i, \u0435\u0441\u043b\u0438 \u043e\u043d \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u0432 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u043f\u043e Spyke, \u0438\u043b\u0438 \u0440\u0430\u0432\u043d\u043e \u043d\u0443\u043b\u044e, \u0432 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435.\n\n\u0421\u0447\u0438\u0442\u0430\u0439\u0442\u0435, \u0447\u0442\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438 \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u043e\u0442 1 \u0434\u043e n \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0440 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0432\u0435\u0434\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440 \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439, \u0438\u043b\u0438 -1, \u0435\u0441\u043b\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0437\u0430\u043a\u0440\u0430\u043b\u0430\u0441\u044c \u043e\u0448\u0438\u0431\u043a\u0430, \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u043c\u043e\u0433\u043b\u0430 \u043f\u0440\u043e\u0438\u0437\u043e\u0439\u0442\u0438.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n6\n0 1 7 1 7 10\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n3\n1 1 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n-1\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1\n0\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n0\n\n\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0435\u0441\u0442\u044c \u0434\u0432\u0430 \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u044b\u0445 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430 \u043c\u0435\u0436\u0434\u0443 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f\u043c\u0438: \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 2 \u0438 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 4, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 3 \u0438 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 5.\n\n\u0412\u043e \u0432\u0442\u043e\u0440\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u0430, \u0442\u0430\u043a \u043a\u0430\u043a \u043d\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u044b \u043a\u043e\u043d\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0438.\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}"}, {"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"}], "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. \u0420\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044b \u0432 Spyke\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u2014 \u0434\u0438\u0440\u0435\u043a\u0442\u043e\u0440 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438. \u0412 \u044d\u0442\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 n \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0439 VoIP-\u0441\u0438\u0441\u0442\u0435\u043c\u043e\u0439 Spyke \u0434\u043b\u044f \u0432\u0435\u0434\u0435\u043d\u0438\u044f \u043f\u0435\u0440\u0435\u0433\u043e\u0432\u043e\u0440\u043e\u0432 \u0432 \u0442\u0435\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0431\u043e\u0447\u0435\u0433\u043e \u0434\u043d\u044f. \u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e, \u043a\u043e\u0433\u0434\u0430 \u0434\u0432\u0430 \u0447\u0435\u043b\u043e\u0432\u0435\u043a\u0430 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u044e\u0442 \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u043e\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 Spyke, \u0441\u0435\u0442\u044c Spyke \u043f\u0440\u0438\u0441\u0432\u0430\u0438\u0432\u0430\u0435\u0442 \u044d\u0442\u043e\u043c\u0443 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0443 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 (\u0446\u0435\u043b\u043e\u0435 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e) \u2014 \u043d\u043e\u043c\u0435\u0440 \u0441\u0435\u0441\u0441\u0438\u0438.\n\n\u041a\u0430\u043a-\u0442\u043e \u0440\u0430\u0437 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u0430\u0445\u043e\u0442\u0435\u043b \u0443\u0437\u043d\u0430\u0442\u044c, \u043a\u0442\u043e \u0438\u0437 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u043f\u043e Spyke, \u0430 \u043a\u0442\u043e \u2014 \u043d\u0435\u0442. \u041e\u043d \u0432\u044b\u043f\u0438\u0441\u0430\u043b \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f \u043d\u043e\u043c\u0435\u0440 \u0441\u0435\u0441\u0441\u0438\u0438 \u0435\u0433\u043e \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430, \u0438\u043b\u0438 0, \u0435\u0441\u043b\u0438 \u044d\u0442\u043e\u0442 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u0441\u0435\u0439\u0447\u0430\u0441 \u043d\u0435 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u043f\u043e Spyke.\n\n\u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u043f\u043e \u044d\u0442\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u043c \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043f\u0430\u0440 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0441\u0435\u0439\u0447\u0430\u0441 \u0432\u0435\u0434\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440 \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439. \u0415\u0441\u043b\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0437\u0430\u043a\u0440\u0430\u043b\u0430\u0441\u044c \u043e\u0448\u0438\u0431\u043a\u0430, \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u043c\u043e\u0433\u043b\u0430 \u043f\u0440\u043e\u0438\u0437\u043e\u0439\u0442\u0438, \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u044c \u043e\u0431 \u044d\u0442\u043e\u043c.\n\n\u041e\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438 \u043c\u043e\u0433\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0442\u044c \u043f\u043e Spyke \u043d\u0435 \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u0440\u0443\u0433 \u0441 \u0434\u0440\u0443\u0433\u043e\u043c \u2014 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044b \u0441 \u0432\u043d\u0435\u0448\u043d\u0438\u043c\u0438 \u0441\u043e\u0431\u0435\u0441\u0435\u0434\u043d\u0438\u043a\u0430\u043c\u0438. \u0422\u0430\u043a\u0436\u0435 \u043d\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u044b \u043a\u043e\u043d\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0438 Spyke \u2014 \u0442\u043e \u0435\u0441\u0442\u044c \u0432 \u043a\u0430\u0436\u0434\u043e\u043c \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0443\u0447\u0430\u0441\u0442\u0432\u043e\u0432\u0430\u0442\u044c \u0440\u043e\u0432\u043d\u043e \u0434\u0432\u0430 \u0441\u043e\u0431\u0435\u0441\u0435\u0434\u043d\u0438\u043a\u0430.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0432 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430. \u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b n \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b: id1,\u2009id2,\u2009...,\u2009idn (0\u2009\u2264\u2009idi\u2009\u2264\u2009109). \u0427\u0438\u0441\u043b\u043e idi \u0440\u0430\u0432\u043d\u043e \u043d\u043e\u043c\u0435\u0440\u0443 \u0441\u0435\u0441\u0441\u0438\u0438 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f \u043d\u043e\u043c\u0435\u0440 i, \u0435\u0441\u043b\u0438 \u043e\u043d \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u0432 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u043f\u043e Spyke, \u0438\u043b\u0438 \u0440\u0430\u0432\u043d\u043e \u043d\u0443\u043b\u044e, \u0432 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435.\n\n\u0421\u0447\u0438\u0442\u0430\u0439\u0442\u0435, \u0447\u0442\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438 \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u043e\u0442 1 \u0434\u043e n \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0440 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0432\u0435\u0434\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440 \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439, \u0438\u043b\u0438 -1, \u0435\u0441\u043b\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0437\u0430\u043a\u0440\u0430\u043b\u0430\u0441\u044c \u043e\u0448\u0438\u0431\u043a\u0430, \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u043c\u043e\u0433\u043b\u0430 \u043f\u0440\u043e\u0438\u0437\u043e\u0439\u0442\u0438.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n6\n0 1 7 1 7 10\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n3\n1 1 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n-1\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1\n0\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n0\n\n\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0435\u0441\u0442\u044c \u0434\u0432\u0430 \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u044b\u0445 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430 \u043c\u0435\u0436\u0434\u0443 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f\u043c\u0438: \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 2 \u0438 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 4, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 3 \u0438 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 5.\n\n\u0412\u043e \u0432\u0442\u043e\u0440\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u0430, \u0442\u0430\u043a \u043a\u0430\u043a \u043d\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u044b \u043a\u043e\u043d\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0438.\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. \u0420\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044b \u0432 Spyke\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u2014 \u0434\u0438\u0440\u0435\u043a\u0442\u043e\u0440 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438. \u0412 \u044d\u0442\u043e\u0439 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 n \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0439 VoIP-\u0441\u0438\u0441\u0442\u0435\u043c\u043e\u0439 Spyke \u0434\u043b\u044f \u0432\u0435\u0434\u0435\u043d\u0438\u044f \u043f\u0435\u0440\u0435\u0433\u043e\u0432\u043e\u0440\u043e\u0432 \u0432 \u0442\u0435\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0431\u043e\u0447\u0435\u0433\u043e \u0434\u043d\u044f. \u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e, \u043a\u043e\u0433\u0434\u0430 \u0434\u0432\u0430 \u0447\u0435\u043b\u043e\u0432\u0435\u043a\u0430 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u044e\u0442 \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u043e\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 Spyke, \u0441\u0435\u0442\u044c Spyke \u043f\u0440\u0438\u0441\u0432\u0430\u0438\u0432\u0430\u0435\u0442 \u044d\u0442\u043e\u043c\u0443 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0443 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 (\u0446\u0435\u043b\u043e\u0435 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e) \u2014 \u043d\u043e\u043c\u0435\u0440 \u0441\u0435\u0441\u0441\u0438\u0438.\n\n\u041a\u0430\u043a-\u0442\u043e \u0440\u0430\u0437 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u0430\u0445\u043e\u0442\u0435\u043b \u0443\u0437\u043d\u0430\u0442\u044c, \u043a\u0442\u043e \u0438\u0437 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u043f\u043e Spyke, \u0430 \u043a\u0442\u043e \u2014 \u043d\u0435\u0442. \u041e\u043d \u0432\u044b\u043f\u0438\u0441\u0430\u043b \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f \u043d\u043e\u043c\u0435\u0440 \u0441\u0435\u0441\u0441\u0438\u0438 \u0435\u0433\u043e \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430, \u0438\u043b\u0438 0, \u0435\u0441\u043b\u0438 \u044d\u0442\u043e\u0442 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u0441\u0435\u0439\u0447\u0430\u0441 \u043d\u0435 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u043f\u043e Spyke.\n\n\u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u043f\u043e \u044d\u0442\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u043c \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043f\u0430\u0440 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0441\u0435\u0439\u0447\u0430\u0441 \u0432\u0435\u0434\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440 \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439. \u0415\u0441\u043b\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0437\u0430\u043a\u0440\u0430\u043b\u0430\u0441\u044c \u043e\u0448\u0438\u0431\u043a\u0430, \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u043c\u043e\u0433\u043b\u0430 \u043f\u0440\u043e\u0438\u0437\u043e\u0439\u0442\u0438, \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0441\u043e\u043e\u0431\u0449\u0438\u0442\u044c \u043e\u0431 \u044d\u0442\u043e\u043c.\n\n\u041e\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438 \u043c\u043e\u0433\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0442\u044c \u043f\u043e Spyke \u043d\u0435 \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u0440\u0443\u0433 \u0441 \u0434\u0440\u0443\u0433\u043e\u043c \u2014 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044b \u0441 \u0432\u043d\u0435\u0448\u043d\u0438\u043c\u0438 \u0441\u043e\u0431\u0435\u0441\u0435\u0434\u043d\u0438\u043a\u0430\u043c\u0438. \u0422\u0430\u043a\u0436\u0435 \u043d\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u044b \u043a\u043e\u043d\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0438 Spyke \u2014 \u0442\u043e \u0435\u0441\u0442\u044c \u0432 \u043a\u0430\u0436\u0434\u043e\u043c \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0443\u0447\u0430\u0441\u0442\u0432\u043e\u0432\u0430\u0442\u044c \u0440\u043e\u0432\u043d\u043e \u0434\u0432\u0430 \u0441\u043e\u0431\u0435\u0441\u0435\u0434\u043d\u0438\u043a\u0430.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439 \u0432 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430. \u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b n \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b: id1,\u2009id2,\u2009...,\u2009idn (0\u2009\u2264\u2009idi\u2009\u2264\u2009109). \u0427\u0438\u0441\u043b\u043e idi \u0440\u0430\u0432\u043d\u043e \u043d\u043e\u043c\u0435\u0440\u0443 \u0441\u0435\u0441\u0441\u0438\u0438 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f \u043d\u043e\u043c\u0435\u0440 i, \u0435\u0441\u043b\u0438 \u043e\u043d \u0440\u0430\u0437\u0433\u043e\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u0442 \u0432 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u043f\u043e Spyke, \u0438\u043b\u0438 \u0440\u0430\u0432\u043d\u043e \u043d\u0443\u043b\u044e, \u0432 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435.\n\n\u0421\u0447\u0438\u0442\u0430\u0439\u0442\u0435, \u0447\u0442\u043e \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438 \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u043e\u0442 1 \u0434\u043e n \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0440 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0435\u0439, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0432\u0435\u0434\u0443\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440 \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439, \u0438\u043b\u0438 -1, \u0435\u0441\u043b\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0437\u0430\u043a\u0440\u0430\u043b\u0430\u0441\u044c \u043e\u0448\u0438\u0431\u043a\u0430, \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u043c\u043e\u0433\u043b\u0430 \u043f\u0440\u043e\u0438\u0437\u043e\u0439\u0442\u0438.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n6\n0 1 7 1 7 10\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n3\n1 1 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n-1\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1\n0\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n0\n\n\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0435\u0441\u0442\u044c \u0434\u0432\u0430 \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u044b\u0445 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0430 \u043c\u0435\u0436\u0434\u0443 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044f\u043c\u0438: \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 2 \u0438 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 4, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 3 \u0438 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u044c \u043d\u043e\u043c\u0435\u0440 5.\n\n\u0412\u043e \u0432\u0442\u043e\u0440\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f \u043d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u0430, \u0442\u0430\u043a \u043a\u0430\u043a \u043d\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u044b \u043a\u043e\u043d\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0438.\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"} {"nl": {"description": "Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer $$$a$$$. You want to choose some integer $$$b$$$ from $$$1$$$ to $$$a - 1$$$ inclusive in such a way that the greatest common divisor (GCD) of integers $$$a \\oplus b$$$ and $$$a \\> \\& \\> b$$$ is as large as possible. In other words, you'd like to compute the following function:$$$$$$f(a) = \\max_{0 < b < a}{gcd(a \\oplus b, a \\> \\& \\> b)}.$$$$$$Here $$$\\oplus$$$ denotes the bitwise XOR operation, and $$$\\&$$$ denotes the bitwise AND operation.The greatest common divisor of two integers $$$x$$$ and $$$y$$$ is the largest integer $$$g$$$ such that both $$$x$$$ and $$$y$$$ are divided by $$$g$$$ without remainder.You are given $$$q$$$ integers $$$a_1, a_2, \\ldots, a_q$$$. For each of these integers compute the largest possible value of the greatest common divisor (when $$$b$$$ is chosen optimally). ", "input_spec": "The first line contains an integer $$$q$$$ ($$$1 \\le q \\le 10^3$$$)\u00a0\u2014 the number of integers you need to compute the answer for. After that $$$q$$$ integers are given, one per line: $$$a_1, a_2, \\ldots, a_q$$$ ($$$2 \\le a_i \\le 2^{25} - 1$$$)\u00a0\u2014 the integers you need to compute the answer for. ", "output_spec": "For each integer, print the answer in the same order as the integers are given in input.", "sample_inputs": ["3\n2\n3\n5"], "sample_outputs": ["3\n1\n7"], "notes": "NoteFor the first integer the optimal choice is $$$b = 1$$$, then $$$a \\oplus b = 3$$$, $$$a \\> \\& \\> b = 0$$$, and the greatest common divisor of $$$3$$$ and $$$0$$$ is $$$3$$$.For the second integer one optimal choice is $$$b = 2$$$, then $$$a \\oplus b = 1$$$, $$$a \\> \\& \\> b = 2$$$, and the greatest common divisor of $$$1$$$ and $$$2$$$ is $$$1$$$.For the third integer the optimal choice is $$$b = 2$$$, then $$$a \\oplus b = 7$$$, $$$a \\> \\& \\> b = 0$$$, and the greatest common divisor of $$$7$$$ and $$$0$$$ is $$$7$$$."}, "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\n REP(ni()) { _ =>\n val a = ni()\n\n val all1 = Integer.highestOneBit(a) - 1 + Integer.highestOneBit(a)\n // \u5168\u90e8\u30d3\u30c3\u30c8\u305f\u3063\u3066\u3044\u308b\u304b\u3069\u3046\u304b\n val ans = if (all1 == a) {\n // \u5168\u90e8\u30d3\u30c3\u30c8\u305f\u3063\u3066\u3044\u305f\u3089 gcd(a^b, a&b) == gcd(b, ~b)\n // b + ~b == a == (n + m) * c\n // n + m >= 2\u3067c\u3092\u6700\u5927\u5316\u306a\u306e\u3067\u3001\u3059\u306a\u308f\u3061\uff12\u756a\u76ee\u306b\u5927\u304d\u3044devisor\u3068\u3044\u3063\u3057\u3087\n val d = divisors(a)\n d(d.length - 2)\n } else {\n // 0\u306e\u30d3\u30c3\u30c8\u304c\u3042\u308b\u306e\u3067a&b==0 \u306eb\u3092\u3064\u304f\u308b\u3053\u3068\u304c\u3067\u304d\u308b\n // \u4e00\u756a\u5de6\u306f0\u306b\u306a\u308a\u3048\u306a\u3044\u306e\u3067\u3001b = ~a \u306e\u3068\u304d b^a == 2^n - 1 \u3067\u6700\u5927\u306b\u3067\u304d\u308b\n all1\n }\n out.println(ans)\n }\n }\n\n /**\n * O(\u221ax)\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"}, {"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"} {"nl": {"description": "Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the number of columns of the grid. The following two lines each contain a string consisting of $$$n$$$ characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively\u00a0\u2014 the description of the grid.", "output_spec": "For each test case, output \"YES\" if Vasya considers the grid's two rows to be identical, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["6\n\n2\n\nRG\n\nRB\n\n4\n\nGRBG\n\nGBGB\n\n5\n\nGGGGG\n\nBBBBB\n\n7\n\nBBBBBBB\n\nRRRRRRR\n\n8\n\nRGBRRGBR\n\nRGGRRBGR\n\n1\n\nG\n\nG"], "sample_outputs": ["YES\nNO\nYES\nNO\nYES\nYES"], "notes": "NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same."}, "positive_code": [{"source_code": "object _1722B 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, String, String)]\n val ans = a.replace('G', 'B') == b.replace('G', '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 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": "86a2e0854f9faf0b119d0d5e4b8fe952"} {"nl": {"description": " William really likes the cellular automaton called \"Game of Life\" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $$$n$$$ cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way: If the element is dead and it has exactly $$$1$$$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $$$i$$$ the neighbors would be elements with indices $$$i - 1$$$ and $$$i + 1$$$. If there is no element at that index, it is considered to be a dead neighbor. William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after $$$m$$$ iterations of evolution.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^3$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 10^3, 1 \\le m \\le 10^9$$$), which are the total number of cells in the array and the number of iterations. The second line of each test case contains a string of length $$$n$$$ made up of characters \"0\" and \"1\" and defines the initial state of the array. \"1\" means a cell is alive and \"0\" means it is dead. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "In each test case output a string of length $$$n$$$, made up of characters \"0\" and \"1\" \u00a0\u2014 the state of the array after $$$m$$$ iterations of evolution.", "sample_inputs": ["4\n11 3\n01000000001\n10 2\n0110100101\n5 2\n10101\n3 100\n000"], "sample_outputs": ["11111001111\n1110111101\n10101\n000"], "notes": "NoteSequence of iterations of evolution for the first test case 01000000001 \u00a0\u2014 initial state 11100000011 \u00a0\u2014 first iteration of evolution 11110000111 \u00a0\u2014 second iteration of evolution 11111001111 \u00a0\u2014 third iteration of evolution Sequence of iterations of evolution for the second test case 0110100101 \u00a0\u2014 initial state 1110111101 \u00a0\u2014 first iteration of evolution 1110111101 \u00a0\u2014 second iteration of evolution "}, "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 state = readLine().split(\"\").map(_.toInt)\r\n\r\n def go(i: Int): Boolean =\r\n if (i == 0) false\r\n else {\r\n var flag = false\r\n\r\n for {\r\n j <- 0 until n if state(j) == 0\r\n l = if (j == 0) 0 else state(j - 1)\r\n r = if (j + 1 == n) 0 else state(j + 1)\r\n sj = l ^ r if sj != state(j)\r\n } {\r\n flag = true\r\n state(j) = sj\r\n }\r\n\r\n flag && go(i - 1)\r\n }\r\n\r\n go(m)\r\n\r\n println(state.mkString(\"\"))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "9c9befb908f24a0d7481b75bfdd5780b"} {"nl": {"description": "Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A\u2009=\u2009{a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i\u2009\u2009-\u2009\u20091)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.", "input_spec": "The first line contains integers n, w, h (1\u2009\u2009\u2264\u2009n\u2009\u2264\u20095000, 1\u2009\u2264\u2009w,\u2009\u2009h\u2009\u2009\u2264\u2009106) \u2014 amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi \u2014 width and height of the i-th envelope (1\u2009\u2264\u2009wi,\u2009\u2009hi\u2009\u2264\u2009106).", "output_spec": "In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.", "sample_inputs": ["2 1 1\n2 2\n2 2", "3 3 3\n5 4\n12 11\n9 8"], "sample_outputs": ["1\n1", "3\n1 3 2"], "notes": null}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Andrew plays a game called \"Civilization\". Dima helps him.The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1,\u2009v2,\u2009...,\u2009vk, that there is a road between any contiguous cities vi and vi\u2009+\u20091 (1\u2009\u2264\u2009i\u2009<\u2009k). The length of the described path equals to (k\u2009-\u20091). We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.During the game events of two types take place: Andrew asks Dima about the length of the longest path in the region where city x lies. Andrew asks Dima to merge the region where city x lies with the region where city y lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them. Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.", "input_spec": "The first line contains three integers n, m, q (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105; 0\u2009\u2264\u2009m\u2009<\u2009n; 1\u2009\u2264\u2009q\u2009\u2264\u20093\u00b7105) \u2014 the number of cities, the number of the roads we already have and the number of queries, correspondingly. Each of the following m lines contains two integers, ai and bi (ai\u2009\u2260\u2009bi; 1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n). These numbers represent the road between cities ai and bi. There can be at most one road between two cities. Each of the following q lines contains one of the two events in the following format: 1 xi. It is the request Andrew gives to Dima to find the length of the maximum path in the region that contains city xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n). 2 xi yi. It is the request Andrew gives to Dima to merge the region that contains city xi and the region that contains city yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n). Note, that xi can be equal to yi. ", "output_spec": "For each event of the first type print the answer on a separate line.", "sample_inputs": ["6 0 6\n2 1 2\n2 3 4\n2 5 6\n2 3 2\n2 5 3\n1 1"], "sample_outputs": ["4"], "notes": null}, "positive_code": [{"source_code": "import java.awt.geom.Area\nimport java.io._\nimport java.util._\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main {\n\n var in: FastScanner = null\n var out: PrintWriter = null\n\n class Dsu(n: Int) {\n\n var p = new Array[Int](n)\n var d = new Array[Int](n)\n\n for (i <- 0 until n) {\n p(i) = i\n }\n\n def get(v: Int): Int = {\n if (p(v) == v)\n p(v)\n else {\n p(v) = get(p(v))\n p(v)\n }\n }\n\n def union(vv: Int, uu: Int) {\n val v = get(vv)\n val u = get(uu)\n if (v == u)\n return\n p(u) = v\n d(v) = un(d(v), d(u))\n }\n\n def un(d1: Int, d2: Int): Int = {\n val l1 = (1 + d1) / 2\n val l2 = (1 + d2) / 2\n Math.max(Math.max(d1, d2), l1 + l2 + 1)\n }\n }\n\n val MAX = 1000000\n val q = new Array[Int](MAX)\n\n def bfs(dist: Array[Int], from: Int, used: ArrayBuffer[Int],\n g: Array[ArrayBuffer[Int]], color: Array[Int], curColor: Int) {\n var sz = 1\n var it = 0\n q(0) = from\n dist(from) = 0\n while (it < sz) {\n val v = q(it)\n it += 1\n used.append(v)\n color(v) = curColor\n for (to <- g(v)) {\n if (dist(to) == -1) {\n dist(to) = dist(v) + 1\n q(sz) = to\n sz += 1\n }\n }\n }\n }\n\n def solve() {\n val n = in.nextInt()\n val m = in.nextInt()\n val q = in.nextInt()\n val g = new Array[ArrayBuffer[Int]](n)\n for (i <- 0 until n) {\n g(i) = new ArrayBuffer[Int]()\n }\n for (i <- 0 until m) {\n val x = in.nextInt() - 1\n val y = in.nextInt() - 1\n g(x).append(y)\n g(y).append(x)\n }\n val color = new Array[Int](n)\n for (i <- 0 until n)\n color(i) = -1\n var cntColors = 0\n val dist = new Array[Int](n)\n for (i <- 0 until n)\n dist(i) = -1\n val used = new ArrayBuffer[Int]()\n val lengths = new ArrayBuffer[Int]()\n for (i <- 0 until n) {\n if (color(i) == -1) {\n used.clear()\n bfs(dist, i, used, g, color, cntColors)\n var maxId = i\n for (to <- used) {\n if (dist(to) > dist(maxId))\n maxId = to\n }\n for ( to <- used) {\n dist(to) = -1\n }\n used.clear()\n bfs(dist, maxId, used, g, color, cntColors)\n cntColors += 1\n var maxLen = 0\n for ( to <- used) {\n maxLen = Math.max(maxLen, dist(to))\n }\n lengths.append(maxLen)\n }\n }\n\n val dsu = new Dsu(lengths.size)\n\n for (i <- 0 until lengths.size) {\n dsu.d(i) = lengths(i)\n }\n for (qq <- 0 until q) {\n if (in.nextInt() == 1) {\n out.println(dsu.d(dsu.get(color(in.nextInt() - 1))))\n } else {\n dsu.union(color(in.nextInt() - 1), color(in.nextInt() - 1))\n }\n }\n }\n\n def runIO() {\n\n in = new FastScanner(System.in)\n out = new PrintWriter(System.out)\n\n solve()\n\n out.close()\n }\n\n class FastScanner(f: InputStream) {\n\n val br = new BufferedReader(new InputStreamReader(f))\n var st : StringTokenizer = null\n\n// public FastScanner(File f) {\n// try {\n// br = new BufferedReader(new FileReader(f));\n// } catch (FileNotFoundException e) {\n// e.printStackTrace();\n// }\n// }\n\n def next(): String = {\n while (st == null || !st.hasMoreTokens) {\n var s: String = null\n try {\n s = br.readLine\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n if (s == null)\n return null\n st = new StringTokenizer(s)\n }\n st.nextToken()\n }\n\n def hasMoreTokens: Boolean = {\n while (st == null || !st.hasMoreTokens) {\n var s: String = null\n try {\n s = br.readLine()\n } catch {\n case e: IOException =>\n e.printStackTrace()\n }\n if (s == null)\n return false\n st = new StringTokenizer(s)\n }\n true\n }\n\n def nextInt() = {\n Integer.parseInt(next())\n }\n\n def nextLong() = {\n java.lang.Long.parseLong(next())\n }\n\n def nextDouble() {\n java.lang.Double.parseDouble(next())\n }\n }\n\n def main(args: Array[String]) {\n runIO()\n }\n\n}\n"}], "negative_code": [], "src_uid": "54c1d57482a1aa9c1013c2d54c5f9c13"} {"nl": {"description": "Sereja loves integer sequences very much. He especially likes stairs.Sequence a1,\u2009a2,\u2009...,\u2009a|a| (|a| is the length of the sequence) is stairs if there is such index i (1\u2009\u2264\u2009i\u2009\u2264\u2009|a|), that the following condition is met: a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009ai\u2009-\u20091\u2009<\u2009ai\u2009>\u2009ai\u2009+\u20091\u2009>\u2009...\u2009>\u2009a|a|\u2009-\u20091\u2009>\u2009a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?", "input_spec": "The first line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of Sereja's cards. The second line contains m integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u20095000) \u2014 the numbers on the Sereja's cards.", "output_spec": "In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.", "sample_inputs": ["5\n1 2 3 4 5", "6\n1 1 2 2 3 3"], "sample_outputs": ["5\n5 4 3 2 1", "5\n1 2 3 2 1"], "notes": null}, "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\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"}, {"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"} {"nl": {"description": "There are $$$n$$$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $$$x$$$ eats a slime with a value $$$y$$$, the eaten slime disappears, and the value of the remaining slime changes to $$$x - y$$$.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.", "input_spec": "The first line of the input contains an integer $$$n$$$ ($$$1 \\le n \\le 500\\,000$$$) denoting the number of slimes. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$-10^9 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the value of $$$i$$$-th slime.", "output_spec": "Print an only integer\u00a0\u2014 the maximum possible value of the last slime.", "sample_inputs": ["4\n2 1 2 1", "5\n0 -1 -1 -1 -1"], "sample_outputs": ["4", "4"], "notes": "NoteIn the first example, a possible way of getting the last slime with value $$$4$$$ is: Second slime eats the third slime, the row now contains slimes $$$2, -1, 1$$$ Second slime eats the third slime, the row now contains slimes $$$2, -2$$$ First slime eats the second slime, the row now contains $$$4$$$ In the second example, the first slime can keep eating slimes to its right to end up with a value of $$$4$$$."}, "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) out.println(A.head)\n else {\n val S = A.map(abs(_).toLong).sum\n val hasPlus = A exists (_ >= 0)\n val hasMinus = A exists (_ <= 0)\n\n val ans = if (hasMinus && hasPlus) S\n else if (hasPlus) S - 2 * A.min // plus only\n else S - 2 * abs(A.max) // minus only\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 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 S = A.map(abs(_).toLong).sum\n val hasPlus = A exists (_ >= 0)\n val hasMinus = A exists (_ <= 0)\n\n val ans = if (hasMinus && hasPlus) S\n else if (hasPlus) S - 2 * A.min // plus only\n else S - 2 * abs(A.max) // minus only\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): 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 = ni()\n val A = na(N)\n var S = 0L\n if (N == 1) {\n out.println(A(0))\n } else {\n A find (_ <= 0) match {\n case Some(_) =>\n A foreach (a => S += abs(a))\n\n case None =>\n A foreach (a => S += a)\n S -= 2 * A.min\n }\n\n out.println(S)\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}"}], "src_uid": "090f57798ba45ba9e4c9d2d0514e478c"} {"nl": {"description": "The Fair Nut found a string $$$s$$$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $$$p_1, p_2, \\ldots, p_k$$$, such that: For each $$$i$$$ ($$$1 \\leq i \\leq k$$$), $$$s_{p_i} =$$$ 'a'. For each $$$i$$$ ($$$1 \\leq i < k$$$), there is such $$$j$$$ that $$$p_i < j < p_{i + 1}$$$ and $$$s_j =$$$ 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo $$$10^9 + 7$$$.", "input_spec": "The first line contains the string $$$s$$$ ($$$1 \\leq |s| \\leq 10^5$$$) consisting of lowercase Latin letters.", "output_spec": "In a single line print the answer to the problem\u00a0\u2014 the number of such sequences $$$p_1, p_2, \\ldots, p_k$$$ modulo $$$10^9 + 7$$$.", "sample_inputs": ["abbaa", "baaaa", "agaa"], "sample_outputs": ["5", "4", "3"], "notes": "NoteIn the first example, there are $$$5$$$ possible sequences. $$$[1]$$$, $$$[4]$$$, $$$[5]$$$, $$$[1, 4]$$$, $$$[1, 5]$$$.In the second example, there are $$$4$$$ possible sequences. $$$[2]$$$, $$$[3]$$$, $$$[4]$$$, $$$[5]$$$.In the third example, there are $$$3$$$ possible sequences. $$$[1]$$$, $$$[3]$$$, $$$[4]$$$."}, "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 // aa\u306e\u7d44\u307f\u5408\u308f\u305b, \u76f4\u524d\u306eba\u306e\u7d44\u307f\u5408\u308f\u305b\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}"}, {"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"} {"nl": {"description": "Polycarpus is a system administrator. There are two servers under his strict guidance \u2014 a and b. To stay informed about the servers' performance, Polycarpus executes commands \"ping a\" and \"ping b\". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x\u2009+\u2009y\u2009=\u200910;\u00a0x,\u2009y\u2009\u2265\u20090). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is \"alive\" or not. Polycarpus thinks that the server is \"alive\", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is \"alive\" or not by the given commands and their results.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers \u2014 the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1\u2009\u2264\u2009ti\u2009\u2264\u20092;\u00a0xi,\u2009yi\u2009\u2265\u20090;\u00a0xi\u2009+\u2009yi\u2009=\u200910). If ti\u2009=\u20091, then the i-th command is \"ping a\", otherwise the i-th command is \"ping b\". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one \"ping a\" command and at least one \"ping b\" command.", "output_spec": "In the first line print string \"LIVE\" (without the quotes) if server a is \"alive\", otherwise print \"DEAD\" (without the quotes). In the second line print the state of server b in the similar format.", "sample_inputs": ["2\n1 5 5\n2 6 4", "3\n1 0 10\n2 0 10\n1 10 0"], "sample_outputs": ["LIVE\nLIVE", "LIVE\nDEAD"], "notes": "NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network."}, "positive_code": [{"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": "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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "1d8870a705036b9820227309d74dd1e8"} {"nl": {"description": "Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form: You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\\frac{x}{u} + \\frac{y}{v} = \\frac{x + y}{u + v}.$$$$$$ The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \\neq (0, 0)$$$. Please help Ivan to solve some equations of this form.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\leq u, v \\leq 10^9$$$) \u2014 the parameters of the equation.", "output_spec": "For each test case print two integers $$$x$$$, $$$y$$$ \u2014 a possible solution to the equation. It should be satisfied that $$$-10^{18} \\leq x, y \\leq 10^{18}$$$ and $$$(x, y) \\neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.", "sample_inputs": ["4\n1 1\n2 3\n3 5\n6 9"], "sample_outputs": ["-1 1\n-4 9\n-18 50\n-4 9"], "notes": "NoteIn the first test case: $$$\\frac{-1}{1} + \\frac{1}{1} = 0 = \\frac{-1 + 1}{1 + 1}$$$.In the second test case: $$$\\frac{-4}{2} + \\frac{9}{3} = 1 = \\frac{-4 + 9}{2 + 3}$$$.In the third test case: $$$\\frac{-18}{3} + \\frac{50}{5} = 4 = \\frac{-18 + 50}{3 + 5}$$$.In the fourth test case: $$$\\frac{-4}{6} + \\frac{9}{9} = \\frac{1}{3} = \\frac{-4 + 9}{6 + 9}$$$."}, "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 var n = readLong()\n var k = readLong()\n n = -1L * n * n\n k = k * k\n writer.println(n + \" \" + k)\n\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "4dfa99acbe06b314f0f0b934237c66f3"} {"nl": {"description": "Monocarp has forgotten the password to his mobile phone. The password consists of $$$4$$$ digits from $$$0$$$ to $$$9$$$ (note that it can start with the digit $$$0$$$).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of $$$4$$$ digits that could be the password for Monocarp's mobile phone (i.\u2009e. these sequences should meet all constraints on Monocarp's password).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 8$$$)\u00a0\u2014 the number of digits for which Monocarp remembers that they were not used in the password. The second line contains $$$n$$$ different integers $$$a_1, a_2, \\dots a_n$$$ ($$$0 \\le a_i \\le 9$$$) representing the digits that were not used in the password. Note that the digits $$$a_1, a_2, \\dots, a_n$$$ are given in ascending order.", "output_spec": "For each testcase, print one integer\u00a0\u2014 the number of different $$$4$$$-digit sequences that meet the constraints.", "sample_inputs": ["2\n\n8\n\n0 1 2 4 5 6 8 9\n\n1\n\n8"], "sample_outputs": ["6\n216"], "notes": "NoteIn the first example, all possible passwords are: \"3377\", \"3737\", \"3773\", \"7337\", \"7373\", \"7733\"."}, "positive_code": [{"source_code": "object _1743A extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val unused = io.nextN(io.nextInt()).toSet\n var ans = 0\n for {\n d1 <- 0 to 9 if !unused.contains(d1)\n d2 <- 0 to 9 if !unused.contains(d2) if d1 < d2\n } ans += 6\n io.printLine(ans)\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": [], "src_uid": "33e751f5716cbd666be36ab8f5e3977e"} {"nl": {"description": "Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s\u2009=\u2009s1s2... sn (n is the length of the string), consisting only of characters \".\" and \"#\" and m queries. Each query is described by a pair of integers li,\u2009ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n). The answer to the query li,\u2009ri is the number of such integers i (li\u2009\u2264\u2009i\u2009<\u2009ri), that si\u2009=\u2009si\u2009+\u20091.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.", "input_spec": "The first line contains string s of length n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). It is guaranteed that the given string only consists of characters \".\" and \"#\". The next line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li,\u2009ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print m integers \u2014 the answers to the queries in the order in which they are given in the input.", "sample_inputs": ["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"], "sample_outputs": ["1\n1\n5\n4", "1\n1\n2\n2\n0"], "notes": null}, "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 def main(args: Array[String]) {\n taskB\n }\n}"}, {"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"}, {"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"}, {"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 }"}], "negative_code": [], "src_uid": "b30e09449309b999473e4be6643d68cd"} {"nl": {"description": "You are given an integer $$$n$$$. You have to construct a permutation of size $$$n$$$.A permutation is an array where each integer from $$$1$$$ to $$$s$$$ (where $$$s$$$ is the size of permutation) occurs exactly once. For example, $$$[2, 1, 4, 3]$$$ is a permutation of size $$$4$$$; $$$[1, 2, 4, 5, 3]$$$ is a permutation of size $$$5$$$; $$$[1, 4, 3]$$$ is not a permutation (the integer $$$2$$$ is absent), $$$[2, 1, 3, 1]$$$ is not a permutation (the integer $$$1$$$ appears twice).A subsegment of a permutation is a contiguous subsequence of that permutation. For example, the permutation $$$[2, 1, 4, 3]$$$ has $$$10$$$ subsegments: $$$[2]$$$, $$$[2, 1]$$$, $$$[2, 1, 4]$$$, $$$[2, 1, 4, 3]$$$, $$$[1]$$$, $$$[1, 4]$$$, $$$[1, 4, 3]$$$, $$$[4]$$$, $$$[4, 3]$$$ and $$$[3]$$$.The value of the permutation is the number of its subsegments which are also permutations. For example, the value of $$$[2, 1, 4, 3]$$$ is $$$3$$$ since the subsegments $$$[2, 1]$$$, $$$[1]$$$ and $$$[2, 1, 4, 3]$$$ are permutations.You have to construct a permutation of size $$$n$$$ with minimum possible value among all permutations of size $$$n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 48$$$) \u2014 the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th of them contains one integer $$$n$$$ ($$$3 \\le n \\le 50$$$) representing the $$$i$$$-th test case.", "output_spec": "For each test case, print $$$n$$$ integers \u2014 the permutation of size $$$n$$$ with minimum possible value. If there are multiple such permutations, print any of them.", "sample_inputs": ["2\n\n5\n\n6"], "sample_outputs": ["1 4 3 5 2\n4 1 6 2 5 3"], "notes": "NoteIn the first example, the permutation $$$[1, 4, 3, 5, 2]$$$ is one of the possible answers; its value is $$$2$$$.In the second example, the permutation $$$[4, 1, 6, 2, 5, 3]$$$ is one of the possible answers; its value is $$$2$$$."}, "positive_code": [{"source_code": "object _1743B extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n = io.nextInt()\n val ans = Array.ofDim[Int](n)\n ans(0) = 1\n ans(n-1) = 2\n (1 until n-1).foreach(i => ans(i) = i+2)\n io.printLine(ans: _*)\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": [], "src_uid": "6fced7d8ac3dd58b1791430ada53332d"} {"nl": {"description": "You are given a board of size $$$n \\times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n < 5 \\cdot 10^5$$$) \u2014 the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \\cdot 10^5$$$ ($$$\\sum n \\le 5 \\cdot 10^5$$$).", "output_spec": "For each test case print the answer \u2014 the minimum number of moves needed to get all the figures into one cell.", "sample_inputs": ["3\n1\n5\n499993"], "sample_outputs": ["0\n40\n41664916690999888"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. Each $$$a_i$$$ is one of the six following numbers: $$$4, 8, 15, 16, 23, 42$$$.Your task is to remove the minimum number of elements to make this array good.An array of length $$$k$$$ is called good if $$$k$$$ is divisible by $$$6$$$ and it is possible to split it into $$$\\frac{k}{6}$$$ subsequences $$$4, 8, 15, 16, 23, 42$$$.Examples of good arrays: $$$[4, 8, 15, 16, 23, 42]$$$ (the whole array is a required sequence); $$$[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$$$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements); $$$[]$$$ (the empty array is good). Examples of bad arrays: $$$[4, 8, 15, 16, 42, 23]$$$ (the order of elements should be exactly $$$4, 8, 15, 16, 23, 42$$$); $$$[4, 8, 15, 16, 23, 42, 4]$$$ (the length of the array is not divisible by $$$6$$$); $$$[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$$$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence). ", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 5 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ (each $$$a_i$$$ is one of the following numbers: $$$4, 8, 15, 16, 23, 42$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer \u2014 the minimum number of elements you have to remove to obtain a good array.", "sample_inputs": ["5\n4 8 15 16 23", "12\n4 8 4 15 16 8 23 15 16 42 23 42", "15\n4 8 4 8 15 16 8 16 23 15 16 4 42 23 42"], "sample_outputs": ["5", "0", "3"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 20000$$$) \u2014 the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \\le |s| \\le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.", "output_spec": "For each test case, print one integer \u2014 the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.", "sample_inputs": ["7\n123\n12222133333332\n112233\n332211\n12121212\n333333\n31121"], "sample_outputs": ["3\n3\n4\n4\n0\n0\n4"], "notes": "NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used."}, "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 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"}, {"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"} {"nl": {"description": "Bessie is out grazing on the farm, which consists of $$$n$$$ fields connected by $$$m$$$ bidirectional roads. She is currently at field $$$1$$$, and will return to her home at field $$$n$$$ at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $$$k$$$ special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field $$$1$$$ to field $$$n$$$. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!", "input_spec": "The first line contains integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$n-1 \\le m \\le 2 \\cdot 10^5$$$, $$$2 \\le k \\le n$$$) \u00a0\u2014 the number of fields on the farm, the number of roads, and the number of special fields. The second line contains $$$k$$$ integers $$$a_1, a_2, \\ldots, a_k$$$ ($$$1 \\le a_i \\le n$$$) \u00a0\u2014 the special fields. All $$$a_i$$$ are distinct. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$, $$$x_i \\ne y_i$$$), representing a bidirectional road between fields $$$x_i$$$ and $$$y_i$$$. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.", "output_spec": "Output one integer, the maximum possible length of the shortest path from field $$$1$$$ to $$$n$$$ after Farmer John installs one road optimally.", "sample_inputs": ["5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4", "5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5"], "sample_outputs": ["3", "3"], "notes": "NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields $$$3$$$ and $$$5$$$, and the resulting shortest path from $$$1$$$ to $$$5$$$ is length $$$3$$$. The graph for the second example is shown below. Farmer John must add a road between fields $$$2$$$ and $$$4$$$, and the resulting shortest path from $$$1$$$ to $$$5$$$ is length $$$3$$$. "}, "positive_code": [{"source_code": "object Main {\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 //\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 m = in.nextInt()\n val k = in.nextInt()\n\n val edges = Array.fill(n+1)(ListBuffer.empty[Int])\n val visited = Array.fill(n+1)(false)\n def buildShortesPat(a: Array[Int],node: Int): Unit = {\n val q = mutable.Queue.empty[Int]\n q.enqueue(node)\n //a.indices.foreach(i => a(i) = Int.MaxValue)\n a(node) = 0\n visited(node) = true\n while(q.nonEmpty){\n val x = q.dequeue()\n edges(x).filter(u => !visited(u)).foreach{ u =>\n a(u) = a(x) +1\n visited(u) = true\n q.enqueue(u)\n }\n\n\n }\n\n\n\n }\n val specialFields = (1 to k).map(_ => in.nextInt())\n (1 to m).foreach{ _ =>\n val (x,y) = (in.nextInt(),in.nextInt())\n edges(x).append(y)\n edges(y).append(x)\n }\n\n val toEnd = Array.fill(n+1)(0)\n val fromBegin = Array.fill(n+1)(0)\n buildShortesPat(toEnd,n)\n visited.indices.foreach(i => visited(i) = false)\n buildShortesPat(fromBegin,1)\n\n val gs = specialFields.map(f => (f,fromBegin(f))).sortBy(_._2).toList.map(_._1)\n val minLength = fromBegin(n)\n val res = gs.zip(gs.tail).map{\n case (f,g) => {\n if(fromBegin(f) +1 + toEnd(g) <= minLength){\n fromBegin(f) +1 + toEnd(g)\n }else{\n minLength\n }\n }\n }.max\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}"}], "negative_code": [], "src_uid": "dc044b8fe01b0a94638139cea034b1a8"} {"nl": {"description": "\"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme.\"\"Little Alena got an array as a birthday present...\"The array b of length n is obtained from the array a of length n and two integers l and r\u00a0(l\u2009\u2264\u2009r) using the following procedure:b1\u2009=\u2009b2\u2009=\u2009b3\u2009=\u2009b4\u2009=\u20090.For all 5\u2009\u2264\u2009i\u2009\u2264\u2009n: bi\u2009=\u20090 if ai,\u2009ai\u2009-\u20091,\u2009ai\u2009-\u20092,\u2009ai\u2009-\u20093,\u2009ai\u2009-\u20094\u2009>\u2009r and bi\u2009-\u20091\u2009=\u2009bi\u2009-\u20092\u2009=\u2009bi\u2009-\u20093\u2009=\u2009bi\u2009-\u20094\u2009=\u20091 bi\u2009=\u20091 if ai,\u2009ai\u2009-\u20091,\u2009ai\u2009-\u20092,\u2009ai\u2009-\u20093,\u2009ai\u2009-\u20094\u2009<\u2009l and bi\u2009-\u20091\u2009=\u2009bi\u2009-\u20092\u2009=\u2009bi\u2009-\u20093\u2009=\u2009bi\u2009-\u20094\u2009=\u20090 bi\u2009=\u2009bi\u2009-\u20091 otherwise You are given arrays a and b' of the same length. Find two integers l and r\u00a0(l\u2009\u2264\u2009r), such that applying the algorithm described above will yield an array b equal to b'.It's guaranteed that the answer exists.", "input_spec": "The first line of input contains a single integer n (5\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the length of a and b'. The second line of input contains n space separated integers a1,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of a. The third line of input contains a string of n characters, consisting of 0 and 1\u00a0\u2014 the elements of b'. Note that they are not separated by spaces.", "output_spec": "Output two integers l and r\u00a0(\u2009-\u2009109\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009109), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists.", "sample_inputs": ["5\n1 2 3 4 5\n00001", "10\n-10 -9 -8 -7 -6 6 7 8 9 10\n0000111110"], "sample_outputs": ["6 15", "-5 5"], "notes": "NoteIn the first test case any pair of l and r pair is valid, if 6\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009109, in that case b5\u2009=\u20091, because a1,\u2009...,\u2009a5\u2009<\u2009l."}, "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"}, {"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"}], "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"} {"nl": {"description": "It has finally been decided to build a roof over the football field in School 179. Its construction will require placing $$$n$$$ consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation $$$p$$$ of integers from $$$0$$$ to $$$n - 1$$$, where $$$p_i$$$ is the height of the $$$i$$$-th pillar from the left $$$(1 \\le i \\le n)$$$.As the chief, you know that the cost of construction of consecutive pillars is equal to the maximum value of the bitwise XOR of heights of all pairs of adjacent pillars. In other words, the cost of construction is equal to $$$\\max\\limits_{1 \\le i \\le n - 1}{p_i \\oplus p_{i + 1}}$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation.Find any sequence of pillar heights $$$p$$$ of length $$$n$$$ with the smallest construction cost.In this problem, a permutation is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n - 1$$$ in arbitrary order. For example, $$$[2,3,1,0,4]$$$ is a permutation, but $$$[1,0,1]$$$ is not a permutation ($$$1$$$ appears twice in the array) and $$$[1,0,3]$$$ is also not a permutation ($$$n=3$$$, but $$$3$$$ is in the array).", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The only line for each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of pillars for the construction of the roof. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\\ldots$$$, $$$p_n$$$ \u2014 the sequence of pillar heights with the smallest construction cost. If there are multiple answers, print any of them.", "sample_inputs": ["4\n2\n3\n5\n10"], "sample_outputs": ["0 1\n2 0 1\n3 2 1 0 4\n4 6 3 2 0 8 9 1 7 5"], "notes": "NoteFor $$$n = 2$$$ there are $$$2$$$ sequences of pillar heights: $$$[0, 1]$$$ \u2014 cost of construction is $$$0 \\oplus 1 = 1$$$. $$$[1, 0]$$$ \u2014 cost of construction is $$$1 \\oplus 0 = 1$$$. For $$$n = 3$$$ there are $$$6$$$ sequences of pillar heights: $$$[0, 1, 2]$$$ \u2014 cost of construction is $$$\\max(0 \\oplus 1, 1 \\oplus 2) = \\max(1, 3) = 3$$$. $$$[0, 2, 1]$$$ \u2014 cost of construction is $$$\\max(0 \\oplus 2, 2 \\oplus 1) = \\max(2, 3) = 3$$$. $$$[1, 0, 2]$$$ \u2014 cost of construction is $$$\\max(1 \\oplus 0, 0 \\oplus 2) = \\max(1, 2) = 2$$$. $$$[1, 2, 0]$$$ \u2014 cost of construction is $$$\\max(1 \\oplus 2, 2 \\oplus 0) = \\max(3, 2) = 3$$$. $$$[2, 0, 1]$$$ \u2014 cost of construction is $$$\\max(2 \\oplus 0, 0 \\oplus 1) = \\max(2, 1) = 2$$$. $$$[2, 1, 0]$$$ \u2014 cost of construction is $$$\\max(2 \\oplus 1, 1 \\oplus 0) = \\max(3, 1) = 3$$$. "}, "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 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"}, {"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 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"}], "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"} {"nl": {"description": "Little penguin Polo has got a tree \u2014 a non-directed connected acyclic graph, containing n nodes and n\u2009-\u20091 edges. We will consider the tree nodes numbered by integers from 1 to n.Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers a,\u2009b,\u2009c and d such that: 1\u2009\u2264\u2009a\u2009<\u2009b\u2009\u2264\u2009n; 1\u2009\u2264\u2009c\u2009<\u2009d\u2009\u2264\u2009n; there's no such node that lies on both the shortest path from node a to node b and from node c to node d. The shortest path betweem two nodes is the path that is shortest in the number of edges.Help Polo solve this problem.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200980000) \u2014 the number of tree nodes. Each of the following n\u2009-\u20091 lines contains a pair of integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n;\u00a0ui\u2009\u2260\u2009vi) \u2014 the i-th edge of the tree. It is guaranteed that the given graph is a tree.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem. Please do not use the %lld specificator to read or write 64-bit numbers in \u0421++. It is recommended to use the cin, cout streams or the %I64d specificator.", "sample_inputs": ["4\n1 2\n2 3\n3 4"], "sample_outputs": ["2"], "notes": null}, "positive_code": [{"source_code": "import collection.mutable.ArrayBuffer\nimport io.Source\nimport java.io.PrintWriter\n\nobject CF288D {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val edges = Array.fill(n)(ArrayBuffer.empty[Int])\n for (it <- 0 until n - 1) {\n val u, v = in().toInt - 1\n// val u = it\n// val v = it + 1\n edges(u) += v\n edges(v) += u\n }\n var ans = BigInt(0)\n def dfs(u: Int, p: Int): Long = {\n var size = 1L\n val d = Array.fill(2, 5)(0L)\n d(0)(0) = 1\n def regSubtree(s: Long) {\n for (i <- 1.to(0, -1); j <- 4.to(0, -1)) {\n if (i < 1) {\n d(i + 1)(j) += d(i)(j) * s * s\n }\n if (j < 4) {\n d(i)(j + 1) += d(i)(j) * s\n }\n }\n }\n var it = 0\n while (it < edges(u).size) {\n val v = edges(u)(it)\n if (v != p) {\n val sub = dfs(v, u)\n size += sub\n regSubtree(sub)\n }\n it += 1\n }\n if (p != -1) {\n regSubtree(n - size)\n }\n// out.println(u, d(1)(2), d(0)(4), d(1)(1), d(0)(3), d(1)(0), d(0)(2))\n ans += d(1)(2) * BigInt(2) + d(0)(4) * BigInt(12) + d(1)(1) * 2 + d(0)(3) * 12 + d(1)(0) + d(0)(2) * 4\n size\n }\n dfs(0, -1)\n assert(ans % 2 == 0)\n ans = BigInt(n.toLong * (n - 1) / 2) * (n.toLong * (n - 1) / 2) - ans / 2\n out.println(ans)\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 }, \"thread\", 64000000).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": [{"source_code": "import collection.mutable.ArrayBuffer\nimport io.Source\nimport java.io.PrintWriter\n\nobject CF288D {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val edges = Array.fill(n)(ArrayBuffer.empty[Int])\n for (it <- 0 until n - 1) {\n val u, v = in().toInt - 1\n// val u = it\n// val v = it + 1\n edges(u) += v\n edges(v) += u\n }\n var ans = BigInt(0)\n def dfs(u: Int, p: Int): Long = {\n var size = 1L\n val d = Array.fill(2, 5)(0L)\n d(0)(0) = 1\n def regSubtree(s: Long) {\n for (i <- 1.to(0, -1); j <- 4.to(0, -1)) {\n if (i < 1) {\n d(i + 1)(j) += d(i)(j) * s * s\n }\n if (j < 4) {\n d(i)(j + 1) += d(i)(j) * s\n }\n }\n }\n var it = 0\n while (it < edges(u).size) {\n val v = edges(u)(it)\n if (v != p) {\n val sub = dfs(v, u)\n size += sub\n regSubtree(sub)\n }\n it += 1\n }\n if (p != -1) {\n regSubtree(n - size)\n }\n// out.println(u, d(1)(2), d(0)(4), d(1)(1), d(0)(3), d(1)(0), d(0)(2))\n ans += d(1)(2) * 2 + d(0)(4) * 12 + d(1)(1) * 2 + d(0)(3) * 12 + d(1)(0) + d(0)(2) * 2 * 2\n size\n }\n dfs(0, -1)\n assert(ans % 2 == 0)\n ans = BigInt(n.toLong * (n - 1) / 2) * (n.toLong * (n - 1) / 2) - ans / 2\n out.println(ans)\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 }, \"thread\", 64000000).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}"}], "src_uid": "a1631f068c8da218243a9ab0aced4f16"} {"nl": {"description": "Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p\u2009=\u2009p0,\u2009p1,\u2009...,\u2009pn, Polo has defined its beauty \u2014 number .Expression means applying the operation of bitwise excluding \"OR\" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as \"^\" and in Pascal \u2014 as \"xor\".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.", "input_spec": "The single line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106).", "output_spec": "In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m. If there are several suitable permutations, you are allowed to print any of them.", "sample_inputs": ["4"], "sample_outputs": ["20\n0 2 1 4 3"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "A sequence $$$a = [a_1, a_2, \\ldots, a_l]$$$ of length $$$l$$$ has an ascent if there exists a pair of indices $$$(i, j)$$$ such that $$$1 \\le i < j \\le l$$$ and $$$a_i < a_j$$$. For example, the sequence $$$[0, 2, 0, 2, 0]$$$ has an ascent because of the pair $$$(1, 4)$$$, but the sequence $$$[4, 3, 3, 3, 1]$$$ doesn't have an ascent.Let's call a concatenation of sequences $$$p$$$ and $$$q$$$ the sequence that is obtained by writing down sequences $$$p$$$ and $$$q$$$ one right after another without changing the order. For example, the concatenation of the $$$[0, 2, 0, 2, 0]$$$ and $$$[4, 3, 3, 3, 1]$$$ is the sequence $$$[0, 2, 0, 2, 0, 4, 3, 3, 3, 1]$$$. The concatenation of sequences $$$p$$$ and $$$q$$$ is denoted as $$$p+q$$$.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has $$$n$$$ sequences $$$s_1, s_2, \\ldots, s_n$$$ which may have different lengths. Gyeonggeun will consider all $$$n^2$$$ pairs of sequences $$$s_x$$$ and $$$s_y$$$ ($$$1 \\le x, y \\le n$$$), and will check if its concatenation $$$s_x + s_y$$$ has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs ($$$x, y$$$) of sequences $$$s_1, s_2, \\ldots, s_n$$$ whose concatenation $$$s_x + s_y$$$ contains an ascent.", "input_spec": "The first line contains the number $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$) denoting the number of sequences. The next $$$n$$$ lines contain the number $$$l_i$$$ ($$$1 \\le l_i$$$) denoting the length of $$$s_i$$$, followed by $$$l_i$$$ integers $$$s_{i, 1}, s_{i, 2}, \\ldots, s_{i, l_i}$$$ ($$$0 \\le s_{i, j} \\le 10^6$$$) denoting the sequence $$$s_i$$$. It is guaranteed that the sum of all $$$l_i$$$ does not exceed $$$100\\,000$$$.", "output_spec": "Print a single integer, the number of pairs of sequences whose concatenation has an ascent.", "sample_inputs": ["5\n1 1\n1 1\n1 2\n1 4\n1 3", "3\n4 2 0 2 0\n6 9 9 8 8 7 7\n1 6", "10\n3 62 24 39\n1 17\n1 99\n1 60\n1 64\n1 30\n2 79 29\n2 20 73\n2 85 37\n1 100"], "sample_outputs": ["9", "7", "72"], "notes": "NoteFor the first example, the following $$$9$$$ arrays have an ascent: $$$[1, 2], [1, 2], [1, 3], [1, 3], [1, 4], [1, 4], [2, 3], [2, 4], [3, 4]$$$. Arrays with the same contents are counted as their occurences."}, "positive_code": [{"source_code": "import java.util\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = Array.fill(n) {\n val l = nextInt\n nextInts(l)\n }\n\n val mins = xs.map(_.min)\n val maxs = xs.map(_.max)\n\n def isAsc(as: Array[Int]): Boolean = {\n var min = as.head\n var res = false\n for (i <- 1 until as.length) {\n if (as(i) < min) min = as(i)\n else if (as(i) > min) res = true\n }\n res\n }\n\n val asc = xs.map(isAsc)\n val ascCount: Long = asc.count(identity)\n val maxNonAsc = ((for {\n i <- 0 until n\n if !asc(i)\n } yield maxs(i) * 10000000L + i) :+ 10000000L * 10000000L).toArray.sorted\n\n var res: Long = ascCount * n + (n - ascCount) * ascCount\n//println(ascCount, res)\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, x: Long): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (maxNonAsc(mid) >= x) binSearch(low, mid - 1, x)\n else binSearch(mid + 1, hi, x)\n }\n }\n//println(maxNonAsc.mkString(\" \"))\n for (i <- 0 until n) {\n if (!asc(i)) {\n val c = maxNonAsc.length - binSearch(0, maxNonAsc.length, (mins(i) + 1) * 10000000L) - 1\n // println(mins(i), c)\n res += c\n }\n }\n\n out.println(res)\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 java.util\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = Array.fill(n) {\n val l = nextInt\n nextInts(l)\n }\n\n val mins = xs.map(_.min)\n val maxs = xs.map(_.max)\n\n def isAsc(as: Array[Int]): Boolean = {\n var min = as.head\n var res = false\n for (i <- 1 until as.length) {\n if (as(i) < min) min = as(i)\n else if (as(i) > min) res = true\n }\n res\n }\n\n val asc = xs.map(isAsc)\n val ascCount = asc.count(identity)\n val maxNonAsc = ((for {\n i <- 0 until n\n if !asc(i)\n } yield maxs(i) * 10000000L + i) :+ 10000000L * 10000000L).toArray.sorted\n\n var res: Long = ascCount * n + (n - ascCount) * ascCount\n//println(ascCount, res)\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, x: Long): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (maxNonAsc(mid) >= x) binSearch(low, mid - 1, x)\n else binSearch(mid + 1, hi, x)\n }\n }\n//println(maxNonAsc.mkString(\" \"))\n for (i <- 0 until n) {\n if (!asc(i)) {\n val c = maxNonAsc.length - binSearch(0, maxNonAsc.length, (mins(i) + 1) * 10000000L) - 1\n // println(mins(i), c)\n res += c\n }\n }\n\n out.println(res)\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 java.util\n\nobject B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val n = nextInt\n val xs = Array.fill(n) {\n val l = nextInt\n nextInts(l)\n }\n\n val mins = xs.map(_.min)\n val maxs = xs.map(_.max)\n\n def isAsc(as: Array[Int]): Boolean = {\n var min = as.head\n var res = false\n for (i <- 1 until as.length) {\n if (as(i) < min) min = as(i)\n else if (as(i) > min) res = true\n }\n res\n }\n\n val asc = xs.map(isAsc)\n val ascCount = asc.count(identity)\n val maxNonAsc = ((for {\n i <- 0 until n\n if !asc(i)\n } yield maxs(i) * 10000000L + i) :+ 10000000L * 10000000L).toArray.sorted\n\n var res = ascCount * n + (n - ascCount) * ascCount\n//println(ascCount, res)\n @annotation.tailrec\n def binSearch(low: Int, hi: Int, x: Long): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (maxNonAsc(mid) >= x) binSearch(low, mid - 1, x)\n else binSearch(mid + 1, hi, x)\n }\n }\n//println(maxNonAsc.mkString(\" \"))\n for (i <- 0 until n) {\n if (!asc(i)) {\n val c = maxNonAsc.length - binSearch(0, maxNonAsc.length, (mins(i) + 1) * 10000000L) - 1\n // println(mins(i), c)\n res += c\n }\n }\n\n out.println(res)\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": "b6b60d1e21e51771d6ba2a8b41619296"} {"nl": {"description": "Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1,\u2009a2,\u2009...,\u2009an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1,\u2009b2,\u2009...,\u2009bm will be as large as possible.Find this maximum possible value of the minimum among the bj (1\u2009\u2264\u2009j\u2009\u2264\u2009m), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u20092000). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the performer of the i-th song.", "output_spec": "In the first line print two integers: the maximum possible value of the minimum among the bj (1\u2009\u2264\u2009j\u2009\u2264\u2009m), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make. In the second line print the changed playlist. If there are multiple answers, print any of them.", "sample_inputs": ["4 2\n1 2 3 2", "7 3\n1 3 2 2 2 2 1", "4 4\n1000000000 100 7 1000000000"], "sample_outputs": ["2 1\n1 2 1 2", "2 1\n1 3 3 2 2 2 1", "1 4\n1 2 3 4"], "notes": "NoteIn the first sample, after Polycarp's changes the first band performs two songs (b1\u2009=\u20092), and the second band also performs two songs (b2\u2009=\u20092). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist. In the second sample, after Polycarp's changes the first band performs two songs (b1\u2009=\u20092), the second band performs three songs (b2\u2009=\u20093), and the third band also performs two songs (b3\u2009=\u20092). Thus, the best minimum value is 2. "}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Given an array $$$a$$$ of $$$n$$$ elements, print any value that appears at least three times or print -1 if there is no such value.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2\\cdot10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq n$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each test case, print any value that appears at least three times or print -1 if there is no such value.", "sample_inputs": ["7\n\n1\n\n1\n\n3\n\n2 2 2\n\n7\n\n2 2 3 3 4 2 2\n\n8\n\n1 4 3 4 3 2 4 1\n\n9\n\n1 1 1 2 2 2 3 3 3\n\n5\n\n1 5 2 4 3\n\n4\n\n4 4 4 4"], "sample_outputs": ["-1\n2\n2\n4\n3\n-1\n4"], "notes": "NoteIn the first test case there is just a single element, so it can't occur at least three times and the answer is -1.In the second test case, all three elements of the array are equal to $$$2$$$, so $$$2$$$ occurs three times, and so the answer is $$$2$$$.For the third test case, $$$2$$$ occurs four times, so the answer is $$$2$$$.For the fourth test case, $$$4$$$ occurs three times, so the answer is $$$4$$$.For the fifth test case, $$$1$$$, $$$2$$$ and $$$3$$$ all occur at least three times, so they are all valid outputs.For the sixth test case, all elements are distinct, so none of them occurs at least three times and the answer is -1."}, "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n *\r\n * \u0412\u0430\u043c \u0437\u0430\u0434\u0430\u043d \u043c\u0430\u0441\u0441\u0438\u0432 \ud835\udc4e \u0438\u0437 \ud835\udc5b \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432. \u041d\u0430\u0439\u0434\u0438\u0442\u0435 \u043b\u044e\u0431\u043e\u0435 \u0447\u0438\u0441\u043b\u043e, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u0435\u0442\u0441\u044f \u0432 \u044d\u0442\u043e\u043c \u043c\u0430\u0441\u0441\u0438\u0432\u0435 \u0445\u043e\u0442\u044f \u0431\u044b \u0442\u0440\u0438 \u0440\u0430\u0437\u0430, \u0438\u043b\u0438 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 -1, \u0435\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445 \u0447\u0438\u0441\u0435\u043b \u043d\u0435\u0442.\r\n *\r\n * \u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\r\n * \u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \ud835\udc61 (1\u2264\ud835\udc61\u2264104) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043d\u0430\u0431\u043e\u0440\u043e\u0432 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445.\r\n *\r\n * \u041f\u0435\u0440\u0432\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u043d\u0430\u0431\u043e\u0440\u0430 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043e\u0434\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \ud835\udc5b (1\u2264\ud835\udc5b\u22642\u22c5105) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435.\r\n *\r\n * \u0412\u0442\u043e\u0440\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u043d\u0430\u0431\u043e\u0440\u0430 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \ud835\udc5b \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \ud835\udc4e1,\ud835\udc4e2,\u2026,\ud835\udc4e\ud835\udc5b (1\u2264\ud835\udc4e\ud835\udc56\u2264\ud835\udc5b) \u2014 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b \u043c\u0430\u0441\u0441\u0438\u0432\u0430.\r\n *\r\n * \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0441\u0443\u043c\u043c\u0430 \ud835\udc5b \u043f\u043e \u0432\u0441\u0435\u043c \u043d\u0430\u0431\u043e\u0440\u0430\u043c \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u043d\u0435 \u043f\u0440\u0435\u0432\u043e\u0441\u0445\u043e\u0434\u0438\u0442 2\u22c5105.\r\n *\r\n * \u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\r\n * \u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u043d\u0430\u0431\u043e\u0440\u0430 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043b\u044e\u0431\u043e\u0435 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u0435\u0442\u0441\u044f \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 \u0445\u043e\u0442\u044f \u0431\u044b \u0442\u0440\u0438 \u0440\u0430\u0437\u0430, \u0438\u043b\u0438 -1, \u0435\u0441\u043b\u0438 \u0442\u0430\u043a\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u043d\u0435\u0442.\r\n */\r\n\r\n\r\nobject Task2 extends App {\r\n\r\n def getNextNum = StdIn.readLine().toInt\r\n\r\n def createResultMap = scala.collection.mutable.Map[Int, Int]().withDefaultValue(0)\r\n\r\n val inputSize = getNextNum\r\n\r\n for (_ <- 0 until inputSize) {\r\n getNextNum\r\n val array = StdIn.readLine().split(\" \").map(_.toInt)\r\n val counterMap = createResultMap\r\n var gotResult = false\r\n var pos = 0\r\n\r\n do {\r\n counterMap(array(pos)) += 1\r\n if (counterMap(array(pos)) == 3) {\r\n println(array(pos))\r\n gotResult = true\r\n }\r\n pos += 1\r\n } while (!gotResult && pos < array.length)\r\n\r\n if (!gotResult) {\r\n println(-1)\r\n }\r\n\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "7d4174e3ae76de7b1389f618eb89d334"} {"nl": {"description": "You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) of array s equals . The operation x\u00a0mod\u00a0y means that we take the remainder of the division of number x by number y. Then we write the contents of the array s to the array a. Element number i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) of the array s becomes the i-th element of the array a (ai\u2009=\u2009si). You task is to find array a after exactly k described operations are applied.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092000, 0\u2009\u2264\u2009k\u2009\u2264\u2009109). The next line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an\u00a0\u2014 elements of the array a (0\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print n integers \u00a0\u2014 elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.", "sample_inputs": ["3 1\n1 2 3", "5 0\n3 14 15 92 6"], "sample_outputs": ["1 3 6", "3 14 15 92 6"], "notes": null}, "positive_code": [{"source_code": "// CodeForces 223C ToDo\nobject PartSums extends App {\n val MOD: Long = 1000000007L\n var kkf:Vector[Long] = Vector()\n \n def mull(a:Long, b:Long):Long = (a * b) % MOD\n def addl(a:Long, b:Long):Long = (a + b) % MOD\n def divl(a:Long, n:Int):Long = {\n val lst = for {\n i <- Range(0, n)\n if (a+i*MOD) % n == 0\n } yield ((a+i*MOD) / n)\n lst(0)\n }\n \n def koefs(n:Int, k:Int): Vector[Long] = {\n var vc = Vector[Long]()\n var cf:Long = 1\n for (i <- 0 until n) {\n vc = vc :+ cf\n cf = mull(cf, (k+i))\n cf = divl(cf, i+1)\n }\n vc\n }\n \n def sum(n:Int, aa:Vector[Long]):Long = {\n var sm:Long = 0\n val kfs = kkf; // koefs(n+1, k)\n for (i <- 0 to n) {\n sm = addl(sm, mull(aa(i), kfs(n-i))) \n }\n sm\n }\n\n def work() = {\n\t var ss = (Console.readLine.split(\" \")) map (_.toInt)\n\t val n = ss(0)\n\t val k = ss(1)\n\t val aa = (Console.readLine.split(\" \") map (_.toLong)) toList;\n\t var vaa:Vector[Long] = Vector()\t \n\t vaa = vaa ++ aa\n\t kkf = koefs(n+5, k)\n\t val smaa = for (i <- 0 until n) \n\t yield sum(i, vaa)\n\t \n\t println( smaa mkString \" \" ) \n }\n def printSums(kk:Int) = {\n kkf = koefs(20, kk) \n\t print(\"kk = \" + kk + \" sums: \")\n\t for (i <- Range(0,5)) \n\t print(\" \" + sum(i, Vector(1,2,4,8, 10)))\n\t println()\n }\n def testPrint() = {\n\t println(\"MOD = \" + MOD)\n\t println(\"mul29 = \" + mull(2,9))\n\t println(\"add29 = \" + addl(1000000000L,14))\n\t println(\"divl = \" + divl(1000000000L, 1000))\n\t println(koefs(4,4)) // expect 1, 4\n\t println(koefs(10,3)) // expect 1, 4\n\t println(koefs(0,4)) // expect 1, 4\n\t kkf = koefs(20,4)\n\t printSums(0)\n\t printSums(1)\n\t printSums(100000) \n }\n // testPrint()\n work()\n}"}], "negative_code": [], "src_uid": "584f7008e27dde53037396d2459efd84"} {"nl": {"description": "During the \"Russian Code Cup\" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x\u00a0\u2014 the number of different solutions that are sent before the first solution identical to A, and k \u2014 the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x\u2009>\u20090) of the participant with number k, then the testing system has a solution with number x\u2009-\u20091 of the same participant stored somewhere before.During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of solutions. Each of the following n lines contains two integers separated by space x and k (0\u2009\u2264\u2009x\u2009\u2264\u2009105; 1\u2009\u2264\u2009k\u2009\u2264\u2009105)\u00a0\u2014 the number of previous unique solutions and the identifier of the participant.", "output_spec": "A single line of the output should contain \u00abYES\u00bb if the data is in chronological order, and \u00abNO\u00bb otherwise.", "sample_inputs": ["2\n0 1\n1 1", "4\n0 1\n1 2\n1 1\n0 2", "4\n0 1\n1 1\n0 1\n0 2"], "sample_outputs": ["YES", "NO", "YES"], "notes": null}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val n = readLine().toInt\n val versions = new Array[Int](100001)\n for (i <- 1 to 100000) {\n versions(i) = -1\n }\n for (i <- 1 to n) {\n val Array(x, k) = readLine().split(\" \").map(_.toInt)\n if (!(x <= versions(k) || x == versions(k) + 1)) {\n println(\"NO\")\n return\n }\n if (x == versions(k) + 1) {\n versions(k) += 1\n }\n }\n println(\"YES\")\n }\n}\n"}], "negative_code": [], "src_uid": "6f6f56d3106e09d51ebb3a206fa4be3c"} {"nl": {"description": "For an array $$$a$$$ of integers let's denote its maximal element as $$$\\max(a)$$$, and minimal as $$$\\min(a)$$$. We will call an array $$$a$$$ of $$$k$$$ integers interesting if $$$\\max(a) - \\min(a) \\ge k$$$. For example, array $$$[1, 3, 4, 3]$$$ isn't interesting as $$$\\max(a) - \\min(a) = 4 - 1 = 3 < 4$$$ while array $$$[7, 3, 0, 4, 3]$$$ is as $$$\\max(a) - \\min(a) = 7 - 0 = 7 \\ge 5$$$.You are given an array $$$a$$$ of $$$n$$$ integers. Find some interesting nonempty subarray of $$$a$$$, or tell that it doesn't exist.An array $$$b$$$ is a subarray of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.", "input_spec": "The first line contains integer number $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2\\le n \\le 2\\cdot 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0\\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output \"NO\" in a separate line if there is no interesting nonempty subarray in $$$a$$$. Otherwise, output \"YES\" in a separate line. In the next line, output two integers $$$l$$$ and $$$r$$$ ($$$1\\le l \\le r \\le n$$$)\u00a0\u2014 bounds of the chosen subarray. If there are multiple answers, print any. You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n5\n1 2 3 4 5\n4\n2 0 1 9\n2\n2019 2020"], "sample_outputs": ["NO\nYES\n1 4\nNO"], "notes": "NoteIn the second test case of the example, one of the interesting subarrays is $$$a = [2, 0, 1, 9]$$$: $$$\\max(a) - \\min(a) = 9 - 0 = 9 \\ge 4$$$."}, "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 = 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"}, {"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 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}"}], "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"} {"nl": {"description": "Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2\u2009\u00d7\u20092 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2\u2009\u00d7\u20092 square consisting of black pixels is formed.", "input_spec": "The first line of the input contains three integers n,\u2009m,\u2009k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u2009105)\u00a0\u2014 the number of rows, the number of columns and the number of moves that Pasha is going to perform. The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1\u2009\u2264\u2009i\u2009\u2264\u2009n, 1\u2009\u2264\u2009j\u2009\u2264\u2009m), representing the row number and column number of the pixel that was painted during a move.", "output_spec": "If Pasha loses, print the number of the move when the 2\u2009\u00d7\u20092 square consisting of black pixels is formed. If Pasha doesn't lose, that is, no 2\u2009\u00d7\u20092 square consisting of black pixels is formed during the given k moves, print 0.", "sample_inputs": ["2 2 4\n1 1\n1 2\n2 1\n2 2", "2 3 6\n2 3\n2 2\n1 3\n2 2\n1 2\n1 1", "5 3 7\n2 3\n1 2\n1 1\n4 1\n3 1\n5 3\n3 2"], "sample_outputs": ["4", "5", "0"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "Let us define a magic grid to be a square matrix of integers of size $$$n \\times n$$$, satisfying the following conditions. All integers from $$$0$$$ to $$$(n^2 - 1)$$$ inclusive appear in the matrix exactly once. Bitwise XOR of all elements in a row or a column must be the same for each row and column. You are given an integer $$$n$$$ which is a multiple of $$$4$$$. Construct a magic grid of size $$$n \\times n$$$.", "input_spec": "The only line of input contains an integer $$$n$$$ ($$$4 \\leq n \\leq 1000$$$). It is guaranteed that $$$n$$$ is a multiple of $$$4$$$.", "output_spec": "Print a magic grid, i.e. $$$n$$$ lines, the $$$i$$$-th of which contains $$$n$$$ space-separated integers, representing the $$$i$$$-th row of the grid. If there are multiple answers, print any. We can show that an answer always exists.", "sample_inputs": ["4", "8"], "sample_outputs": ["8 9 1 13\n3 12 7 5\n0 2 4 11\n6 10 15 14", "19 55 11 39 32 36 4 52\n51 7 35 31 12 48 28 20\n43 23 59 15 0 8 16 44\n3 47 27 63 24 40 60 56\n34 38 6 54 17 53 9 37\n14 50 30 22 49 5 33 29\n2 10 18 46 41 21 57 13\n26 42 62 58 1 45 25 61"], "notes": "NoteIn the first example, XOR of each row and each column is $$$13$$$.In the second example, XOR of each row and each column is $$$60$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "You are given $$$n$$$ sticks with positive integral length $$$a_1, a_2, \\ldots, a_n$$$.You can perform the following operation any number of times (possibly zero): choose one stick, then either increase or decrease its length by $$$1$$$. After each operation, all sticks should have positive lengths. What is the minimum number of operations that you have to perform such that it is possible to select three of the $$$n$$$ sticks and use them without breaking to form an equilateral triangle?An equilateral triangle is a triangle where all of its three sides have the same length.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 300$$$)\u00a0\u2014 the number of sticks. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the lengths of the sticks. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$300$$$. ", "output_spec": "For each test case, print one integer on a single line\u00a0\u2014 the minimum number of operations to be made.", "sample_inputs": ["4\n\n3\n\n1 2 3\n\n4\n\n7 3 7 3\n\n5\n\n3 4 2 1 1\n\n8\n\n3 1 4 1 5 9 2 6"], "sample_outputs": ["2\n4\n1\n1"], "notes": "NoteIn the first test case, you can increase the length of the first stick by $$$1$$$, then decrease the length of the third stick by $$$1$$$. In total, you perform $$$2$$$ operations, such that the three sticks form an equilateral triangle of side length $$$2$$$.In the fourth test case, you can decrease the length of the seventh stick by $$$1$$$. An equilateral triangle of side length $$$1$$$ can be selected and formed by the second, fourth, and seventh sticks."}, "positive_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(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"}, {"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"}, {"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 | \u96be\u5ea6\uff1a800\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}"}], "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 | \u96be\u5ea6\uff1a800\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"} {"nl": {"description": "Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves\u00a0\u2014 from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j\u00a0\u2014 Place a book at position j at shelf i if there is no book at it. 2 i j\u00a0\u2014 Remove the book from position j at shelf i if there is a book at it. 3 i\u00a0\u2014 Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k\u00a0\u2014 Return the books in the bookcase in a state they were after applying k-th operation. In particular, k\u2009=\u20090 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?", "input_spec": "The first line of the input contains three integers n, m and q (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103, 1\u2009\u2264\u2009q\u2009\u2264\u2009105)\u00a0\u2014 the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order\u00a0\u2014 i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0.", "output_spec": "For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order.", "sample_inputs": ["2 3 3\n1 1 1\n3 2\n4 0", "4 2 6\n3 2\n2 2 2\n3 3\n3 2\n2 2 2\n3 2", "2 2 2\n3 2\n2 2 1"], "sample_outputs": ["1\n4\n0", "2\n1\n3\n3\n2\n4", "2\n1"], "notes": "NoteThis image illustrates the second sample case."}, "positive_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 = 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": "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"}, {"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": "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"} {"nl": {"description": "There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert \u2013 Tablecity\u2019s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.Tablecity can be represented as 1000\u2009\u00d7\u20092 grid, where every cell represents one district. Each district has its own unique name \u201c(X,\u2009Y)\u201d, where X and Y are the coordinates of the district in the grid. The thief\u2019s movement is as Every hour the thief will leave the district (X,\u2009Y) he is currently hiding in, and move to one of the districts: (X\u2009-\u20091,\u2009Y), (X\u2009+\u20091,\u2009Y), (X\u2009-\u20091,\u2009Y\u2009-\u20091), (X\u2009-\u20091,\u2009Y\u2009+\u20091), (X\u2009+\u20091,\u2009Y\u2009-\u20091), (X\u2009+\u20091,\u2009Y\u2009+\u20091) as long as it exists in Tablecity. Below is an example of thief\u2019s possible movements if he is located in district (7,1):Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.", "input_spec": "There is no input for this problem. ", "output_spec": "The first line of output contains integer N \u2013 duration of police search in hours. Each of the following N lines contains exactly 4 integers Xi1, Yi1, Xi2, Yi2 separated by spaces, that represent 2 districts (Xi1, Yi1), (Xi2, Yi2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief\u2019s initial position and movement. N\u2009\u2264\u20092015 1\u2009\u2264\u2009X\u2009\u2264\u20091000 1\u2009\u2264\u2009Y\u2009\u2264\u20092 ", "sample_inputs": ["\u0412 \u044d\u0442\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u043d\u0435\u0442 \u043f\u0440\u0438\u043c\u0435\u0440\u043e\u0432 \u0432\u0432\u043e\u0434\u0430-\u0432\u044b\u0432\u043e\u0434\u0430.\nThis problem doesn't have sample input and output."], "sample_outputs": ["\u0421\u043c\u043e\u0442\u0440\u0438\u0442\u0435 \u0437\u0430\u043c\u0435\u0447\u0430\u043d\u0438\u0435 \u043d\u0438\u0436\u0435.\nSee the note below."], "notes": "NoteLet's consider the following output:25 1 50 28 1 80 2This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.Consider the following initial position and thief\u2019s movement:In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.Since there is no further investigation by the police, the thief escaped!"}, "positive_code": [{"source_code": "object Main {\n\n def main(args: Array[String]) {\n println(2000)\n for (i <- 1 to 1000) {\n println(i + \" \" + 1 + \" \" + i + \" \" + 2)\n }\n for (i <- (1 to 1000).reverse) {\n println(i + \" \" + 1 + \" \" + i + \" \" + 2)\n }\n }\n}"}], "negative_code": [{"source_code": "object Main {\n\n def main(args: Array[String]) {\n println(1000)\n for (i <- 1 to 1000) {\n println(i + \" \" + 1 + \" \" + i + \" \" + 2)\n }\n }\n}\n"}, {"source_code": "object Main {\n\n def main(args: Array[String]) {\n println(1999)\n for (i <- 1 to 1000) {\n println(i + \" \" + 1 + \" \" + i + \" \" + 2)\n }\n for (i <- (1 to 999).reverse) {\n println(i + \" \" + 1 + \" \" + i + \" \" + 2)\n }\n }\n}"}], "src_uid": "19190fd248eb2c621ac2c78b803049a8"} {"nl": {"description": "Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review \u00a0\u2014 in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named \u00abPoisson\u00bb, that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \\times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to \">\", in the opposite case $$$a_{ij}$$$ is equal to \"<\". Dishes also may be equally good, in this case $$$a_{ij}$$$ is \"=\".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is \"<\", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is \">\", then it should be greater, and finally if $$$a_{ij}$$$ is \"=\", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.", "input_spec": "The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 1000$$$)\u00a0\u2014 the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of \"<\", \">\" and \"=\".", "output_spec": "The first line of output should contain \"Yes\", if it's possible to do a correct evaluation for all the dishes, or \"No\" otherwise. If case an answer exist, on the second line print $$$n$$$ integers\u00a0\u2014 evaluations of dishes from the first set, and on the third line print $$$m$$$ integers\u00a0\u2014 evaluations of dishes from the second set.", "sample_inputs": ["3 4\n>>>>\n>>>>\n>>>>", "3 3\n>>>\n<<<\n>>>", "3 2\n==\n=<\n=="], "sample_outputs": ["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"], "notes": "NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory\u00a0\u2014 there is no possible evaluation of the dishes that satisfies it."}, "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\n val mat = nm_c(N, M)\n\n val uf = new UnionFind(N + M)\n\n REP(N) { i =>\n REP(M) { j =>\n if (mat(i)(j) == '=') uf.unite(i, N + j)\n }\n }\n\n // \u77e2\u5370\u306e\u65b9\u5411\u306f\u5927\u304d\u3044\u307b\u3046\u304b\u3089\u5c0f\u3055\u3044\u65b9\u3078\n val g = Array.fill[ArrayBuffer[Int]](N + M)(ArrayBuffer())\n REP(N) { i =>\n REP(M) { j =>\n val v = uf.find(i)\n val u = uf.find(j + N)\n mat(i)(j) match {\n case '<' => g(u) += v\n case '>' => g(v) += u\n case _ =>\n }\n }\n }\n\n val ans = Array.ofDim[Int](N + M)\n val visit = Array.ofDim[Int](N + M)\n\n def dfs(v: Int): Boolean = {\n// debug(s\"dfs($v)\")\n visit(v) = 1 \n if (g(v).isEmpty) ans(v) = 1\n else {\n var mx = 0\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (visit(u) == 0) {\n if (!dfs(u)) return false\n } else if (visit(u) == 1) return false\n mx = max(ans(u), mx)\n }\n ans(v) = mx + 1 // \u6700\u5927\u306e\u5b50\u4f9b + 1\n// debug(s\"ans($v) = ${ans(v)}\")\n }\n\n visit(v) = 2\n true\n }\n\n var ok = true\n REP(N + M) { i =>\n val v = uf.find(i)\n if (ok && visit(v) == 0) ok &&= dfs(v)\n }\n\n if (!ok) out.println(\"No\")\n else {\n out.println(\"Yes\")\n val first = map(N) { i =>\n val v = uf.find(i)\n ans(v)\n }.mkString(\" \")\n\n val second = map(M) { i =>\n val v = uf.find(N + i)\n ans(v)\n }.mkString(\" \")\n\n out.println(first)\n out.println(second)\n }\n }\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\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, M = ni()\n\n val mat = nm_c(N, M)\n\n val uf = new UnionFind(N + M)\n\n REP(N) { i =>\n REP(M) { j =>\n if (mat(i)(j) == '=') uf.unite(i, N + j)\n }\n }\n\n // \u77e2\u5370\u306e\u65b9\u5411\u306f\u5927\u304d\u3044\u307b\u3046\u304b\u3089\u5c0f\u3055\u3044\u65b9\u3078\n val g = Array.fill[ArrayBuffer[Int]](N + M)(ArrayBuffer())\n REP(N) { i =>\n REP(M) { j =>\n val v = uf.find(i)\n val u = uf.find(j + N)\n mat(i)(j) match {\n case '<' => g(u) += v\n case '>' => g(v) += u\n case _ =>\n }\n }\n }\n\n val ans = Array.ofDim[Int](N + M)\n val visit = Array.ofDim[Int](N + M)\n\n def dfs(v: Int): Boolean = {\n visit(v) = 1\n if (g(v).isEmpty) ans(v) = 1\n else {\n var mx = 0\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (visit(u) == 0) dfs(u)\n else if (visit(u) == 1) return false\n mx = max(ans(u), mx)\n }\n ans(v) = mx + 1 // \u6700\u5927\u306e\u5b50\u4f9b + 1\n }\n\n visit(v) = 2\n true\n }\n\n var ok = true\n REP(N + M) { i =>\n val v = uf.find(i)\n if (ok && visit(v) == 0) ok &&= dfs(v)\n }\n\n if (!ok) out.println(\"No\")\n else {\n out.println(\"Yes\")\n val first = map(N) { i =>\n val v = uf.find(i)\n ans(v)\n }.mkString(\" \")\n\n val second = map(M) { i =>\n val v = uf.find(N + i)\n ans(v)\n }.mkString(\" \")\n\n out.println(first)\n out.println(second)\n }\n }\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\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}"}], "src_uid": "016bf7989ba58fdc3894a4cf3e0ac302"} {"nl": {"description": "Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it. ", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000)\u00a0\u2014 the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters\u00a0\u2014 the encoding.", "output_spec": "Print the word that Polycarp encoded.", "sample_inputs": ["5\nlogva", "2\nno", "4\nabba"], "sample_outputs": ["volga", "no", "baba"], "notes": "NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject B 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 s = readLine()\n\n var s2 = Array.fill(n)(' ')\n\n (0 until n).foreach { i =>\n val l = n - i\n var m = (l - 1) / 2\n var j = 0\n while (m >= 0) {\n if (s2(j) == ' ') m -= 1\n if (m < 0) s2(j) = s(i)\n j += 1\n }\n }\n\n println(s2.mkString)\n}\n"}], "negative_code": [], "src_uid": "2a414730d1bc7eef50bdb631ea966366"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 10^7$$$).", "output_spec": "For each test case, print the answer \u2014 \"YES\" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and \"NO\" otherwise.", "sample_inputs": ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES\nNO"], "notes": "NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day \u2014 exactly $$$2$$$ problems, during the third day \u2014 exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$) \u2014 the number of problems in the $$$i$$$-th contest.", "output_spec": "Print one integer \u2014 the maximum number of days Polycarp can train if he chooses the contests optimally.", "sample_inputs": ["4\n3 1 4 1", "3\n1 1 1", "5\n1 1 1 2 2"], "sample_outputs": ["3", "1", "2"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "In the year of $$$30XX$$$ participants of some world programming championship live in a single large hotel. The hotel has $$$n$$$ floors. Each floor has $$$m$$$ sections with a single corridor connecting all of them. The sections are enumerated from $$$1$$$ to $$$m$$$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $$$n$$$ and width $$$m$$$. We can denote sections with pairs of integers $$$(i, j)$$$, where $$$i$$$ is the floor, and $$$j$$$ is the section number on the floor.The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $$$(1, x)$$$, $$$(2, x)$$$, $$$\\ldots$$$, $$$(n, x)$$$ for some $$$x$$$ between $$$1$$$ and $$$m$$$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $$$v$$$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.You are to process $$$q$$$ queries. Each query is a question \"what is the minimum time needed to go from a room in section $$$(x_1, y_1)$$$ to a room in section $$$(x_2, y_2)$$$?\"", "input_spec": "The first line contains five integers $$$n, m, c_l, c_e, v$$$ ($$$2 \\leq n, m \\leq 10^8$$$, $$$0 \\leq c_l, c_e \\leq 10^5$$$, $$$1 \\leq c_l + c_e \\leq m - 1$$$, $$$1 \\leq v \\leq n - 1$$$)\u00a0\u2014 the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains $$$c_l$$$ integers $$$l_1, \\ldots, l_{c_l}$$$ in increasing order ($$$1 \\leq l_i \\leq m$$$), denoting the positions of the stairs. If $$$c_l = 0$$$, the second line is empty. The third line contains $$$c_e$$$ integers $$$e_1, \\ldots, e_{c_e}$$$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $$$l_i$$$ and $$$e_i$$$ are distinct. The fourth line contains a single integer $$$q$$$ ($$$1 \\leq q \\leq 10^5$$$)\u00a0\u2014 the number of queries. The next $$$q$$$ lines describe queries. Each of these lines contains four integers $$$x_1, y_1, x_2, y_2$$$ ($$$1 \\leq x_1, x_2 \\leq n$$$, $$$1 \\leq y_1, y_2 \\leq m$$$)\u00a0\u2014 the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i.\u00a0e. $$$y_1$$$ and $$$y_2$$$ are not among $$$l_i$$$ and $$$e_i$$$.", "output_spec": "Print $$$q$$$ integers, one per line\u00a0\u2014 the answers for the queries.", "sample_inputs": ["5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3"], "sample_outputs": ["7\n5\n4"], "notes": "NoteIn the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either: Remove a single cow from a chosen non-empty pile. Choose a pile of cows with even size 2\u00b7x (x\u2009>\u20090), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1,\u2009a2,\u2009...,\u2009an, help Kevin and Nicky find the winner, given that both sides play in optimal way.", "input_spec": "The first line of the input contains two space-separated integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109). The second line contains n integers, a1,\u2009a2,\u2009... an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) describing the initial state of the game. ", "output_spec": "Output the name of the winning player, either \"Kevin\" or \"Nicky\" (without quotes).", "sample_inputs": ["2 1\n3 4", "1 2\n3"], "sample_outputs": ["Kevin", "Nicky"], "notes": "NoteIn the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other."}, "positive_code": [{"source_code": "object E{\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,k)=(nextInt,nextInt)\n def f(a:Int):Int={\n if(k%2==0){\n a match {\n case 0 => 0\n case 1 => 1\n case 2 => 2\n case _ => if(a%2==1) 0 else 1\n }\n }else{\n a match {\n case 0 => 0\n case 1 => 1\n case 2 => 0\n case 3 => 1\n case 4 => 2\n case _ => if(a%2==1) 0 else if(f(a/2)==1){\n 2\n }else 1\n }\n }\n }\n var ans=0\n for(i<-0 until n) ans^=f(nextInt)\n out.println(if (ans==0) \"Nicky\" else \"Kevin\")\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "object E{\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,k)=(nextInt,nextInt)\n def f(a:Int):Int={\n if(k%2==0){\n a match {\n case 0 => 0\n case 1 => 1\n case 2 => 2\n case _ => if(a%2==1) 0 else 1\n }\n }else{\n a match {\n case 0 => 0\n case 1 => 1\n case 2 => 0\n case _ => if(a%2==1) 0 else if(f(a/2)==1){\n 2\n }else 1\n }\n }\n }\n var ans=0\n for(i<-0 until n) ans^=f(nextInt)\n out.println(if (ans==0) \"Nicky\" else \"Kevin\")\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "5ae6585bf96e0bff343bb76c1af3ebc2"} {"nl": {"description": "Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \\dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \\le i \\le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \\le k \\le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \\leq i < j \\leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \\neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \\leq i < j \\leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following: For every non-special array $$$c_i$$$ ($$$i \\neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \\dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \\leq n \\leq 10^5$$$, $$$7 \\leq m \\leq 3 \\cdot 10^5$$$) \u2014 the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \\dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \\leq c_{i,j} \\leq 3 \\cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \\cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.", "output_spec": "For each test case, output one line containing two integers \u2014 the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.", "sample_inputs": ["7\n3 9\n0 1 2 0 0 2 1 1 0\n0 1 1 1 2 0 0 2 0\n0 1 2 0 0 1 2 1 0\n3 7\n25 15 20 15 25 20 20\n26 14 20 14 26 20 20\n25 15 20 15 20 20 25\n3 9\n25 15 20 15 25 20 20 20 20\n26 14 20 14 26 20 20 20 20\n25 15 20 15 25 15 20 20 25\n3 11\n25 15 20 15 25 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20\n25 15 20 15 25 20 15 20 20 20 25\n3 13\n25 15 20 15 25 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 15 20 20 20 20 25\n3 15\n25 15 20 15 25 20 20 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 20 15 20 20 20 20 20 25\n3 9\n909459 479492 676924 224197 162866 164495 193268 742456 728277\n948845 455424 731850 327890 304150 237351 251763 225845 798316\n975446 401170 792914 272263 300770 242037 236619 334316 725899"], "sample_outputs": ["3 1\n3 10\n3 15\n3 20\n3 25\n3 30\n1 1378716"], "notes": "NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2."}, "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 B = new Array[Long](m)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (j <- 1 to m){\r\n B(j-1) = tokenizer.nextToken().toInt\r\n }\r\n var nom = 0\r\n var s: Long =0\r\n for (i <- 1 until n){\r\n var cou: Long = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (j <- 1 to m){\r\n cou+=j*(B(j-1) - tokenizer.nextToken().toInt)\r\n }\r\n if (cou != 0){\r\n nom = i\r\n s = cou\r\n }\r\n }\r\n if (s < 0){\r\n println((nom+1).toString + \" \" + (-s).toString)\r\n }\r\n else {\r\n println(1+ \" \" + (s).toString)\r\n }\r\n }\r\n }\r\n}"}], "negative_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 = Array[Long](-1,-1)\r\n var l1= 0\r\n var l2= 0\r\n for (i <- 1 to n){\r\n var cou: Long = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (j <- 1 to m){\r\n cou+=j*tokenizer.nextToken().toInt\r\n }\r\n if (!A.contains(cou)){\r\n if (A(0) == -1){\r\n A(0) = cou\r\n l1 = i\r\n }\r\n else {\r\n A(1) = cou\r\n l2 = i\r\n }\r\n }\r\n }\r\n if (A(0) > A(1)){\r\n println(l1.toString+\" \"+ (A.max - A.min).toString )\r\n }\r\n else {\r\n println(l2.toString+\" \"+ (A.max - A.min).toString )\r\n }\r\n }\r\n }\r\n}"}], "src_uid": "abcafb310d4dcf3f7e34fc4eda1ee324"} {"nl": {"description": "There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n\u2009+\u20091) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw? The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses. ", "input_spec": "The first line contains integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009104) \u2014 the number of test cases. The second line contains t space-separated integers ni (1\u2009\u2264\u2009ni\u2009\u2264\u2009109) \u2014 the sides of the square for each test sample.", "output_spec": "For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier. ", "sample_inputs": ["3\n4 8 100"], "sample_outputs": ["17\n33\n401"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.There is a set $$$S$$$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a positive integer $$$k$$$ and replace each element $$$s$$$ of the set $$$S$$$ with $$$s \\oplus k$$$ ($$$\\oplus$$$ denotes the exclusive or operation). Help him choose such $$$k$$$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $$$\\{1, 2, 3\\}$$$ equals to set $$$\\{2, 1, 3\\}$$$.Formally, find the smallest positive integer $$$k$$$ such that $$$\\{s \\oplus k | s \\in S\\} = S$$$ or report that there is no such number.For example, if $$$S = \\{1, 3, 4\\}$$$ and $$$k = 2$$$, new set will be equal to $$$\\{3, 1, 6\\}$$$. If $$$S = \\{0, 1, 2, 3\\}$$$ and $$$k = 1$$$, after playing set will stay the same.", "input_spec": "In the first line of input, there is a single integer $$$t$$$ ($$$1 \\leq t \\leq 1024$$$), the number of test cases. In the next lines, $$$t$$$ test cases follow. Each of them consists of two lines. In the first line there is a single integer $$$n$$$ ($$$1 \\leq n \\leq 1024$$$) denoting the number of elements in set $$$S$$$. Second line consists of $$$n$$$ distinct integers $$$s_i$$$ ($$$0 \\leq s_i < 1024$$$), elements of $$$S$$$. It is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$1024$$$.", "output_spec": "Print $$$t$$$ lines; $$$i$$$-th line should contain the answer to the $$$i$$$-th test case, the minimal positive integer $$$k$$$ satisfying the conditions or $$$-1$$$ if no such $$$k$$$ exists.", "sample_inputs": ["6\n4\n1 0 2 3\n6\n10 7 14 8 3 12\n2\n0 2\n3\n1 2 3\n6\n1 4 6 10 11 12\n2\n0 1023"], "sample_outputs": ["1\n4\n2\n-1\n-1\n1023"], "notes": "NoteIn the first test case, the answer is $$$1$$$ because it is a minimum positive integer and it satisfies all the conditions."}, "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 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"}, {"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"} {"nl": {"description": "In Berland there are n cities and n\u2009-\u20091 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.", "input_spec": "The first line of the input contains a positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of cities in Berland. Each of the next n\u2009-\u20091 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi).", "output_spec": "First print number k\u00a0\u2014 the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di \u2014 the number of roads that should be repaired on the i-th day, and then di space-separated integers \u2014 the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them.", "sample_inputs": ["4\n1 2\n3 4\n3 2", "6\n3 4\n5 4\n3 2\n1 3\n4 6"], "sample_outputs": ["2\n2 2 1\n1 3", "3\n1 1 \n2 2 3 \n2 4 5"], "notes": "NoteIn the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 \u2014 on the second day."}, "positive_code": [{"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 except = Array.ofDim[Int](n)\n val edges = Array.fill[List[Int]](n){ Nil }\n var map = mutable.HashMap.empty[(Int, Int), Int]\n\n (1 until n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n map += (Math.max(a, b), Math.min(a, b)) -> i\n edges(a) ::= b\n edges(b) ::= a\n }\n val max = edges.maxBy(_.length).length\n var answer = Array.fill[List[Int]](max) { Nil }\n\n var processing = List(0)\n except(0) = -1\n\n while (processing.nonEmpty) {\n var nextProcessing = List.empty[Int]\n processing.foreach { i =>\n var n = 1\n edges(i).foreach { j =>\n if (except(j) == 0) {\n if (n == except(i)) n += 1\n except(j) = n\n answer(n - 1) ::= map((Math.max(i, j), Math.min(j, i)))\n n += 1\n nextProcessing ::= j\n }\n }\n }\n processing = nextProcessing\n }\n\n println(max)\n println(answer.map(j => j.mkString(j.length + \" \", \" \", \"\")).mkString(\"\\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\n case class Edge(to: Int, number: Int)\n\n val nodes = Array.fill[List[Edge]](n) { Nil }\n val power = Array.ofDim[Int](n)\n\n var joined = 0\n\n val data = (1 until n).foreach{ i =>\n val Array(from, to) = in.next().split(' ').map(_.toInt - 1)\n nodes(from) ::= Edge(to, i)\n nodes(to) ::= Edge(from, i)\n power(from) += 1\n power(to) += 1\n }\n var solution = List.empty[List[Int]]\n\n while (joined != n - 1) {\n val processed = Array.ofDim[Boolean](n)\n var list = List.empty[Int]\n power.zipWithIndex.sorted.foreach {\n case((value, index)) if value == 0 || processed(index) =>\n case((_, index)) =>\n val connected = nodes(index).filterNot(edge => processed(edge.to))\n if (connected.nonEmpty) {\n val connect = connected.maxBy(i => power(i.to))\n processed(index) = true\n processed(connect.to) = true\n power(index) -= 1\n power(connect.to) -= 1\n nodes(index) = nodes(index).filter(_.to != connect.to)\n nodes(connect.to) = nodes(connect.to).filter(_.to != index)\n list ::= connect.number\n joined += 1\n }\n }\n solution ::= list\n }\n\n println(solution.length)\n println(solution.reverse.map(i => i.mkString(s\"${i.length} \", \" \", \"\")).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 val roadCounts = Array.fill[Set[Int]](n) { Set.empty }\n var fixed = 0\n var map = Map.empty[(Int, Int), Int]\n (1 until n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n roadCounts(a) += b\n roadCounts(b) += a\n map += (a, b) -> i\n map += (b, a) -> i\n }\n\n val sorted = roadCounts.indices.sortBy(i => -roadCounts(i).size).toArray\n val max = roadCounts(sorted(0)).size\n var answer = List.empty[List[Int]]\n var a = List.empty[String]\n\n while (fixed != n - 1) {\n val busy = Array.ofDim[Boolean](n)\n var list = List.empty[Int]\n sorted.foreach { i =>\n if (!busy(i)) {\n val roads = roadCounts(i).filterNot(busy)\n if (roads.nonEmpty) {\n val nJ = roads.maxBy(j => roadCounts(j).size)\n roadCounts(nJ) -= i\n roadCounts(i) -= nJ\n list ::= map(i, nJ) + 1\n busy(i) = true\n busy(nJ) = true\n fixed += 1\n }\n }\n }\n a ::= list.reverse.mkString(list.length + \" \", \" \", \"\")\n }\n\n\n\n\n println(max)\n println(a.reverse.mkString(\"\\n\"))\n}\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 except = Array.ofDim[Int](n)\n val edges = Array.fill[List[Int]](n){ Nil }\n var map = mutable.HashMap.empty[(Int, Int), Int]\n var answer = Array.ofDim[Int](n - 1)\n (1 until n).foreach { i =>\n val Array(a, b) = in.next().split(' ').map(_.toInt - 1)\n map += (a, b) -> i\n map += (b, a) -> i\n edges(a) ::= b\n edges(b) ::= a\n }\n\n var processing = List(0)\n except(0) = -1\n\n while (processing.nonEmpty) {\n var nextProcessing = List.empty[Int]\n processing.foreach { i =>\n var n = 1\n edges(i).foreach { j =>\n if (except(j) == 0) {\n if (n == except(i)) n += 1\n except(j) = n\n answer(map((i, j)) - 1) = n\n n += 1\n nextProcessing ::= j\n }\n }\n }\n processing = nextProcessing\n }\n\n val groupped = answer.zipWithIndex.groupBy(_._1).toList.sortBy(_._1).map(i => (i._1, i._2.map(_._1)))\n println(groupped.length)\n println(groupped.map(j => j._2.mkString(j._2.length + \" \", \" \", \"\")).mkString(\"\\n\"))\n}\n"}], "src_uid": "5acd7b95a44dcb8f72623b51fcf85f1b"} {"nl": {"description": "You've got array a[1],\u2009a[2],\u2009...,\u2009a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i,\u2009j (2\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n\u2009-\u20091), that .", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]|\u2009\u2264\u2009\u2009109) \u2014 the elements of array a.", "output_spec": "Print a single integer \u2014 the number of ways to split the array into three parts with the same sum.", "sample_inputs": ["5\n1 2 3 0 3", "4\n0 1 -1 0", "2\n4 1"], "sample_outputs": ["2", "1", "0"], "notes": null}, "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)\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"}, {"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": "\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"}, {"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 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}"}], "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"} {"nl": {"description": "You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k)\u2009=\u2009{cu\u00a0:\u2009\u00a0cu\u2009\u2260\u2009k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.", "input_spec": "The first line contains two space-separated integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009105) \u2014 the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi) \u2014 the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges.", "output_spec": "Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.", "sample_inputs": ["6 6\n1 1 2 3 5 8\n1 2\n3 2\n1 4\n4 3\n4 5\n4 6", "5 6\n4 2 5 2 4\n1 2\n2 3\n3 1\n5 3\n5 4\n3 4"], "sample_outputs": ["3", "2"], "notes": null}, "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, 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"}, {"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"} {"nl": {"description": "You are given an array consisting of all integers from $$$[l, r]$$$ inclusive. For example, if $$$l = 2$$$ and $$$r = 5$$$, the array would be $$$[2, 3, 4, 5]$$$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\leq l \\leq r \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the description of the array.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["5\n1 2\n2 8\n4 5\n1 5\n100000 200000"], "sample_outputs": ["1\n3\n0\n2\n31072"], "notes": "NoteIn the first test case, the array is $$$[1, 2]$$$. Currently, the bitwise AND is $$$0$$$, as $$$1\\ \\& \\ 2 = 0$$$. However, after deleting $$$1$$$ (or $$$2$$$), the array becomes $$$[2]$$$ (or $$$[1]$$$), and the bitwise AND becomes $$$2$$$ (or $$$1$$$). This can be proven to be the optimal, so the answer is $$$1$$$.In the second test case, the array is $$$[2, 3, 4, 5, 6, 7, 8]$$$. Currently, the bitwise AND is $$$0$$$. However, after deleting $$$4$$$, $$$5$$$, and $$$8$$$, the array becomes $$$[2, 3, 6, 7]$$$, and the bitwise AND becomes $$$2$$$. This can be proven to be the optimal, so the answer is $$$3$$$. Note that there may be other ways to delete $$$3$$$ elements."}, "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615B(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.math.{max, min, pow}\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\n\r\n\r\n\r\nclass CF1615B (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n\r\n import Main._\r\n import fScanner._\r\n\r\n val M: Int = 200012\r\n val L: Int = 20\r\n\r\n def pre(mx: Int, L: Int): mutable.Seq[ArrayBuffer[Int]] = {\r\n val prf = ArrayBuffer.fill(M, 20)(0)\r\n (1 until mx).foreach{ i =>\r\n (0 until L).foreach { j =>\r\n prf(i)(j) =\r\n prf(i-1)(j) + {\r\n if (((1 << j) & i) > 0) 1\r\n else 0\r\n }\r\n }\r\n }\r\n prf\r\n }\r\n\r\n def solve(): Unit = {\r\n val prf = pre(M, L)\r\n val T = ni()\r\n\r\n (1 to T).foreach { tc =>\r\n val L = ni()\r\n val R = ni()\r\n val ans =\r\n (0 until 20).map{ j =>\r\n R - L + 1 - {\r\n val x = prf(R)(j) - prf(L-1)(j)\r\n x\r\n }\r\n }.min\r\n out.println(ans)\r\n }\r\n }\r\n\r\n}"}], "negative_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615B(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = false\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport java.io._\r\nimport java.util.StringTokenizer\r\nimport scala.math.{max, min, pow}\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\n\r\n\r\n\r\nclass CF1615B (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n\r\n import Main._\r\n import fScanner._\r\n\r\n val M: Int = 200012\r\n val L: Int = 20\r\n\r\n def pre(mx: Int, L: Int): mutable.Seq[ArrayBuffer[Int]] = {\r\n val prf = ArrayBuffer.fill(M, 20)(0)\r\n (1 until mx).foreach{ i =>\r\n (0 until L).foreach { j =>\r\n prf(i)(j) =\r\n prf(i-1)(j) + {\r\n if (((1 << j) & i) > 0) 1\r\n else 0\r\n }\r\n }\r\n }\r\n prf\r\n }\r\n\r\n def solve(): Unit = {\r\n val prf = pre(M, L)\r\n val T = ni()\r\n\r\n (1 to T).foreach { tc =>\r\n val L = ni()\r\n val R = ni()\r\n val ans =\r\n (0 until 20).map{ j =>\r\n R - L + 1 - {\r\n val x = prf(R)(j) - prf(L-1)(j)\r\n x\r\n }\r\n }.min\r\n out.println(ans)\r\n }\r\n }\r\n\r\n}"}], "src_uid": "0601e3636b5d5b6ad0c8c1abb7f83d82"} {"nl": {"description": "Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x\u2009-\u2009y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is .Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y\u00a0(1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.", "input_spec": "The first line of input contains two integers n and m\u00a0(1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The next line contains m integers separated by spaces: a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u2009n).", "output_spec": "Print a single integer \u2014 the minimum number of pages Ryouko needs to turn.", "sample_inputs": ["4 6\n1 2 3 4 3 2", "10 5\n9 4 3 8 8"], "sample_outputs": ["3", "6"], "notes": "NoteIn the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1,\u20092,\u20093,\u20093,\u20093,\u20092}, so the number of pages Ryouko needs to turn is |1\u2009-\u20092|\u2009+\u2009|2\u2009-\u20093|\u2009+\u2009|3\u2009-\u20093|\u2009+\u2009|3\u2009-\u20093|\u2009+\u2009|3\u2009-\u20092|\u2009=\u20093.In the second sample, optimal solution is achieved by merging page 9 to 4."}, "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\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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the \"less\" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs \"more\" and \"less\" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.", "output_spec": "In a single line, print \"yes\" (without the quotes), if Dima decoded the text message correctly, and \"no\" (without the quotes) otherwise.", "sample_inputs": ["3\ni\nlove\nyou\n<3i<3love<23you<3", "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3"], "sample_outputs": ["yes", "no"], "notes": "NotePlease note that Dima got a good old kick in the pants for the second sample from the statement."}, "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": "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}"}, {"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"} {"nl": {"description": "Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are $$$2$$$ teams each having $$$n$$$ players and $$$2n$$$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the $$$i$$$-th of the heroes as $$$p_i$$$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $$$m$$$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $$$q$$$ or greater regardless of jury's program choices, you must get $$$q$$$ or greater to pass a test.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^3$$$, $$$0 \\le m \\le n$$$)\u00a0\u2014 the number of players in one team and the number of special pairs of heroes. The second line contains $$$2n$$$ integers $$$p_1, p_2, \\ldots, p_{2n}$$$ ($$$1 \\le p_i \\le 10^3$$$)\u00a0\u2014 the powers of the heroes. Each of the next $$$m$$$ lines contains two integer $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 2n$$$, $$$a \\ne b$$$)\u00a0\u2014 a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list. The next line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2$$$)\u00a0\u2014 the team you are to play for. If $$$t = 1$$$, the first turn is yours, otherwise you have the second turn. Hacks In order to hack, use the format described above with one additional line. In this line output $$$2n$$$ distinct integers from $$$1$$$ to $$$2n$$$\u00a0\u2014 the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.", "output_spec": null, "sample_inputs": ["3 1\n1 2 3 4 5 6\n2 6\n1\n\n2\n\n4\n\n1", "3 1\n1 2 3 4 5 6\n1 5\n2\n6\n\n1\n\n3"], "sample_outputs": ["6\n\n5\n\n3", "5\n\n4\n\n2"], "notes": "NoteIn the first example the first turn is yours. In example, you choose $$$6$$$, the other team is forced to reply with $$$2$$$. You choose $$$5$$$, the other team chooses $$$4$$$. Finally, you choose $$$3$$$ and the other team choose $$$1$$$.In the second example you have the second turn. The other team chooses $$$6$$$, you choose $$$5$$$, forcing the other team to choose $$$1$$$. Now you choose $$$4$$$, the other team chooses $$$3$$$ and you choose $$$2$$$."}, "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) = readInts(2)\n val ps = readInts(2 * n)\n\n val pairs = Array.fill(m) {\n readInts(2).map(_ - 1).sortBy(ps)\n }\n\n val Array(t0) = readInts(1)\n var myTurn = t0 == 1\n\n var left = 2 * n\n var next = -1\n while (left > 0) {\n if (myTurn) {\n if (next == -1) {\n var maxPair = 0\n for (i <- 0 until m) {\n val p = ps(pairs(i)(1))\n if (p > maxPair) {\n next = pairs(i)(1)\n maxPair = p\n }\n }\n if (next == -1) {\n var max = 0\n for (i <- 0 until 2 * n) {\n if (ps(i) > max) {\n next = i\n max = ps(i)\n }\n }\n }\n }\n ps(next) = -1\n println(next + 1)\n } else {\n val Array(x0) = readInts(1)\n val x = x0 - 1\n ps(x) = -1\n next = -1\n var i = 0\n while (i < m && next == -1) {\n if (pairs(i)(0) == x && ps(pairs(i)(1)) > 0) {\n next = pairs(i)(1)\n } else if (pairs(i)(1) == x && ps(pairs(i)(0)) > 0) {\n next = pairs(i)(0)\n }\n i += 1\n }\n }\n myTurn = !myTurn\n left -= 1\n }\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(n, m) = readInts(2)\n val ps = readInts(2 * n)\n\n val pairs = Array.fill(m) {\n readInts(2).map(_ - 1).sortBy(ps)\n }\n\n val Array(t0) = readInts(1)\n var myTurn = t0 == 1\n\n var left = 2 * n\n var next = -1\n while (left > 0) {\n if (myTurn) {\n if (next >= 0) {\n println(next + 1)\n } else {\n var maxPair = 0\n for (i <- 0 until m) {\n val p = ps(pairs(i)(1))\n if (p > maxPair) {\n next = pairs(i)(1)\n maxPair = p\n }\n }\n if (next == -1) {\n var max = 0\n for (i <- 0 until 2 * n) {\n if (ps(i) > max) {\n next = i\n max = ps(i)\n }\n }\n }\n ps(next) = -1\n println(next + 1)\n }\n } else {\n val Array(x0) = readInts(1)\n val x = x0 - 1\n ps(x) = -1\n next = -1\n var i = 0\n while (i < m && next == -1) {\n if (pairs(i)(0) == x && ps(pairs(i)(1)) > 0) {\n next = pairs(i)(1)\n } else if (pairs(i)(1) == x && ps(pairs(i)(0)) > 0) {\n next = pairs(i)(0)\n }\n i += 1\n }\n }\n myTurn = !myTurn\n left -= 1\n }\n\n}\n"}], "src_uid": "5e07da229bc2762f3a68bc083e34b9a1"} {"nl": {"description": "This is the easier version of the problem. In this version $$$1 \\le n, m \\le 100$$$. You can hack this problem only if you solve and lock both problems.You are given a sequence of integers $$$a=[a_1,a_2,\\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \\le k \\le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \\dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \\dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \\le t \\le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t<c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \\le k \\le n$$$, $$$1 \\le pos_j \\le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ \u2014 it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \\le m \\le 100$$$) \u2014 the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \\le k \\le n$$$, $$$1 \\le pos_j \\le k_j$$$) \u2014 the requests.", "output_spec": "Print $$$m$$$ integers $$$r_1, r_2, \\dots, r_m$$$ ($$$1 \\le r_j \\le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.", "sample_inputs": ["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"], "sample_outputs": ["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"], "notes": "NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$. "}, "positive_code": [{"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"}, {"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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\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 \u304cLong\u3068\u304b\u3058\u3083\u306a\u3044\u5834\u5408\u306f\u3053\u308c\u3089\u3092\u5b9f\u88c5\u3057\u306a\u3044\u3068\u4e0b\u306e\u5974\u3089\u304c\u4f7f\u3048\u306a\u3044\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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) // \u964d\u9806\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"} {"nl": {"description": "Levko loves array a1,\u2009a2,\u2009... ,\u2009an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types: Increase all elements from li to ri by di. In other words, perform assignments aj\u2009=\u2009aj\u2009+\u2009di for all j that meet the inequation li\u2009\u2264\u2009j\u2009\u2264\u2009ri. Find the maximum of elements from li to ri. That is, calculate the value . Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20095000) \u2014 the size of the array and the number of operations in Levko's records, correspondingly. Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20092) that describes the operation type. If ti\u2009=\u20091, then it is followed by three integers li, ri and di (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n, \u2009-\u2009104\u2009\u2264\u2009di\u2009\u2264\u2009104) \u2014 the description of the operation of the first type. If ti\u2009=\u20092, then it is followed by three integers li, ri and mi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n, \u2009-\u20095\u00b7107\u2009\u2264\u2009mi\u2009\u2264\u20095\u00b7107) \u2014 the description of the operation of the second type. The operations are given in the order Levko performed them on his array.", "output_spec": "In the first line print \"YES\" (without the quotes), if the solution exists and \"NO\" (without the quotes) otherwise. If the solution exists, then on the second line print n integers a1,\u2009a2,\u2009... ,\u2009an (|ai|\u2009\u2264\u2009109) \u2014 the recovered array.", "sample_inputs": ["4 5\n1 2 3 1\n2 1 2 8\n2 3 4 7\n1 1 3 3\n2 3 4 8", "4 5\n1 2 3 1\n2 1 2 8\n2 3 4 7\n1 1 3 3\n2 3 4 13"], "sample_outputs": ["YES\n4 7 4 7", "NO"], "notes": null}, "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 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 val ds = Array.fill(n)(0)\n val as = Array.fill(n)(1000000000)\n \n val ops = Array.fill(m)(readInts(4))\n\n for (j <- 0 until m) {\n val Array(t, l, r, x) = ops(j)\n if (t == 1) {\n var i = l - 1\n while (i < r) {\n ds(i) += x\n i += 1\n }\n } else {\n var i = l - 1\n var found = false\n while (i < r) {\n if (as(i) >= x - ds(i)) found = true\n as(i) = math.min(x - ds(i), as(i))\n i += 1\n }\n if (!found) {\n println(\"NO\")\n exit\n }\n }\n }\n \n val ans = as.clone\n\n for (j <- 0 until m) {\n val Array(t, l, r, x) = ops(j)\n if (t == 1) {\n var i = l - 1\n while (i < r) {\n as(i) += x\n i += 1\n }\n } else {\n if (x != as.view(l - 1, r).max) {\n println(\"NO\")\n exit\n }\n }\n }\n\n println(\"YES\")\n println(ans.mkString(\" \"))\n}"}], "negative_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 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 val ds = Array.fill(n)(0)\n val maxs = Array.fill(n)(1000000000)\n\n for (j <- 0 until m) {\n val Array(t, l, r, x) = readInts(4)\n if (t == 1) {\n var i = l - 1\n while (i < r) {\n ds(i) += x\n i += 1\n }\n } else {\n var i = l - 1\n var found = false\n while (i < r) {\n if (maxs(i) >= x - ds(i)) {\n found = true\n maxs(i) = math.min(x - ds(i), maxs(i))\n //ds(i) = 0\n } else {\n maxs(i) = math.min(x - ds(i), maxs(i))\n //maxs(i) -= ds(i)\n //ds(i) = 0\n }\n i += 1\n }\n if (!found) {\n //println(j, i, maxs(i), ds(i), x)\n println(\"NO\")\n exit\n }\n }\n }\n\n println(\"YES\")\n println(maxs.mkString(\" \"))\n}"}], "src_uid": "ae5757df3be42b74076cdf42f7f897cd"} {"nl": {"description": "Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.It is known that in a match between two players, the one whose skill is greater will win. The skill of the $$$i$$$-th player is equal to $$$s_i$$$ and all skill levels are pairwise different (i.\u2009e. there are no two identical values in the array $$$s$$$).The tournament is called fair if the two players with the highest skills meet in the finals.Determine whether the given tournament is fair.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. A single line of test case contains four integers $$$s_1, s_2, s_3, s_4$$$ ($$$1 \\le s_i \\le 100$$$)\u00a0\u2014 skill of the players. It is guaranteed that all the numbers in the array are different.", "output_spec": "For each testcase, output YES if the tournament is fair, or NO otherwise.", "sample_inputs": ["4\n3 7 9 5\n4 5 6 9\n5 3 8 1\n6 5 3 2"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteConsider the example: in the first test case, players $$$2$$$ and $$$3$$$ with skills $$$7$$$ and $$$9$$$ advance to the finals; in the second test case, players $$$2$$$ and $$$4$$$ with skills $$$5$$$ and $$$9$$$ advance to the finals. The player with skill $$$6$$$ does not advance, but the player with skill $$$5$$$ advances to the finals, so the tournament is not fair; in the third test case, players $$$1$$$ and $$$3$$$ with skills $$$5$$$ and $$$8$$$ advance to the finals; in the fourth test case, players $$$1$$$ and $$$3$$$ with skills $$$6$$$ and $$$3$$$ advance to the finals. The player with skill $$$5$$$ does not advance, but the player with skill $$$3$$$ advances to the finals, so the tournament is not fair. "}, "positive_code": [{"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"}, {"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\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}"}], "negative_code": [], "src_uid": "cb24509580ff9b2f1a11103a0e4cdcbd"} {"nl": {"description": "Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $$$i$$$-th page contains some mystery that will be explained on page $$$a_i$$$ ($$$a_i \\ge i$$$).Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $$$i$$$ such that Ivan already has read it, but hasn't read page $$$a_i$$$). After that, he closes the book and continues to read it on the following day from the next page.How many days will it take to read the whole book?", "input_spec": "The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$) \u2014 the number of pages in the book. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$i \\le a_i \\le n$$$), where $$$a_i$$$ is the number of page which contains the explanation of the mystery on page $$$i$$$.", "output_spec": "Print one integer \u2014 the number of days it will take to read the whole book.", "sample_inputs": ["9\n1 3 3 6 7 6 8 8 9"], "sample_outputs": ["4"], "notes": "NoteExplanation of the example test:During the first day Ivan will read only the first page. During the second day Ivan will read pages number $$$2$$$ and $$$3$$$. During the third day \u2014 pages $$$4$$$-$$$8$$$. During the fourth (and the last) day Ivan will read remaining page number $$$9$$$."}, "positive_code": [{"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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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": "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"}], "negative_code": [], "src_uid": "291601d6cdafa4113c1154f0dda3470d"} {"nl": {"description": "You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters and an integer number $$$k$$$.Let's define a substring of some string $$$s$$$ with indices from $$$l$$$ to $$$r$$$ as $$$s[l \\dots r]$$$.Your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ positions $$$i$$$ such that $$$s[i \\dots i + n - 1] = t$$$. In other words, your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$.It is guaranteed that the answer is always unique.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 50$$$) \u2014 the length of the string $$$t$$$ and the number of substrings. The second line of the input contains the string $$$t$$$ consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "Print such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$. It is guaranteed that the answer is always unique.", "sample_inputs": ["3 4\naba", "3 2\ncat"], "sample_outputs": ["ababababa", "catcat"], "notes": null}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "You had $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$ arranged in a circle. For each pair of neighboring numbers ($$$a_1$$$ and $$$a_2$$$, $$$a_2$$$ and $$$a_3$$$, ..., $$$a_{n - 1}$$$ and $$$a_n$$$, and $$$a_n$$$ and $$$a_1$$$), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array $$$a$$$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $$$a$$$ which is consistent with information you have about equality or non-equality of corresponding pairs?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains a non-empty string $$$s$$$ consisting of characters E and/or N. The length of $$$s$$$ is equal to the size of array $$$n$$$ and $$$2 \\le n \\le 50$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$: if $$$s_i =$$$ E then $$$a_i$$$ is equal to $$$a_{i + 1}$$$ ($$$a_n = a_1$$$ for $$$i = n$$$); if $$$s_i =$$$ N then $$$a_i$$$ is not equal to $$$a_{i + 1}$$$ ($$$a_n \\neq a_1$$$ for $$$i = n$$$). ", "output_spec": "For each test case, print YES if it's possible to choose array $$$a$$$ that are consistent with information from $$$s$$$ you know. Otherwise, print NO. It can be proved, that if there exists some array $$$a$$$, then there exists an array $$$a$$$ of positive integers with values less or equal to $$$10^9$$$.", "sample_inputs": ["4\nEEE\nEN\nENNEENE\nNENN"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteIn the first test case, you can choose, for example, $$$a_1 = a_2 = a_3 = 5$$$.In the second test case, there is no array $$$a$$$, since, according to $$$s_1$$$, $$$a_1$$$ is equal to $$$a_2$$$, but, according to $$$s_2$$$, $$$a_2$$$ is not equal to $$$a_1$$$.In the third test case, you can, for example, choose array $$$a = [20, 20, 4, 50, 50, 50, 20]$$$.In the fourth test case, you can, for example, choose $$$a = [1, 3, 3, 7]$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "e744184150bf55a30568060cca69de04"} {"nl": {"description": "Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,\u2009i,\u2009j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.", "input_spec": "The first line contains odd integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.", "output_spec": "Print one number \u2014 minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.", "sample_inputs": ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"], "sample_outputs": ["1", "2"], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "dc46c6cb6b4b9b5e7e6e5b4b7d034874"} {"nl": {"description": "Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) has a best friend p[i] (1\u2009\u2264\u2009p[i]\u2009\u2264\u2009n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really \"special individuals\" for who i\u2009=\u2009p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: on the first day of revising each student studies his own Mathematical Analysis notes, in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1\u2009\u2264\u2009i\u2009\u2264\u2009n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising: a1,\u2009a2,\u2009...,\u2009an, where ai means the student who gets the i-th student's notebook on the third day of revising; b1,\u2009b2,\u2009...,\u2009bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of students in the group. The second line contains sequence of different integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n). The third line contains the sequence of different integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009n).", "output_spec": "Print sequence n of different integers p[1],\u2009p[2],\u2009...,\u2009p[n] (1\u2009\u2264\u2009p[i]\u2009\u2264\u2009n). It is guaranteed that the solution exists and that it is unique.", "sample_inputs": ["4\n2 1 4 3\n3 4 2 1", "5\n5 2 3 1 4\n1 3 2 4 5", "2\n1 2\n2 1"], "sample_outputs": ["4 3 1 2", "4 3 2 5 1", "2 1"], "notes": null}, "positive_code": [{"source_code": "import java.util.InputMismatchException\nimport java.util.Scanner\nimport java.io.InputStream\nimport java.io.PrintWriter\n\n/**\n * Created with IntelliJ IDEA.\n */\nobject ProblemF extends App {\n val in = new InputReader(System.in)\n var out = new PrintWriter(System.out)\n val n = in.nextInt\n val data = new Array[Int](n+1)\n (1 to n).foreach(f => {\n data(in.nextInt) = f\n })\n (1 to n).foreach(x => {\n if (x > 1) {\n out.print(' ')\n }\n out.print(data(in.nextInt()))\n })\n out.println()\n out.flush()\n\n\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"}], "negative_code": [], "src_uid": "a133b2c63e1025bdf13d912497f9b6a4"} {"nl": {"description": "You are given a graph with $$$3 \\cdot n$$$ vertices and $$$m$$$ edges. You are to find a matching of $$$n$$$ edges, or an independent set of $$$n$$$ vertices.A set of edges is called a matching if no two edges share an endpoint.A set of vertices is called an independent set if no two vertices are connected with an edge.", "input_spec": "The first line contains a single integer $$$T \\ge 1$$$\u00a0\u2014 the number of graphs you need to process. The description of $$$T$$$ graphs follows. The first line of description of a single graph contains two integers $$$n$$$ and $$$m$$$, where $$$3 \\cdot n$$$ is the number of vertices, and $$$m$$$ is the number of edges in the graph ($$$1 \\leq n \\leq 10^{5}$$$, $$$0 \\leq m \\leq 5 \\cdot 10^{5}$$$). Each of the next $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \\leq v_i, u_i \\leq 3 \\cdot n$$$), meaning that there is an edge between vertices $$$v_i$$$ and $$$u_i$$$. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all $$$n$$$ over all graphs in a single test does not exceed $$$10^{5}$$$, and the sum of all $$$m$$$ over all graphs in a single test does not exceed $$$5 \\cdot 10^{5}$$$.", "output_spec": "Print your answer for each of the $$$T$$$ graphs. Output your answer for a single graph in the following format. If you found a matching of size $$$n$$$, on the first line print \"Matching\" (without quotes), and on the second line print $$$n$$$ integers\u00a0\u2014 the indices of the edges in the matching. The edges are numbered from $$$1$$$ to $$$m$$$ in the input order. If you found an independent set of size $$$n$$$, on the first line print \"IndSet\" (without quotes), and on the second line print $$$n$$$ integers\u00a0\u2014 the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print \"Impossible\" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size $$$n$$$, and an independent set of size $$$n$$$, then you should print exactly one of such matchings or exactly one of such independent sets.", "sample_inputs": ["4\n1 2\n1 3\n1 2\n1 2\n1 3\n1 2\n2 5\n1 2\n3 1\n1 4\n5 1\n1 6\n2 15\n1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 5\n4 6\n5 6"], "sample_outputs": ["Matching\n2\nIndSet\n1\nIndSet\n2 4\nMatching\n1 15"], "notes": "NoteThe first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly $$$n$$$.The fourth graph does not have an independent set of size 2, but there is a matching of size 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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n class Flag(n: Int) {\n val b = Array.ofDim[Boolean](n)\n val ix = Array.fill[Int](n)(-1)\n\n def is(i: Int, g: Int): Boolean = {\n if (ix(i) != g) {\n ix(i) = g\n b(i) = false\n }\n b(i)\n }\n\n def set(i: Int, g: Int, flg: Boolean): Unit = {\n b(i) = flg\n ix(i) = g\n }\n }\n\n def solve(): Unit = {\n val fg = new Flag(3e5.toInt)\n REP(ni()) { t =>\n val N, M = ni()\n\n val mt = ArrayBuffer[Int]()\n REP(M) { i =>\n val u, v = ni() - 1\n if (!fg.is(u, t) && !fg.is(v, t)) {\n mt += i\n fg.set(u, t, flg = true)\n fg.set(v, t, flg = true)\n }\n }\n\n debug(mt.mkString(\" \"))\n DEBUG {\n debug(map(3 * N)(fg.is(_, t)))\n }\n\n if (mt.length >= N) {\n out.println(\"Matching\")\n REP(N) { i =>\n out.print(s\"${mt(i)+1} \")\n }\n out.println()\n } else {\n out.println(\"IndSet\")\n var i = 0\n var cnt = 0\n while(cnt < N) {\n if (!fg.is(i, t)) {\n out.print(s\"${i+1} \")\n cnt += 1\n }\n i += 1\n }\n out.println()\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "0cca30daffe672caa6a6fdbb6a935f43"} {"nl": {"description": "There is an array $$$a$$$ with $$$n-1$$$ integers. Let $$$x$$$ be the bitwise XOR of all elements of the array. The number $$$x$$$ is added to the end of the array $$$a$$$ (now it has length $$$n$$$), and then the elements are shuffled.You are given the newly formed array $$$a$$$. What is $$$x$$$? If there are multiple possible values of $$$x$$$, you can output any of them.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the number of integers in the resulting array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 127$$$)\u00a0\u2014 the elements of the newly formed array $$$a$$$. Additional constraint on the input: the array $$$a$$$ is made by the process described in the statement; that is, some value of $$$x$$$ exists.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the value of $$$x$$$, as described in the statement. If there are multiple possible values of $$$x$$$, output any of them.", "sample_inputs": ["4\n\n4\n\n4 3 2 5\n\n5\n\n6 1 10 7 10\n\n6\n\n6 6 6 6 6 6\n\n3\n\n100 100 0"], "sample_outputs": ["3\n7\n6\n0"], "notes": "NoteIn the first test case, one possible array $$$a$$$ is $$$a=[2, 5, 4]$$$. Then $$$x = 2 \\oplus 5 \\oplus 4 = 3$$$ ($$$\\oplus$$$ denotes the bitwise XOR), so the new array is $$$[2, 5, 4, 3]$$$. Afterwards, the array is shuffled to form $$$[4, 3, 2, 5]$$$.In the second test case, one possible array $$$a$$$ is $$$a=[1, 10, 6, 10]$$$. Then $$$x = 1 \\oplus 10 \\oplus 6 \\oplus 10 = 7$$$, so the new array is $$$[1, 10, 6, 10, 7]$$$. Afterwards, the array is shuffled to form $$$[6, 1, 10, 7, 10]$$$.In the third test case, all elements of the array are equal to $$$6$$$, so $$$x=6$$$.In the fourth test case, one possible array $$$a$$$ is $$$a=[100, 100]$$$. Then $$$x = 100 \\oplus 100 = 0$$$, so the new array is $$$[100, 100, 0]$$$. Afterwards, the array is shuffled to form $$$[100, 100, 0]$$$. (Note that after the shuffle, the array can remain the same.)"}, "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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokinizer = new StringTokenizer(input.readLine())\r\n val n = tokinizer.nextToken().toInt\r\n for (i <- 1 to n) {\r\n tokinizer = new StringTokenizer(input.readLine())\r\n val a = tokinizer.nextToken()\r\n tokinizer = new StringTokenizer(input.readLine())\r\n val b = tokinizer.nextToken()\r\n output.println(b)\r\n }\r\n }\r\n\r\n\r\n}"}], "negative_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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokinizer = new StringTokenizer(input.readLine())\r\n val n = tokinizer.nextToken().toInt\r\n for (i <- 1 to n) {\r\n tokinizer = new StringTokenizer(input.readLine())\r\n val a = tokinizer.nextToken()\r\n output.println(a)\r\n }\r\n }\r\n\r\n\r\n}"}], "src_uid": "329ac6671e26b73ab70749ca509f5b09"} {"nl": {"description": "A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the values of the banknotes.", "output_spec": "Print a single line \u2014 the minimum unfortunate sum. If there are no unfortunate sums, print \u2009-\u20091.", "sample_inputs": ["5\n1 2 3 4 5"], "sample_outputs": ["-1"], "notes": null}, "positive_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 println(\"-1\")\n } else {\n println(\"1\")\n }\n }\n}"}, {"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"} {"nl": {"description": "A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $$$0$$$ are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars: The leftmost figure is a star of size $$$1$$$, the middle figure is a star of size $$$2$$$ and the rightmost figure is a star of size $$$3$$$. You are given a rectangular grid of size $$$n \\times m$$$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $$$1$$$ to $$$n$$$, columns are numbered from $$$1$$$ to $$$m$$$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $$$n \\cdot m$$$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $$$n \\cdot m$$$ stars.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$3 \\le n, m \\le 100$$$) \u2014 the sizes of the given grid. The next $$$n$$$ lines contains $$$m$$$ characters each, the $$$i$$$-th line describes the $$$i$$$-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.", "output_spec": "If it is impossible to draw the given grid using stars only, print \"-1\". Otherwise in the first line print one integer $$$k$$$ ($$$0 \\le k \\le n \\cdot m$$$) \u2014 the number of stars needed to draw the given grid. The next $$$k$$$ lines should contain three integers each \u2014 $$$x_j$$$, $$$y_j$$$ and $$$s_j$$$, where $$$x_j$$$ is the row index of the central star character, $$$y_j$$$ is the column index of the central star character and $$$s_j$$$ is the size of the star. Each star should be completely inside the grid.", "sample_inputs": ["6 8\n....*...\n...**...\n..*****.\n...**...\n....*...\n........", "5 5\n.*...\n****.\n.****\n..**.\n.....", "5 5\n.*...\n***..\n.*...\n.*...\n.....", "3 3\n*.*\n.*.\n*.*"], "sample_outputs": ["3\n3 4 1\n3 5 2\n3 5 1", "3\n2 2 1\n3 3 1\n3 4 1", "-1", "-1"], "notes": "NoteIn the first example the output 23 4 13 5 2is also correct."}, "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) // \u4e2d\u5fc3\u3082\u542b\u3081\u305f\u9577\u3055\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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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) // \u4e2d\u5fc3\u3082\u542b\u3081\u305f\u9577\u3055\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}"}], "negative_code": [], "src_uid": "59d4c66892fa3157d1163225a550a368"} {"nl": {"description": "DZY has a sequence a, consisting of n integers.We'll call a sequence ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj (1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n) a subsegment of the sequence a. The value (j\u2009-\u2009i\u2009+\u20091) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.", "input_spec": "The first line contains integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers a1,\u2009a2,\u2009...,\u2009an\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "In a single line print the answer to the problem \u2014 the maximum length of the required subsegment.", "sample_inputs": ["6\n7 2 3 1 5 6"], "sample_outputs": ["5"], "notes": "NoteYou can choose subsegment a2,\u2009a3,\u2009a4,\u2009a5,\u2009a6 and change its 3rd element (that is a4) to 4."}, "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 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"}, {"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-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": "\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 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 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 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"}, {"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"} {"nl": {"description": "You and your friends live in $$$n$$$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. ", "input_spec": "First line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$ \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \\leq n \\leq 1000)$$$. Next $$$n$$$ lines describe the positions of the houses $$$(x_i, y_i)$$$ $$$(0 \\leq x_i, y_i \\leq 10^9)$$$. It's guaranteed that the sum of all $$$n$$$ does not exceed $$$1000$$$.", "output_spec": "For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house.", "sample_inputs": ["6\n3\n0 0\n2 0\n1 2\n4\n1 0\n0 2\n2 3\n3 1\n4\n0 0\n0 1\n1 0\n1 1\n2\n0 0\n1 1\n2\n0 0\n2 0\n2\n0 0\n0 0"], "sample_outputs": ["1\n4\n4\n4\n3\n1"], "notes": "NoteHere are the images for the example test cases. Blue dots stand for the houses, green \u2014 possible positions for the exhibition.First test case.Second test case. Third test case. Fourth test case. Fifth test case. Sixth test case. Here both houses are located at $$$(0, 0)$$$."}, "positive_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.ArrayBuffer\r\n\r\nobject BEasternExhibition {\r\n def solve(xs: ArrayBuffer[Long], ys: ArrayBuffer[Long]): Long = {\r\n def count(list: ArrayBuffer[Long], size: Int): Long = {\r\n if (size % 2 == 1) 1 else list(size/2) - list(size/2-1) + 1\r\n }\r\n count(xs, xs.size)*count(ys, ys.size)\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\\n3\\n0 0\\n2 0\\n1 2\\n4\\n1 0\\n0 2\\n2 3\\n3 1\\n4\\n0 0\\n0 1\\n1 0\\n1 1\\n2\\n0 0\\n1 1\\n2\\n0 0\\n2 0\\n2\\n0 0\\n0 0\".getBytes)))\r\n//\"1\\n3\\n853308909 201424080\\n881046497 871539684\\n161055688 504667277\".getBytes)))\r\n val inputs = file.readLine.toInt\r\n var i = 0\r\n while (i < inputs) {\r\n val p = file.readLine.toInt; var j = 0\r\n val xs = ArrayBuffer[Long]()\r\n val ys = ArrayBuffer[Long]()\r\n while (j < p) {\r\n val arr = file.readLine.split(\" \").map(_.toLong)\r\n xs += arr(0)\r\n ys += arr(1)\r\n j += 1\r\n }\r\n println(solve(xs.sorted, ys.sorted))\r\n i += 1\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\nimport scala.collection.mutable\r\n\r\nobject BEasternExhibition {\r\n def solve(xs: List[Long], ys: List[Long]): Long = {\r\n def count(list: List[Long], size: Int): Long = {\r\n if (size % 2 == 1) 1 else list(size/2) - list(size/2-1) + 1\r\n }\r\n count(xs, xs.size)*count(ys, ys.size)\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\\n3\\n0 0\\n2 0\\n1 2\\n4\\n1 0\\n0 2\\n2 3\\n3 1\\n4\\n0 0\\n0 1\\n1 0\\n1 1\\n2\\n0 0\\n1 1\\n2\\n0 0\\n2 0\\n2\\n0 0\\n0 0\".getBytes)))\r\n//\"1\\n3\\n853308909 201424080\\n881046497 871539684\\n161055688 504667277\".getBytes)))\r\n val inputs = file.readLine.toInt\r\n var i = 0\r\n while (i < inputs) {\r\n val p = file.readLine.toInt; var j = 0\r\n val xs = mutable.TreeSet[Long]()\r\n val ys = mutable.TreeSet[Long]()\r\n while (j < p) {\r\n val arr = file.readLine.split(\" \").map(_.toLong)\r\n xs += arr(0)\r\n ys += arr(1)\r\n j += 1\r\n }\r\n println(solve(xs.toList, ys.toList))\r\n i += 1\r\n }\r\n }\r\n}"}, {"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 BEasternExhibition {\r\n def solve(xs: ArrayBuffer[Long], ys: ArrayBuffer[Long]): Long = {\r\n val l = xs.size\r\n if (l == 1) 1\r\n else if (l == 2) (Math.abs(xs(0) - xs(1)) + 1)*(1 + Math.abs(ys(0) - ys(1)))\r\n else {\r\n// def countMinPos(ys: ArrayBuffer[Long]): Long = {\r\n// var min = Long.MaxValue\r\n// var countMin = 0\r\n// var yd = 0L\r\n// for (p <- ys) {\r\n// yd += Math.abs(ys(0) - p)\r\n// }\r\n// var curr = 1\r\n// for (y <- ys(1) to ys.last) {\r\n// while (ys(curr) < y) {\r\n// curr += 1\r\n// }\r\n// val delta = curr - l + curr\r\n// yd += delta\r\n// if (yd < min) {\r\n// min = yd\r\n// countMin = 1\r\n// } else if (yd == min) countMin += 1\r\n// }\r\n// countMin\r\n// }\r\n def countMinPos2(ys: ArrayBuffer[Long]): Long = {\r\n var yd = 0L\r\n for (p <- ys) {\r\n yd += Math.abs(ys(0) - p)\r\n }\r\n var min = yd\r\n var countMin = 1L\r\n for (i <- 1 until ys.size) {\r\n val delta = i - l + i\r\n yd += delta\r\n val diff = ys(i) - ys(i - 1)\r\n if (yd < min) {\r\n min = yd\r\n countMin = if (diff == 0) 1 else diff\r\n } else if (yd == min) countMin += (if (diff == 0) 1 else diff)\r\n }\r\n countMin\r\n }\r\n val mc = Math.min(countMinPos2(xs), countMinPos2(ys))\r\n mc * mc\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\\n3\\n0 0\\n2 0\\n1 2\\n4\\n1 0\\n0 2\\n2 3\\n3 1\\n4\\n0 0\\n0 1\\n1 0\\n1 1\\n2\\n0 0\\n1 1\\n2\\n0 0\\n2 0\\n2\\n0 0\\n0 0\".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 p = file.readLine.toInt; var j = 0\r\n val xs = ArrayBuffer[Long]()\r\n val ys = ArrayBuffer[Long]()\r\n while (j < p) {\r\n val arr = file.readLine.split(\" \").map(_.toLong)\r\n xs += arr(0)\r\n ys += arr(1)\r\n j += 1\r\n }\r\n println(solve(xs.sorted, ys.sorted))\r\n i += 1\r\n }\r\n }\r\n}"}], "src_uid": "e0a1dc397838852957d0e15ec98d5efe"} {"nl": {"description": "A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 then number of notes in Petya's logbook. The second line contains n non-negative integers t1,\u2009t2,\u2009...,\u2009tn (0\u2009\u2264\u2009ti\u2009<\u2009i) \u2014 notes in the logbook.", "output_spec": "In the only line print a single integer \u2014 the minimum possible number of rooms in Paris catacombs.", "sample_inputs": ["2\n0 0", "5\n0 1 0 1 3"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample, sequence of rooms Petya visited could be, for example 1\u2009\u2192\u20091\u2009\u2192\u20092, 1\u2009\u2192\u20092\u2009\u2192\u20091 or 1\u2009\u2192\u20092\u2009\u2192\u20093. The minimum possible number of rooms is 2.In the second sample, the sequence could be 1\u2009\u2192\u20092\u2009\u2192\u20093\u2009\u2192\u20091\u2009\u2192\u20092\u2009\u2192\u20091."}, "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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 roomByMinute = Array.fill(n + 1)(-1)\n val lastVisit = ArrayBuffer.empty[Int]\n\n roomByMinute(0) = 1\n lastVisit += 0\n lastVisit += 0\n var maxRoom = 1\n\n var now = 1\n for (t <- ts) {\n val r = roomByMinute(t)\n if (lastVisit(r) == t) {\n lastVisit(r) = now\n roomByMinute(now) = r\n } else {\n maxRoom += 1\n lastVisit += now\n roomByMinute(now) = maxRoom\n }\n now += 1\n }\n\n println(maxRoom)\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 val ts = readInts(n)\n\n val zeros = ts.count(_ == 0)\n val max = ts.max\n\n val res = zeros max max\n\n println(res)\n}\n"}], "src_uid": "81c6342b7229892d71cb43e72aee99e9"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$ both of length $$$2$$$ and both consisting only of characters 'a', 'b' and 'c'.Possible examples of strings $$$s$$$ and $$$t$$$: \"ab\", \"ca\", \"bb\".You have to find a string $$$res$$$ consisting of $$$3n$$$ characters, $$$n$$$ characters should be 'a', $$$n$$$ characters should be 'b' and $$$n$$$ characters should be 'c' and $$$s$$$ and $$$t$$$ should not occur in $$$res$$$ as substrings.A substring of a string is a contiguous subsequence of that string. So, the strings \"ab\", \"ac\" and \"cc\" are substrings of the string \"abacc\", but the strings \"bc\", \"aa\" and \"cb\" are not substrings of the string \"abacc\".If there are multiple answers, you can print any of them.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of characters 'a', 'b' and 'c' in the resulting string. The second line of the input contains one string $$$s$$$ of length $$$2$$$ consisting of characters 'a', 'b' and 'c'. The third line of the input contains one string $$$t$$$ of length $$$2$$$ consisting of characters 'a', 'b' and 'c'.", "output_spec": "If it is impossible to find the suitable string, print \"NO\" on the first line. Otherwise print \"YES\" on the first line and string $$$res$$$ on the second line. $$$res$$$ should consist of $$$3n$$$ characters, $$$n$$$ characters should be 'a', $$$n$$$ characters should be 'b' and $$$n$$$ characters should be 'c' and $$$s$$$ and $$$t$$$ should not occur in $$$res$$$ as substrings. If there are multiple answers, you can print any of them.", "sample_inputs": ["2\nab\nbc", "3\naa\nbc", "1\ncb\nac"], "sample_outputs": ["YES\nacbbac", "YES\ncacbacbab", "YES\nabc"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contest1213\n\nobject TwoSmallStrings {\n def categoriseInput(): (Int, (String, String, String)) = {\n val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)\n val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)\n\n val all = Set(\"a\", \"b\", \"c\")\n\n if (l1 == l2 && r1 == r2) { // both same\n if (l1 == r1)\n (9, (l1, (all - l1).toList.head, (all - l1).toList.last))\n else\n (10, (l1, r1, (all - l1 - r1).head))\n } else if (l1 == l2) {\n if (l1 == r1)\n (1, (l1, r2, (all - l1 - r2).head))\n else if (l1 == r2)\n (1, (l1, r1, (all - l1 - r1).head))\n else\n (2, (l1, r1, r2))\n } else {\n if (l1 == r1 && l2 == r2)\n (6, (l1, l2, (all - l1 - l2).head))\n else if (l1 == r1) {\n if (l1 == r2)\n (5, (l1, l2, (all - l1 - l2).head))\n else\n (4, (l1, l2, r2))\n } else if (l2 == r2) {\n if (l2 == r1)\n (5, (l2, l1, (all - l1 - l2).head))\n else\n (4, (l2, l1, r1))\n } else {\n if (l2 == r1 && l1 == r2)\n (8, (l1, r1, (all - l1 - l2).head))\n else if (l2 == r1)\n (3, (l1, r1, r2))\n else if (l1 == r2)\n (3, (l2, r2, r1))\n else\n (7, (l1, r1, l2)) // r1 ==r2\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val (i, (x, y, z)) = categoriseInput()\n\n println(s\"YES\")\n println {\n i match {\n case 1 | 3 | 4 | 5 | 8 | 9 | 10 => (x + z) * n + y * n\n case 2 => y * n + z * n + x * n\n case 6 => (x + y) * n + z * n\n case 7 => y * n + (x + z) * n\n }\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1213\n\nobject TwoSmallStrings {\n\n def categoriseInput(): (Int, (String, String, String)) = {\n val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)\n val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)\n\n val all = Set(\"a\", \"b\", \"c\")\n\n if (l1 == l2 && r1 == r2) {\n if (l1 == r1)\n (7, (l1, (all - l1).toList.head, (all - l1).toList.last))\n else\n (8, (l1, r1, (all - l1 - r1).head))\n } else if (l1 == l2) {\n if (l1 == r1)\n (1, (l1, r2, (all - l1 - r2).head))\n else if (l1 == r2)\n (1, (l1, r1, (all - l1 - r2).head))\n else\n (2, (l1, r1, r2))\n } else {\n if (l1 == r1 && l2 == r2)\n (6, (l1, l2, (all - l1 - l2).head))\n else if (l1 == r1) {\n if (l1 == r2)\n (5, (l1, l2, (all - l1 - l2).head))\n else\n (4, (l1, l2, r2))\n } else if (l2 == r2) {\n if (l2 == r1)\n (5, (l2, l1, (all - l1 - l2).head))\n else\n (4, (l2, l1, r1))\n } else {\n if (l2 == r1)\n (3, (l1, r1, r2))\n else\n (3, (l2, r2, r1))\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val (i, (x, y, z)) = categoriseInput()\n\n println(s\"YES\")\n println {\n i match {\n case 1 | 3 | 4 | 5 | 7 | 8 => (x + z) * n + y * n\n case 2 => y * n + z * n + x * n\n case 6 => (x + y) * n + z * n\n }\n }\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject TwoSmallStrings {\n val base: Map[Char, Set[Char]] = Map(\n 'a' -> Set('a', 'b', 'c'),\n 'b' -> Set('a', 'b', 'c'),\n 'c' -> Set('a', 'b', 'c')\n )\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val graph = {\n val Array(l1, r1) = io.StdIn.readLine.toCharArray\n val Array(l2, r2) = io.StdIn.readLine.toCharArray\n\n base + (l1 -> (base(l1) - r1)) + (l2 -> (base(l2) - r2))\n }\n\n def dfs(c: Char,\n available: Vector[Int], // size 3\n res: Vector[Char]): Option[Vector[Char]] =\n if (available.forall(_ == 0)) Some(res)\n else if (available(c - 'a') <= 0) None\n else {\n val updatedRes = res :+ c\n val updatedAvailable =\n available.updated(c - 'a', available(c - 'a') - 1)\n\n graph(c).foldLeft(Option.empty[Vector[Char]])(\n (acc, next) =>\n if (acc.isDefined) acc else dfs(next, updatedAvailable, updatedRes)\n )\n }\n\n println {\n List('a', 'b', 'c').foldLeft(Option.empty[Vector[Char]])(\n (acc, next) =>\n if (acc.isDefined) acc else dfs(next, Vector(n, n, n), Vector.empty)\n ) match {\n case Some(value) => \"YES\\n\" + value.mkString\n case None => \"NO\"\n }\n }\n }\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject TwoSmallStrings {\n def categoriseInput(): (Int, (String, String, String)) = {\n val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)\n val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)\n\n val all = Set(\"a\", \"b\", \"c\")\n\n if (l1 == l2 && r1 == r2) {\n if (l1 == r1)\n (8, (l1, (all - l1).toList.head, (all - l1).toList.last))\n else\n (9, (l1, r1, (all - l1 - r1).head))\n } else if (l1 == l2) {\n\n\n if (l1 == r1)\n (1, (l1, r2, (all - l1 - r2).head))\n else if (l1 == r2)\n (1, (l1, r1, (all - l1 - r1).head))\n else\n (2, (l1, r1, r2))\n\n\n } else {\n if (l1 == r1 && l2 == r2)\n (6, (l1, l2, (all - l1 - l2).head))\n else if (l1 == r1) {\n if (l1 == r2)\n (5, (l1, l2, (all - l1 - l2).head))\n else\n (4, (l1, l2, r2))\n } else if (l2 == r2) {\n if (l2 == r1)\n (5, (l2, l1, (all - l1 - l2).head))\n else\n (4, (l2, l1, r1))\n } else {\n if (l2 == r1)\n (3, (l1, r1, r2))\n else if (l1 == r2)\n (3, (l2, r2, r1))\n else\n (7, (l1, r1, l2))\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val (i, (x, y, z)) = categoriseInput()\n\n println(s\"YES\")\n println {\n i match {\n case 1 | 3 | 4 | 5 | 8 | 9 => (x + z) * n + y * n\n case 2 => y * n + z * n + x * n\n case 6 => (x + y) * n + z * n\n case 7 => y * n + (x + z) * n\n }\n }\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject TwoSmallStrings {\n def categoriseInput(): (Int, (String, String, String)) = {\n val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)\n val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)\n\n val all = Set(\"a\", \"b\", \"c\")\n\n if (l1 == l2 && r1 == r2) {\n if (l1 == r1)\n (8, (l1, (all - l1).toList.head, (all - l1).toList.last))\n else\n (9, (l1, r1, (all - l1 - r1).head))\n } else if (l1 == l2) {\n if (l1 == r1)\n (1, (l1, r2, (all - l1 - r2).head))\n else if (l1 == r2)\n (1, (l1, r1, (all - l1 - r2).head))\n else\n (2, (l1, r1, r2))\n } else {\n if (l1 == r1 && l2 == r2)\n (6, (l1, l2, (all - l1 - l2).head))\n else if (l1 == r1) {\n if (l1 == r2)\n (5, (l1, l2, (all - l1 - l2).head))\n else\n (4, (l1, l2, r2))\n } else if (l2 == r2) {\n if (l2 == r1)\n (5, (l2, l1, (all - l1 - l2).head))\n else\n (4, (l2, l1, r1))\n } else {\n if (l2 == r1)\n (3, (l1, r1, r2))\n else if (l1 == r2)\n (3, (l2, r2, r1))\n else\n (7, (l1, r1, l2))\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val (i, (x, y, z)) = categoriseInput()\n\n println(s\"YES\")\n println {\n i match {\n case 1 | 3 | 4 | 5 | 8 | 9 => (x + z) * n + y * n\n case 2 => y * n + z * n + x * n\n case 6 => (x + y) * n + z * n\n case 7 => y * n + (x + z) * n\n }\n }\n }\n\n}\n"}], "src_uid": "7f45fba2c06fe176a2b634e8988076c2"} {"nl": {"description": "On an $$$8 \\times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R. ", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 4000$$$)\u00a0\u2014 the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.", "output_spec": "For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).", "sample_inputs": ["4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........"], "sample_outputs": ["R\nB\nB\nR"], "notes": "NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B."}, "positive_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\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"}, {"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"} {"nl": {"description": "You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operations on it: choose an index $$$i$$$ $$$(1 \\le i \\le n)$$$, an integer $$$x$$$ $$$(0 \\le x \\le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j+x$$$ for all $$$(1 \\le j \\le i)$$$, which means add $$$x$$$ to all the elements in the prefix ending at $$$i$$$. choose an index $$$i$$$ $$$(1 \\le i \\le n)$$$, an integer $$$x$$$ $$$(1 \\le x \\le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j \\% x$$$ for all $$$(1 \\le j \\le i)$$$, which means replace every element in the prefix ending at $$$i$$$ with the remainder after dividing it by $$$x$$$. Can you make the array strictly increasing in no more than $$$n+1$$$ operations?", "input_spec": "The first line contains an integer $$$n$$$ $$$(1 \\le n \\le 2000)$$$, the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\dots$$$, $$$a_n$$$ $$$(0 \\le a_i \\le 10^5)$$$, the elements of the array $$$a$$$.", "output_spec": "On the first line, print the number of operations you wish to perform. On the next lines, you should print the operations. To print an adding operation, use the format \"$$$1$$$ $$$i$$$ $$$x$$$\"; to print a modding operation, use the format \"$$$2$$$ $$$i$$$ $$$x$$$\". If $$$i$$$ or $$$x$$$ don't satisfy the limitations above, or you use more than $$$n+1$$$ operations, you'll get wrong answer verdict.", "sample_inputs": ["3\n1 2 3", "3\n7 6 3"], "sample_outputs": ["0", "2\n1 1 1\n2 2 4"], "notes": "NoteIn the first sample, the array is already increasing so we don't need any operations.In the second sample:In the first step: the array becomes $$$[8,6,3]$$$.In the second step: the array becomes $$$[0,2,3]$$$."}, "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 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"}, {"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"} {"nl": {"description": "Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.", "input_spec": "The first line of input will contain two integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009100)\u00a0\u2014 the instructions given to the robot. Each character of s is a digit from 0 to 3.", "output_spec": "Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.", "sample_inputs": ["5 6\n.....#\nS....#\n.#....\n.#....\n...E..\n333300012", "6 6\n......\n......\n..SE..\n......\n......\n......\n01232123212302123021", "5 3\n...\n.S.\n###\n.E.\n...\n3"], "sample_outputs": ["1", "14", "0"], "notes": "NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right."}, "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": "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"}, {"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"} {"nl": {"description": "Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.Igor's chessboard is a square of size n\u2009\u00d7\u2009n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x,\u2009y)\u00a0\u2014 the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx,\u2009dy); using this move, the piece moves from the field (x,\u2009y) to the field (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy). You can perform the move if the cell (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x,\u2009y) and (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: o \u2014 in this case the field (i,\u2009j) is occupied by a piece and the field may or may not be attacked by some other piece; x \u2014 in this case field (i,\u2009j) is attacked by some piece; . \u2014 in this case field (i,\u2009j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board.", "output_spec": "If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n\u2009-\u20091)\u2009\u00d7\u2009(2n\u2009-\u20091) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'.", "sample_inputs": ["5\noxxxx\nx...x\nx...x\nx...x\nxxxxo", "6\n.x.x..\nx.x.x.\n.xo..x\nx..ox.\n.x.x.x\n..x.x.", "3\no.x\noxx\no.x"], "sample_outputs": ["YES\n....x....\n....x....\n....x....\n....x....\nxxxxoxxxx\n....x....\n....x....\n....x....\n....x....", "YES\n...........\n...........\n...........\n....x.x....\n...x...x...\n.....o.....\n...x...x...\n....x.x....\n...........\n...........\n...........", "NO"], "notes": "NoteIn the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight."}, "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"}, {"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"}], "negative_code": [], "src_uid": "2fad1534434f042214dcd1f1dc75405a"} {"nl": {"description": "Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: \"a\", \"e\", \"i\", \"o\" and \"u\".Three phases from a certain poem are given. Determine whether it is haiku or not.", "input_spec": "The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.", "output_spec": "Print \"YES\" (without the quotes) if the poem is a haiku. Otherwise, print \"NO\" (also without the quotes).", "sample_inputs": ["on codeforces \nbeta round is running\n a rustling of keys", "how many gallons\nof edo s rain did you drink\n cuckoo"], "sample_outputs": ["YES", "NO"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1,\u2009a2,\u2009...,\u2009an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.", "input_spec": "The first line contains positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of USB flash drives. The second line contains positive integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the size of Sean's file. Each of the next n lines contains positive integer ai (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.", "output_spec": "Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.", "sample_inputs": ["3\n5\n2\n1\n3", "3\n6\n2\n3\n2", "2\n5\n5\n10"], "sample_outputs": ["2", "3", "1"], "notes": "NoteIn the first example Sean needs only two USB flash drives \u2014 the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive \u2014 the first or the second."}, "positive_code": [{"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"}, {"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()).view.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 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}"}], "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"} {"nl": {"description": "A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.", "output_spec": "For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.", "sample_inputs": ["2\n13\n7818005553535\n11\n31415926535"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535."}, "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 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 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"} {"nl": {"description": "Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition\u00a0\u2014 determine the number of dangerous turns on the track.", "input_spec": "The first line of the input contains an integer n (4\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of straight sections of the track. The following (n\u2009+\u20091)-th line contains pairs of integers (xi,\u2009yi) (\u2009-\u200910\u2009000\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u200910\u2009000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi,\u2009yi) and ends at the point (xi\u2009+\u20091,\u2009yi\u2009+\u20091). It is guaranteed that: the first straight section is directed to the north; the southernmost (and if there are several, then the most western of among them) point of the track is the first point; the last point coincides with the first one (i.e., the start position); any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); no pair of points (except for the first and last one) is the same; no two adjacent straight sections are directed in the same direction or in opposite directions. ", "output_spec": "Print a single integer\u00a0\u2014 the number of dangerous turns on the track.", "sample_inputs": ["6\n0 0\n0 1\n1 1\n1 2\n2 2\n2 0\n0 0", "16\n1 1\n1 5\n3 5\n3 7\n2 7\n2 9\n6 9\n6 7\n5 7\n5 3\n4 3\n4 4\n3 4\n3 2\n5 2\n5 1\n1 1"], "sample_outputs": ["1", "6"], "notes": "NoteThe first sample corresponds to the picture: The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1,\u20091). Thus, the answer is 1."}, "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"}, {"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"}], "negative_code": [], "src_uid": "0054f9e2549900487d78fae9aa4c2d65"} {"nl": {"description": "Given a set of integers (it can contain equal elements).You have to split it into two subsets $$$A$$$ and $$$B$$$ (both of them can contain equal elements or be empty). You have to maximize the value of $$$mex(A)+mex(B)$$$.Here $$$mex$$$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: $$$mex(\\{1,4,0,2,2,1\\})=3$$$ $$$mex(\\{3,3,2,1,3,0,0\\})=4$$$ $$$mex(\\varnothing)=0$$$ ($$$mex$$$ for empty set) The set is splitted into two subsets $$$A$$$ and $$$B$$$ if for any integer number $$$x$$$ the number of occurrences of $$$x$$$ into this set is equal to the sum of the number of occurrences of $$$x$$$ into $$$A$$$ and the number of occurrences of $$$x$$$ into $$$B$$$.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\leq t\\leq 100$$$) \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\\leq n\\leq 100$$$) \u2014 the size of the set. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\\dots a_n$$$ ($$$0\\leq a_i\\leq 100$$$) \u2014 the numbers in the set.", "output_spec": "For each test case, print the maximum value of $$$mex(A)+mex(B)$$$.", "sample_inputs": ["4\n6\n0 2 1 5 0 1\n3\n0 1 2\n4\n0 2 0 1\n6\n1 2 3 4 5 6"], "sample_outputs": ["5\n3\n4\n0"], "notes": "NoteIn the first test case, $$$A=\\left\\{0,1,2\\right\\},B=\\left\\{0,1,5\\right\\}$$$ is a possible choice.In the second test case, $$$A=\\left\\{0,1,2\\right\\},B=\\varnothing$$$ is a possible choice.In the third test case, $$$A=\\left\\{0,1,2\\right\\},B=\\left\\{0\\right\\}$$$ is a possible choice.In the fourth test case, $$$A=\\left\\{1,3,5\\right\\},B=\\left\\{2,4,6\\right\\}$$$ is a possible choice."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "e26b0b117593c159b7f01cfac66a71d1"} {"nl": {"description": "Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct: a1 is equivalent to b1, and a2 is equivalent to b2 a1 is equivalent to b2, and a2 is equivalent to b1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!", "input_spec": "The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200\u2009000 and consists of lowercase English letters. The strings have the same length.", "output_spec": "Print \"YES\" (without the quotes), if these two strings are equivalent, and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["aaba\nabaa", "aabb\nabab"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample you should split the first string into strings \"aa\" and \"ba\", the second one \u2014 into strings \"ab\" and \"aa\". \"aa\" is equivalent to \"aa\"; \"ab\" is equivalent to \"ba\" as \"ab\" = \"a\" + \"b\", \"ba\" = \"b\" + \"a\".In the second sample the first string can be splitted into strings \"aa\" and \"bb\", that are equivalent only to themselves. That's why string \"aabb\" is equivalent only to itself and to string \"bbaa\"."}, "positive_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) == gao(b)) println(\"YES\") else println(\"NO\")\n }\n\n private def gao(s: String): String = {\n val n = s.length\n if (n % 2 == 1) s\n else {\n val l = gao(s.take(n/2))\n val r = gao(s.drop(n/2))\n if (l < r) l + r else r + l\n }\n }\n\n}\n"}, {"source_code": "import scala.io.Source\n\nobject Solution extends App {\n\n def isEq(a: String, b: String, start1: Int, start2: Int, length: Int): Boolean = {\n if (length % 2 == 1) (0 until length).forall(i => 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"}, {"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 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"} {"nl": {"description": "Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?", "input_spec": "The first line of input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of balls in the jar. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20095000) \u2014 the number written on the ith ball. It is guaranteed that no two balls have the same number.", "output_spec": "Print a single real value \u2014 the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["2\n1 2", "3\n1 2 10"], "sample_outputs": ["0.0000000000", "0.0740740741"], "notes": "NoteIn the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.In the second case, each game could've had three outcomes \u2014 10\u2009-\u20092, 10\u2009-\u20091, or 2\u2009-\u20091. Jerry has a higher total if and only if Andrew won 2\u2009-\u20091 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability ."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "9d55b98c75e703a554051d3088a68e59"} {"nl": {"description": "It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.", "input_spec": "The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\\leq n\\leq 100$$$, $$$1\\leq t\\leq 10^5$$$)\u00a0\u2014 the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\\leq s_i,d_i\\leq 10^5$$$)\u00a0\u2014 the time when the first bus of this route arrives and the interval between two buses of this route.", "output_spec": "Print one number\u00a0\u2014 what bus route Serval will use. If there are several possible answers, you can print any of them.", "sample_inputs": ["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"], "sample_outputs": ["1", "3", "1"], "notes": "NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Given an array $$$a$$$ of length $$$n$$$, you can do at most $$$k$$$ operations of the following type on it: choose $$$2$$$ different elements in the array, add $$$1$$$ to the first, and subtract $$$1$$$ from the second. However, all the elements of $$$a$$$ have to remain non-negative after this operation. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \\le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 20$$$)\u00a0\u2013 the number of test cases you need to solve. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 100$$$, $$$1 \\le k \\le 10000$$$)\u00a0\u2014 the number of elements in the array and the maximum number of operations you can make. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{n}$$$ ($$$0 \\le a_i \\le 100$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case, print the lexicographically smallest array you can obtain after at most $$$k$$$ operations.", "sample_inputs": ["2\n3 1\n3 1 4\n2 10\n1 0"], "sample_outputs": ["2 1 5 \n0 1"], "notes": "NoteIn the second test case, we start by subtracting $$$1$$$ from the first element and adding $$$1$$$ to the second. Then, we can't get any lexicographically smaller arrays, because we can't make any of the elements negative."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "6854ad3597f9f41d475aacb774b823ed"} {"nl": {"description": "We just discovered a new data structure in our research group: a suffix three!It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.Let us tell you how it works. If a sentence ends with \"po\" the language is Filipino. If a sentence ends with \"desu\" or \"masu\" the language is Japanese. If a sentence ends with \"mnida\" the language is Korean. Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.Oh, did I say three suffixes? I meant four.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 30$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing a single string denoting the sentence. Spaces are represented as underscores (the symbol \"_\") for ease of reading. The sentence has at least $$$1$$$ and at most $$$1000$$$ characters, and consists only of lowercase English letters and underscores. The sentence has no leading or trailing underscores and no two consecutive underscores. It is guaranteed that the sentence ends with one of the four suffixes mentioned above.", "output_spec": "For each test case, print a single line containing either \"FILIPINO\", \"JAPANESE\", or \"KOREAN\" (all in uppercase, without quotes), depending on the detected language.", "sample_inputs": ["8\nkamusta_po\ngenki_desu\nohayou_gozaimasu\nannyeong_hashimnida\nhajime_no_ippo\nbensamu_no_sentou_houhou_ga_okama_kenpo\nang_halaman_doon_ay_sarisari_singkamasu\nsi_roy_mustang_ay_namamasu"], "sample_outputs": ["FILIPINO\nJAPANESE\nJAPANESE\nKOREAN\nFILIPINO\nFILIPINO\nJAPANESE\nJAPANESE"], "notes": "NoteThe first sentence ends with \"po\", so it is written in Filipino.The second and third sentences end with \"desu\" and \"masu\", so they are written in Japanese.The fourth sentence ends with \"mnida\", so it is written in Korean."}, "positive_code": [{"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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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"} {"nl": {"description": "Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \\dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \\le n \\le 30$$$; $$$n$$$ is even)\u00a0\u2014 the number of coins that Phoenix has. ", "output_spec": "For each test case, output one integer\u00a0\u2014 the minimum possible difference of weights between the two piles.", "sample_inputs": ["2\n2\n4"], "sample_outputs": ["2\n6"], "notes": "NoteIn the first test case, Phoenix has two coins with weights $$$2$$$ and $$$4$$$. No matter how he divides the coins, the difference will be $$$4-2=2$$$.In the second test case, Phoenix has four coins of weight $$$2$$$, $$$4$$$, $$$8$$$, and $$$16$$$. It is optimal for Phoenix to place coins with weights $$$2$$$ and $$$16$$$ in one pile, and coins with weights $$$4$$$ and $$$8$$$ in another pile. The difference is $$$(2+16)-(4+8)=6$$$."}, "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 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"}, {"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"} {"nl": {"description": "One important contest will take place on the most famous programming platform (Topforces) very soon!The authors have a pool of $$$n$$$ problems and should choose at most three of them into this contest. The prettiness of the $$$i$$$-th problem is $$$a_i$$$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $$$x, y, z$$$, then $$$x$$$ should be divisible by neither $$$y$$$, nor $$$z$$$, $$$y$$$ should be divisible by neither $$$x$$$, nor $$$z$$$ and $$$z$$$ should be divisible by neither $$$x$$$, nor $$$y$$$. If the prettinesses of chosen problems are $$$x$$$ and $$$y$$$ then neither $$$x$$$ should be divisible by $$$y$$$ nor $$$y$$$ should be divisible by $$$x$$$. Any contest composed from one problem is considered good.Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of queries. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of problems. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$2 \\le a_i \\le 2 \\cdot 10^5$$$), where $$$a_i$$$ is the prettiness of the $$$i$$$-th problem. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each query print one integer \u2014 the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query.", "sample_inputs": ["3\n4\n5 6 15 30\n4\n10 6 30 15\n3\n3 4 6"], "sample_outputs": ["30\n31\n10"], "notes": null}, "positive_code": [{"source_code": "import scala.util.Sorting\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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A = na(N)\n sort(A)\n\n // 1 + a > 1/2 + a \u304b\u3064 1 + a > 1/2 + 1/3 \u306a\u306e\u3067\n // \u5fc5\u305a\u4e00\u756a\u5927\u304d\u3044\u5024\u3092\u542b\u3080\n def two: Option[Int] = _two(_ => true, N - 1)\n\n def _two(condition: Int => Boolean, last: Int): Option[Int] = {\n for {\n _ <- Option(Unit)\n fstIx = A.lastIndexWhere(condition, last)\n if fstIx != -1\n fst = A(fstIx)\n sndIx = A.lastIndexWhere(a => condition(a) && fst % a != 0, fstIx - 1)\n if sndIx != -1\n snd = A(sndIx)\n _ <- {debug(s\"last:$last fst:$fst snd:$snd\"); Option(Unit)}\n } yield fst + snd\n }\n\n def _three(condition: Int => Boolean): Option[Int] = {\n for {\n _ <- Option(Unit)\n fstIx = A.lastIndexWhere(condition)\n if fstIx != -1\n fst = A(fstIx)\n twoAndThree <- _two(a => condition(a) && fst % a != 0, fstIx - 1) // \u3042\u3068\u306ftwo\u306e\u3068\u304d\u3068\u540c\u3058\u8981\u9818\u3067\n } yield twoAndThree + fst\n }\n\n // \u4e00\u756a\u5927\u304d\u3044\u5024\u304b\uff12\u756a\u3081\u3092\u542b\u3080\n // 1/2+1/3+1/5 > 1 + a + b \u304c\u3042\u308a\u3048\u308b\u306e\u3067\u3001\uff11\u756a\u76ee\u304c\u306a\u3044\u5834\u5408\u3082\u3042\u308b\n def withFst = _three(_ => true)\n def withoutFst = _three(_ != A.last)\n\n val ans = Seq(A.lastOption, two, withFst, withoutFst).flatten.max\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}"}], "negative_code": [{"source_code": "import scala.util.Sorting\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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A = na(N)\n sort(A)\n\n // \u5fc5\u305a\u4e00\u756a\u5927\u304d\u3044\u5024\u3092\u542b\u3080\n // 1 > 1/2 + 1/3 \u306a\u306e\u3067\n def two: Option[Int] = _two(_ => true, N - 1)\n\n def _two(condition: Int => Boolean, last: Int): Option[Int] = {\n for {\n _ <- Option(Unit)\n fstIx = A.lastIndexWhere(condition, last)\n if fstIx != -1\n fst = A(fstIx)\n sndIx = A.lastIndexWhere(a => condition(a) && fst % a != 0, fstIx)\n if sndIx != -1\n snd = A(sndIx)\n } yield fst + snd\n }\n\n def _three(condition: Int => Boolean): Option[Int] = {\n for {\n _ <- Option(Unit)\n fstIx = A.lastIndexWhere(condition)\n if fstIx != -1\n fst = A(fstIx)\n twoAndThree <- _two(a => condition(a) && fst % a != 0, fstIx) // \u3042\u3068\u306ftwo\u306e\u3068\u304d\u3068\u540c\u3058\u8981\u7528\u3067\n } yield twoAndThree + fst\n }\n\n // \u4e00\u756a\u5927\u304d\u3044\u5024\u304b\uff12\u756a\u3081\u3092\u542b\u3080\n // 1/2+1/3+1/4 > 1 \u306a\u306e\u3067\uff11\u756a\u76ee\u304c\u306a\u3044\u5834\u5408\u3082\u3042\u308b\u3048\u308b\n def three: Option[Int] = {\n def withFst = _three(_ => true)\n def withoutFst = _three(_ != A.last)\n\n withFst orElse withoutFst\n }\n\n val ans = Seq(A.lastOption, two, three).flatten.max\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}"}, {"source_code": "import scala.util.Sorting\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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val A = na(N)\n sort(A)\n\n // \u5fc5\u305a\u4e00\u756a\u5927\u304d\u3044\u5024\u3092\u542b\u3080\n // 1 > 1/2 + 1/3 \u306a\u306e\u3067\n def two: Option[Int] = _two(_ => true, N - 1)\n\n def _two(condition: Int => Boolean, last: Int): Option[Int] = {\n for {\n _ <- Option(Unit)\n fstIx = A.lastIndexWhere(condition, last)\n if fstIx != -1\n fst = A(fstIx)\n sndIx = A.lastIndexWhere(a => condition(a) && fst % a != 0, fstIx)\n if sndIx != -1\n snd = A(sndIx)\n } yield fst + snd\n }\n\n def _three(last: Int): Option[Int] = {\n for {\n _ <- Option(Unit)\n fstIx = A.lastIndexWhere(_ => true, last)\n if fstIx != -1\n fst = A(fstIx)\n _ <- {debug(s\"_three($last) fst:$fst\"); Option(Unit)}\n twoAndThree <- _two(fst % _ != 0, fstIx) // \u3042\u3068\u306ftwo\u306e\u3068\u304d\u3068\u540c\u3058\u8981\u7528\u3067\n } yield twoAndThree + fst\n }\n\n // \u4e00\u756a\u5927\u304d\u3044\u5024\u304b\uff12\u756a\u3081\u3092\u542b\u3080\n // 1/2+1/3+1/4 > 1 \u306a\u306e\u3067\uff11\u756a\u76ee\u304c\u306a\u3044\u5834\u5408\u3082\u3042\u308b\u3048\u308b\n def three: Option[Int] = {\n def withFst = _three(N - 1)\n def withoutFst = _three(N - 2)\n\n withFst orElse withoutFst\n }\n\n val ans = Seq(A.lastOption, two, three).flatten.max\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}"}], "src_uid": "da15eae7831e3eb5e1f2e2e4c5222fbf"} {"nl": {"description": "Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.", "input_spec": "The first line will contain two space separated integers n, x (1\u2009\u2264\u2009n,\u2009x\u2009\u2264\u2009105). The next line will contain n space separated integers: c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009105).", "output_spec": "Output a single integer representing the answer to the problem.", "sample_inputs": ["2 3\n4 1", "4 2\n5 1 2 1", "3 3\n1 1 1"], "sample_outputs": ["11", "10", "6"], "notes": "NoteLook at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2\u2009\u00d7\u20091\u2009=\u20092 hours. Hence you will need to spend 12\u2009+\u20092\u2009=\u200914 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3\u2009\u00d7\u20091\u2009=\u20093 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2\u2009\u00d7\u20094\u2009=\u20098 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours."}, "positive_code": [{"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"}, {"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": "\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}"}, {"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"}], "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"} {"nl": {"description": "The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $$$5 = 101_2$$$ and $$$14 = 1110_2$$$ equals to $$$3$$$, since $$$0101$$$ and $$$1110$$$ differ in $$$3$$$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $$$0$$$ to $$$n$$$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.", "input_spec": "The input consists of multiple test cases. The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10\\,000$$$)\u00a0\u2014 the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^{18})$$$.", "output_spec": "Output $$$t$$$ lines. For each test case, you should output a single line with one integer\u00a0\u2014 the unfairness of the contest if the rating sequence equals to $$$0$$$, $$$1$$$, ..., $$$n - 1$$$, $$$n$$$.", "sample_inputs": ["5\n5\n7\n11\n1\n2000000000000"], "sample_outputs": ["8\n11\n19\n1\n3999999999987"], "notes": "NoteFor $$$n = 5$$$ we calculate unfairness of the following sequence (numbers from $$$0$$$ to $$$5$$$ written in binary with extra leading zeroes, so they all have the same length): $$$000$$$ $$$001$$$ $$$010$$$ $$$011$$$ $$$100$$$ $$$101$$$ The differences are equal to $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$ respectively, so unfairness is equal to $$$1 + 2 + 1 + 3 + 1 = 8$$$."}, "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().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"}, {"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": "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"}], "negative_code": [], "src_uid": "2a4f4c91522d83bc8f1ca2f086d24c3c"} {"nl": {"description": "Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.It's known that they have worked together on the same file for $$$n + m$$$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $$$k$$$ lines written in the file.Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.Monocarp worked in total for $$$n$$$ minutes and performed the sequence of actions $$$[a_1, a_2, \\dots, a_n]$$$. If $$$a_i = 0$$$, then he adds a new line to the end of the file. If $$$a_i > 0$$$, then he changes the line with the number $$$a_i$$$. Monocarp performed actions strictly in this order: $$$a_1$$$, then $$$a_2$$$, ..., $$$a_n$$$.Polycarp worked in total for $$$m$$$ minutes and performed the sequence of actions $$$[b_1, b_2, \\dots, b_m]$$$. If $$$b_j = 0$$$, then he adds a new line to the end of the file. If $$$b_j > 0$$$, then he changes the line with the number $$$b_j$$$. Polycarp performed actions strictly in this order: $$$b_1$$$, then $$$b_2$$$, ..., $$$b_m$$$.Restore their common sequence of actions of length $$$n + m$$$ such that all actions would be correct \u2014 there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence $$$[a_1, a_2, \\dots, a_n]$$$ and Polycarp's \u2014 subsequence $$$[b_1, b_2, \\dots, b_m]$$$. They can replace each other at the computer any number of times.Let's look at an example. Suppose $$$k = 3$$$. Monocarp first changed the line with the number $$$2$$$ and then added a new line (thus, $$$n = 2, \\: a = [2, 0]$$$). Polycarp first added a new line and then changed the line with the number $$$5$$$ (thus, $$$m = 2, \\: b = [0, 5]$$$).Since the initial length of the file was $$$3$$$, in order for Polycarp to change line number $$$5$$$ two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be $$$[0, 2, 0, 5]$$$ and $$$[2, 0, 0, 5]$$$. Changes $$$[0, 0, 5, 2]$$$ (wrong order of actions) and $$$[0, 5, 2, 0]$$$ (line $$$5$$$ cannot be edited yet) are not correct.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$). Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains three integers $$$k$$$, $$$n$$$, $$$m$$$ ($$$0 \\le k \\le 100$$$, $$$1 \\le n, m \\le 100$$$)\u00a0\u2014 the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 300$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \\dots, b_m$$$ ($$$0 \\le b_j \\le 300$$$).", "output_spec": "For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length $$$n + m$$$ or -1 if such sequence doesn't exist.", "sample_inputs": ["5\n\n3 2 2\n2 0\n0 5\n\n4 3 2\n2 0 5\n0 6\n\n0 2 2\n1 0\n2 3\n\n5 4 4\n6 0 8 0\n0 7 0 9\n\n5 4 1\n8 7 8 0\n0"], "sample_outputs": ["2 0 0 5 \n0 2 0 6 5 \n-1\n0 6 0 7 0 8 0 9\n-1"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "6628bd89b4d4fdfa90d2357f7cc1b795"} {"nl": {"description": "Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $$$s$$$ and a number $$$k$$$ ($$$0 \\le k < |s|$$$).At the beginning of the game, players are given a substring of $$$s$$$ with left border $$$l$$$ and right border $$$r$$$, both equal to $$$k$$$ (i.e. initially $$$l=r=k$$$). Then players start to make moves one by one, according to the following rules: A player chooses $$$l^{\\prime}$$$ and $$$r^{\\prime}$$$ so that $$$l^{\\prime} \\le l$$$, $$$r^{\\prime} \\ge r$$$ and $$$s[l^{\\prime}, r^{\\prime}]$$$ is lexicographically less than $$$s[l, r]$$$. Then the player changes $$$l$$$ and $$$r$$$ in this way: $$$l := l^{\\prime}$$$, $$$r := r^{\\prime}$$$. Ann moves first. The player, that can't make a move loses.Recall that a substring $$$s[l, r]$$$ ($$$l \\le r$$$) of a string $$$s$$$ is a continuous segment of letters from s that starts at position $$$l$$$ and ends at position $$$r$$$. For example, \"ehn\" is a substring ($$$s[3, 5]$$$) of \"aaaehnsvz\" and \"ahz\" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $$$s$$$ and $$$k$$$.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $$$s$$$ and determines the winner for all possible $$$k$$$.", "input_spec": "The first line of the input contains a single string $$$s$$$ ($$$1 \\leq |s| \\leq 5 \\cdot 10^5$$$) consisting of lowercase English letters.", "output_spec": "Print $$$|s|$$$ lines. In the line $$$i$$$ write the name of the winner (print Mike or Ann) in the game with string $$$s$$$ and $$$k = i$$$, if both play optimally", "sample_inputs": ["abba", "cba"], "sample_outputs": ["Mike\nAnn\nAnn\nMike", "Mike\nMike\nMike"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val s = ns()\n val exists = Array.ofDim[Boolean](26)\n REP(s.length) { i =>\n // s(i)\u3088\u308a\u30a2\u30eb\u30d5\u30a1\u30d9\u30c3\u30c8\u9806\u306b\u5c0f\u3055\u3044\u6587\u5b57\u304c\u3067\u3066\u304d\u305f\u304b\n var ok = false\n REP(s(i)-'a') { c =>\n ok ||= exists(c)\n }\n exists(s(i)-'a') = true\n if (ok) {\n out.println(\"Ann\")\n } else {\n out.println(\"Mike\")\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "1e107d9fb8bead4ad942b857685304c4"} {"nl": {"description": "Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$.Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop.Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$.Your task is to get the number of games Maxim will buy.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$) \u2014 the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$1 \\le c_i \\le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \\dots, a_m$$$ ($$$1 \\le a_j \\le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.", "output_spec": "Print a single integer \u2014 the number of games Maxim will buy.", "sample_inputs": ["5 4\n2 4 5 2 4\n5 3 4 6", "5 2\n20 40 50 20 40\n19 20", "6 4\n4 8 15 16 23 42\n1000 1000 1000 1000"], "sample_outputs": ["3", "0", "4"], "notes": "NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet."}, "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 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}"}], "negative_code": [], "src_uid": "c3f080681e3da5e1290ef935ff91f364"} {"nl": {"description": "Suppose you have an integer $$$v$$$. In one operation, you can: either set $$$v = (v + 1) \\bmod 32768$$$ or set $$$v = (2 \\cdot v) \\bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$?", "input_spec": "The first line contains the single integer $$$n$$$ ($$$1 \\le n \\le 32768$$$)\u00a0\u2014 the number of integers. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i < 32768$$$).", "output_spec": "Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the minimum number of operations required to make $$$a_i$$$ equal to $$$0$$$.", "sample_inputs": ["4\n19 32764 10240 49"], "sample_outputs": ["14 4 4 15"], "notes": "NoteLet's consider each $$$a_i$$$: $$$a_1 = 19$$$. You can, firstly, increase it by one to get $$$20$$$ and then multiply it by two $$$13$$$ times. You'll get $$$0$$$ in $$$1 + 13 = 14$$$ steps. $$$a_2 = 32764$$$. You can increase it by one $$$4$$$ times: $$$32764 \\rightarrow 32765 \\rightarrow 32766 \\rightarrow 32767 \\rightarrow 0$$$. $$$a_3 = 10240$$$. You can multiply it by two $$$4$$$ times: $$$10240 \\rightarrow 20480 \\rightarrow 8192 \\rightarrow 16384 \\rightarrow 0$$$. $$$a_4 = 49$$$. You can multiply it by two $$$15$$$ times. "}, "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\r\n\r\n def powtwo(x: Int) = ((x - 1) & x) == 0\r\n\r\n def calc(i: Int, count: Int = 0): Int = {\r\n if (count == 15) 15\r\n else if (i % 2 == 1) count\r\n else calc(i / 2, count + 1)\r\n }\r\n\r\n import Math._\r\n def add(i: Int, d: Int, count: Int = 1): Int = {\r\n if (i == 32768) min(d, count)\r\n else if (count == 15) d\r\n else if (i % 2 == 0) {\r\n add(i + 1, min(d, count + 15 - calc(i)), count + 1)\r\n }\r\n else add(i + 1, d, count + 1)\r\n }\r\n\r\n // 2^15\r\n def op(i: Int): Int = {\r\n val pt = 15 - calc(i)\r\n add(i + 1, pt)\r\n }\r\n\r\n def solve(n: Int, a: Array[Int]) = {\r\n a.foreach(x => print(s\"${op(x)} \"))\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n\r\n val n = readLine.toInt;\r\n val a = rsi\r\n solve(n, a)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "5c844c0dc0eb718aea7b2446e90ce250"} {"nl": {"description": "Alice and Bob play a game. There is a paper strip which is divided into n\u2009+\u20091 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i\u2009-\u20091, i\u2009-\u20092 or i\u2009-\u2009k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i\u2009<\u2009k. The player who can't make a move loses the game.Who wins if both participants play optimally?Alice and Bob would like to play several games, so you should determine the winner in each game.", "input_spec": "The first line contains the single integer T (1\u2009\u2264\u2009T\u2009\u2264\u2009100) \u2014 the number of games. Next T lines contain one game per line. All games are independent. Each of the next T lines contains two integers n and k (0\u2009\u2264\u2009n\u2009\u2264\u2009109, 3\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the length of the strip and the constant denoting the third move, respectively.", "output_spec": "For each game, print Alice if Alice wins this game and Bob otherwise.", "sample_inputs": ["4\n0 3\n3 3\n3 4\n4 4"], "sample_outputs": ["Bob\nAlice\nBob\nAlice"], "notes": null}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, k = ni()\n val win = if (n == 0) {\n false\n } else if (k % 3 != 0) {\n n % 3 != 0\n } else {\n val r = n % (k + 1)\n r == k || r % 3 != 0\n }\n\n if (win) out.println(\"Alice\")\n else out.println(\"Bob\")\n }\n }\n}"}], "negative_code": [], "src_uid": "8e0b8f3cbee8e770245de72a8fb62e05"} {"nl": {"description": "Lolek and Bolek are about to travel abroad by plane. The local airport has a special \"Choose Your Plane\" offer. The offer's conditions are as follows: it is up to a passenger to choose a plane to fly on; if the chosen plane has x (x\u2009>\u20090) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000) \u2014 the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.", "output_spec": "Print two integers \u2014 the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.", "sample_inputs": ["4 3\n2 1 1", "4 3\n2 2 2"], "sample_outputs": ["5 5", "7 6"], "notes": "NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person \u2014 to the 2-nd plane, the 3-rd person \u2014 to the 3-rd plane, the 4-th person \u2014 to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person \u2014 to the 1-st plane, the 3-rd person \u2014 to the 2-nd plane, the 4-th person \u2014 to the 2-nd plane."}, "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": "import java.io._\nimport java.util.Locale\nimport scala.annotation.tailrec\nimport scala.collection.mutable\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, _) = readInts\n val a = readInts\n val pq1 = mutable.PriorityQueue(a: _*)\n val pq2 = mutable.PriorityQueue(a: _*)(Ordering.Int.reverse)\n val pq = Array(pq1, pq2)\n def ans = pq.map { q =>\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"}, {"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"} {"nl": {"description": "Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai|\u2009\u2264\u2009104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.", "output_spec": "In the single line print the answer to the problem \u2014 the maximum total income that we can obtain after exactly k changes.", "sample_inputs": ["3 2\n-1 -1 1", "3 1\n-1 -1 1"], "sample_outputs": ["3", "1"], "notes": "NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1."}, "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)\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"}, {"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 //\u5148\u982dk\u500b\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"} {"nl": {"description": "Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number ai\u00a0\u2014 the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during ai days for the exam number i. He can mix the order of preparation for exams in any way.Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time. ", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the number of days in the exam period and the number of subjects. The second line contains n integers d1,\u2009d2,\u2009...,\u2009dn (0\u2009\u2264\u2009di\u2009\u2264\u2009m), where di is the number of subject, the exam of which can be passed on the day number i. If di equals 0, it is not allowed to pass any exams on the day number i. The third line contains m positive integers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u2009105), where ai is the number of days that are needed to prepare before passing the exam on the subject i.", "output_spec": "Print one integer\u00a0\u2014 the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.", "sample_inputs": ["7 2\n0 1 0 2 1 0 2\n2 1", "10 3\n0 0 1 2 3 0 2 0 1 2\n1 1 4", "5 1\n1 1 1 1 1\n5"], "sample_outputs": ["5", "9", "-1"], "notes": "NoteIn the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it. "}, "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 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"}, {"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"} {"nl": {"description": "Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\\sum\\limits_{i=1}^{n} \\sum\\limits_{j=i+1}^{n} \\lvert a_i-a_j\\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 10\\,000$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\\leq n\\leq 2\\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0\\leq a_i\\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.", "sample_inputs": ["3\n3\n1 2 3\n4\n0 1 1 0\n10\n8 3 6 11 5 2 1 7 10 4"], "sample_outputs": ["0\n4\n21"], "notes": "NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track."}, "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"}, {"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"}], "negative_code": [], "src_uid": "935bceb69117d06eb75121c805bff69c"} {"nl": {"description": "The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string \"abba\" is a palindrome and string \"abc\" isn't. Determine which player will win, provided that both sides play optimally well \u2014 the one who moves first or the one who moves second.", "input_spec": "The input contains a single line, containing string s (1\u2009\u2264\u2009|s|\u2009\u2009\u2264\u2009\u2009103). String s consists of lowercase English letters.", "output_spec": "In a single line print word \"First\" if the first player wins (provided that both players play optimally well). Otherwise, print word \"Second\". Print the words without the quotes.", "sample_inputs": ["aba", "abca"], "sample_outputs": ["First", "Second"], "notes": null}, "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 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": "\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": "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}"}, {"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"} {"nl": {"description": "Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1,\u2009b2,\u2009...,\u2009bn. The third line contains c1,\u2009c2,\u2009...,\u2009cn. The following limits are fulfilled: 0\u2009\u2264\u2009ai,\u2009bi,\u2009ci\u2009\u2264\u2009105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number \u0441i in the third line shows the joy that hare number i radiates if both his adjacent hares are full.", "output_spec": "In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.", "sample_inputs": ["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"], "sample_outputs": ["13", "44", "4"], "notes": null}, "positive_code": [{"source_code": "object D 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\n val as = readInts(n)\n val bs = readInts(n)\n val cs = readInts(n)\n\n var happy = (as(0), if (n > 1) bs(0) else 0) // (feed current before next, feed current after next)\n\n for (i <- 1 until n - 1) happy = happy match {\n case (before, after) => (\n (after + as(i)) max (before + bs(i)),\n (after + bs(i)) max (before + cs(i)))\n }\n \n if (n > 1) happy = (happy._1 + bs.last, happy._2 + as.last)\n\n println(happy._1 max happy._2)\n}\n"}], "negative_code": [{"source_code": "object D 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\n val as = readInts(n)\n val bs = readInts(n)\n val cs = readInts(n)\n\n var happy = (as(0), bs(0)) // (feed current before next, feed current after next)\n\n for (i <- 1 until n - 1) happy = happy match {\n case (before, after) => (\n (after + as(i)) max (before + bs(i)),\n (after + bs(i)) max (before + cs(i)))\n }\n \n if (n > 1) happy = (happy._1 + bs.last, happy._2 + as.last)\n\n println(happy._1 max happy._2)\n}\n"}, {"source_code": "object D 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\n val as = readInts(n)\n val bs = readInts(n)\n val cs = readInts(n)\n\n var happy = (as(0), bs(0)) // (feed current before next, feed current after next)\n\n for (i <- 1 until n) happy = happy match {\n case (before, after) => (\n (after + as(i)) max (before + bs(i)),\n (after + bs(i)) max (before + cs(i)))\n }\n\n println(happy._1 max happy._2)\n}\n"}, {"source_code": "object D 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\n val as = readInts(n)\n val bs = readInts(n)\n val cs = readInts(n)\n\n var happy = (as(0), bs(0)) // (feed current before next, feed current after next)\n\n for (i <- 1 until n - 1) happy = happy match {\n case (before, after) => (\n (after + as(i)) max (before + bs(i)),\n (after + bs(i)) max (before + cs(i)))\n }\n \n happy = (happy._1 + bs.last, happy._2 + as.last)\n\n println(happy._1 max happy._2)\n}\n"}], "src_uid": "99cf10673cb275ad3b90bcd3757ecd47"} {"nl": {"description": "There is an infinite 2-dimensional grid. The robot stands in cell $$$(0, 0)$$$ and wants to reach cell $$$(x, y)$$$. Here is a list of possible commands the robot can execute: move north from cell $$$(i, j)$$$ to $$$(i, j + 1)$$$; move east from cell $$$(i, j)$$$ to $$$(i + 1, j)$$$; move south from cell $$$(i, j)$$$ to $$$(i, j - 1)$$$; move west from cell $$$(i, j)$$$ to $$$(i - 1, j)$$$; stay in cell $$$(i, j)$$$. The robot wants to reach cell $$$(x, y)$$$ in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach $$$(x, y)$$$ from $$$(0, 0)$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of testcases. Each of the next $$$t$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$0 \\le x, y \\le 10^4$$$)\u00a0\u2014 the destination coordinates of the robot.", "output_spec": "For each testcase print a single integer\u00a0\u2014 the minimum number of commands required for the robot to reach $$$(x, y)$$$ from $$$(0, 0)$$$ if no command is allowed to be executed two or more times in a row.", "sample_inputs": ["5\n5 5\n3 4\n7 1\n0 0\n2 0"], "sample_outputs": ["10\n7\n13\n0\n3"], "notes": "NoteThe explanations for the example test:We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.In the first test case, the robot can use the following sequence: NENENENENE.In the second test case, the robot can use the following sequence: NENENEN.In the third test case, the robot can use the following sequence: ESENENE0ENESE.In the fourth test case, the robot doesn't need to go anywhere at all.In the fifth test case, the robot can use the following sequence: E0E."}, "positive_code": [{"source_code": "//package bScalaAdvanced.exercises.codeForces.edu98\n\n\nimport scala.io.StdIn._\n\n\nobject taskA extends App {\n val sets = readInt\n var res = new Array[Int](sets)\n\n\n var loc = new Array[(Int, Int)](sets)\n (0 until sets).foreach(x => {\n val single = readLine.split(\" \").map(_.toInt)\n loc(x) = (single(0), single(1))\n })\n\n (0 until sets).foreach(x => {\n if(Math.abs(loc(x)._1 - loc(x)._2) > 1) {\n if(loc(x)._1 > loc(x)._2){\n res(x) = loc(x)._2*2+1 + ((loc(x)._1 - loc(x)._2)-1)*2\n }else{\n res(x) = loc(x)._1*2+1 + ((loc(x)._2 - loc(x)._1)-1)*2\n }\n }else res(x) = loc(x)._1 + loc(x)._2\n })\n\n (0 until sets).foreach(x => {\n println(res(x))\n\n })\n\n\n}\n"}], "negative_code": [], "src_uid": "8864c6a04fed970fcbc04e220df9d88d"} {"nl": {"description": "You are given an integer $$$n$$$. You have to apply $$$m$$$ operations to it.In a single operation, you must replace every digit $$$d$$$ of the number with the decimal representation of integer $$$d + 1$$$. For example, $$$1912$$$ becomes $$$21023$$$ after applying the operation once.You have to find the length of $$$n$$$ after applying $$$m$$$ operations. Since the answer can be very large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains two integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$m$$$ ($$$1 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the initial number and the number of operations. ", "output_spec": "For each test case output the length of the resulting number modulo $$$10^9+7$$$.", "sample_inputs": ["5\n1912 1\n5 6\n999 1\n88 2\n12 100"], "sample_outputs": ["5\n2\n6\n4\n2115"], "notes": "NoteFor the first test, $$$1912$$$ becomes $$$21023$$$ after $$$1$$$ operation which is of length $$$5$$$.For the second test, $$$5$$$ becomes $$$21$$$ after $$$6$$$ operations which is of length $$$2$$$.For the third test, $$$999$$$ becomes $$$101010$$$ after $$$1$$$ operation which is of length $$$6$$$.For the fourth test, $$$88$$$ becomes $$$1010$$$ after $$$2$$$ operations which is of length $$$4$$$."}, "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 = 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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: \"Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position\".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.", "input_spec": "The first line contains two non-negative numbers n and m (0\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105, 0\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105) \u2014 the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6\u00b7105. Each line consists only of letters 'a', 'b', 'c'.", "output_spec": "For each query print on a single line \"YES\" (without the quotes), if the memory of the mechanism contains the required string, otherwise print \"NO\" (without the quotes).", "sample_inputs": ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"], "sample_outputs": ["YES\nNO\nNO"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "Lunar New Year is approaching, and Bob is struggling with his homework \u2013 a number division problem.There are $$$n$$$ positive integers $$$a_1, a_2, \\ldots, a_n$$$ on Bob's homework paper, where $$$n$$$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $$$2$$$ numbers. Suppose the numbers are divided into $$$m$$$ groups, and the sum of the numbers in the $$$j$$$-th group is $$$s_j$$$. Bob's aim is to minimize the sum of the square of $$$s_j$$$, that is $$$$$$\\sum_{j = 1}^{m} s_j^2.$$$$$$Bob is puzzled by this hard problem. Could you please help him solve it?", "input_spec": "The first line contains an even integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$), denoting that there are $$$n$$$ integers on Bob's homework paper. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^4$$$), describing the numbers you need to deal with.", "output_spec": "A single line containing one integer, denoting the minimum of the sum of the square of $$$s_j$$$, which is $$$$$$\\sum_{i = j}^{m} s_j^2,$$$$$$ where $$$m$$$ is the number of groups.", "sample_inputs": ["4\n8 5 2 3", "6\n1 1 1 2 2 2"], "sample_outputs": ["164", "27"], "notes": "NoteIn the first sample, one of the optimal solutions is to divide those $$$4$$$ numbers into $$$2$$$ groups $$$\\{2, 8\\}, \\{5, 3\\}$$$. Thus the answer is $$$(2 + 8)^2 + (5 + 3)^2 = 164$$$.In the second sample, one of the optimal solutions is to divide those $$$6$$$ numbers into $$$3$$$ groups $$$\\{1, 2\\}, \\{1, 2\\}, \\{1, 2\\}$$$. Thus the answer is $$$(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$$$."}, "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\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"}, {"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"} {"nl": {"description": "One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series \"Tufurama\". He was pretty surprised when he got results only for season 7 episode 3 with his search query of \"Watch Tufurama season 3 episode 7 online full hd free\". This got Polycarp confused \u2014 what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x\u2009<\u2009y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!", "input_spec": "The first line contains one integer n (1\u2009\u2009\u2264\u2009n\u2009\u2009\u2264\u2009\u20092\u00b7105) \u2014 the number of seasons. The second line contains n integers separated by space a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 number of episodes in each season.", "output_spec": "Print one integer \u2014 the number of pairs x and y (x\u2009<\u2009y) such that there exist both season x episode y and season y episode x.", "sample_inputs": ["5\n1 2 3 4 5", "3\n8 12 7", "3\n3 2 1"], "sample_outputs": ["0", "3", "2"], "notes": "NotePossible pairs in the second example: x\u2009=\u20091, y\u2009=\u20092 (season 1 episode 2 season 2 episode 1); x\u2009=\u20092, y\u2009=\u20093 (season 2 episode 3 season 3 episode 2); x\u2009=\u20091, y\u2009=\u20093 (season 1 episode 3 season 3 episode 1). In the third example: x\u2009=\u20091, y\u2009=\u20092 (season 1 episode 2 season 2 episode 1); x\u2009=\u20091, y\u2009=\u20093 (season 1 episode 3 season 3 episode 1). "}, "positive_code": [{"source_code": "object Solution {\n import scala.collection.mutable.ListBuffer\n \n def main(args: Array[String]) {\n val r = new Reader\n val n = r.read[Int]\n val as = r.read[Array[Int]](n).map(x => x.min(n))\n \n val ss = (0 until as.length).foldLeft(Array.fill(n)(ListBuffer[Int]())) {\n case (arr, i) => { arr(as(i) - 1) += i + 1; arr }\n }\n \n val bs = BIT.fill(n)(1)\n \n val res = (0 until as.length).foldLeft(0L) {\n case (res, i) => {\n val res1 = res + bs(as(i)).toLong\n ss(i).map(bs.update(_, -1))\n if (i < as(i)) res1 - 1L else res1\n }\n }\n \n println(res / 2)\n }\n}\n\nfinal class BIT(arr: Array[Int]) {\n private val _tree = Array.fill(arr.length + 1)(0)\n \n for (i <- 1 until _tree.length) {\n _tree(i) += arr(i - 1)\n if (i + range(i) < _tree.length) _tree(i + range(i)) += _tree(i)\n }\n \n def apply(i: Int): Int = { \n @annotation.tailrec\n def go(acc: Int, i: Int): Int = if (i <= 0) acc else go(acc + _tree(i), i - range(i))\n \n go(0, i)\n }\n\n def apply(i: Int, j: Int): Int = apply(j) - apply(i - 1)\n \n @annotation.tailrec\n def update(i: Int, x: Int): Unit = {\n if (i < _tree.length) {\n _tree(i) += x\n update(i + range(i), x)\n }\n }\n \n private def range(n: Int) = n & (~n + 1)\n}\n\nobject BIT {\n def fill(n: Int)(x: Int) = new BIT(Array.fill(n)(x))\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": [{"source_code": "object Solution {\n import scala.collection.mutable.ListBuffer\n \n def main(args: Array[String]) {\n val r = new Reader\n val n = r.read[Int]\n val as = r.read[Array[Int]](n).map(x => x.min(n))\n \n val ss = (0 until as.length).foldLeft(Array.fill(n)(ListBuffer[Int]())) {\n case (arr, i) => { arr(as(i) - 1) += i + 1; arr }\n }\n \n val bs = BIT.fill(n)(1)\n \n val res = (0 until as.length).foldLeft(0) {\n case (res, i) => {\n val res1 = res + bs(as(i))\n ss(i).map(bs.update(_, -1))\n if (i < as(i)) res1 - 1 else res1\n }\n }\n \n println(res / 2)\n }\n}\n\nfinal class BIT(arr: Array[Int]) {\n private val _tree = Array.fill(arr.length + 1)(0)\n \n for (i <- 1 until _tree.length) {\n _tree(i) += arr(i - 1)\n if (i + range(i) < _tree.length) _tree(i + range(i)) += _tree(i)\n }\n \n def apply(i: Int): Int = { \n @annotation.tailrec\n def go(acc: Int, i: Int): Int = if (i <= 0) acc else go(acc + _tree(i), i - range(i))\n \n go(0, i)\n }\n\n def apply(i: Int, j: Int): Int = apply(j) - apply(i - 1)\n \n @annotation.tailrec\n def update(i: Int, x: Int): Unit = {\n if (i < _tree.length) {\n _tree(i) += x\n update(i + range(i), x)\n }\n }\n \n private def range(n: Int) = n & (~n + 1)\n}\n\nobject BIT {\n def fill(n: Int)(x: Int) = new BIT(Array.fill(n)(x))\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 import scala.collection.mutable.ListBuffer\n \n def main(args: Array[String]) {\n val r = new Reader\n val n = r.read[Int]\n val as = r.read[Array[Int]](n).map(x => x.min(n))\n \n val ss = (0 until as.length).foldLeft(Array.fill(n)(ListBuffer[Int]())) {\n case (arr, i) => { arr(as(i) - 1) += i + 1; arr }\n }\n \n val bs = BIT.fill(n)(1)\n \n val res = (0 until as.length).foldLeft(0) {\n case (res, i) => {\n val res1 = res + bs(as(i))\n ss(i).map(bs.update(_, -1))\n if (i <= as(i)) res1 - 1 else res1\n }\n }\n \n println(res / 2)\n }\n}\n\nfinal class BIT(arr: Array[Int]) {\n private val _tree = Array.fill(arr.length + 1)(0)\n \n for (i <- 1 until _tree.length) {\n _tree(i) = if (i % 2 == 0) _tree(i - 2) + arr(i - 2) + arr(i - 1) else arr(i - 1)\n }\n \n def apply(i: Int): Int = { \n @annotation.tailrec\n def go(acc: Int, i: Int): Int = if (i <= 0) acc else go(acc + _tree(i), i - range(i))\n \n go(0, i)\n }\n\n def apply(i: Int, j: Int): Int = apply(j) - apply(i - 1)\n \n @annotation.tailrec\n def update(i: Int, x: Int): Unit = {\n if (i < _tree.length) {\n _tree(i) += x\n update(i + range(i), x)\n }\n }\n \n def toList = _tree.toList\n\n private def range(n: Int) = n & (~n + 1)\n}\n\nobject BIT {\n def fill(n: Int)(x: Int) = new BIT(Array.fill(n)(x))\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}"}], "src_uid": "5de434a33c91af800bbe75dc9ef54ecf"} {"nl": {"description": "A plane is flying at a constant height of $$$h$$$ meters above the ground surface. Let's consider that it is flying from the point $$$(-10^9, h)$$$ to the point $$$(10^9, h)$$$ parallel with $$$Ox$$$ axis.A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to $$$Ox$$$ axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.There are ascending air flows on certain segments, each such segment is characterized by two numbers $$$x_1$$$ and $$$x_2$$$ ($$$x_1 < x_2$$$) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along $$$Ox$$$ axis, covering one unit of distance every second. If the glider jumps out at $$$1$$$, he will stop at $$$10$$$. Otherwise, if he jumps out at $$$2$$$, he will stop at $$$12$$$. Determine the maximum distance along $$$Ox$$$ axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is $$$0$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$h$$$ $$$(1 \\le n \\le 2\\cdot10^{5}, 1 \\le h \\le 10^{9})$$$\u00a0\u2014 the number of ascending air flow segments and the altitude at which the plane is flying, respectively. Each of the next $$$n$$$ lines contains two integers $$$x_{i1}$$$ and $$$x_{i2}$$$ $$$(1 \\le x_{i1} < x_{i2} \\le 10^{9})$$$\u00a0\u2014 the endpoints of the $$$i$$$-th ascending air flow segment. No two segments intersect, and they are given in ascending order.", "output_spec": "Print one integer\u00a0\u2014 the maximum distance along $$$Ox$$$ axis that the glider can fly from the point where he jumps off the plane to the point where he lands if he can start his flight at any integer coordinate.", "sample_inputs": ["3 4\n2 5\n7 9\n10 11", "5 10\n5 7\n11 12\n16 20\n25 26\n30 33", "1 1000000000\n1 1000000000"], "sample_outputs": ["10", "18", "1999999999"], "notes": "NoteIn the first example if the glider can jump out at $$$(2, 4)$$$, then the landing point is $$$(12, 0)$$$, so the distance is $$$12-2 = 10$$$.In the second example the glider can fly from $$$(16,10)$$$ to $$$(34,0)$$$, and the distance is $$$34-16=18$$$.In the third example the glider can fly from $$$(-100,1000000000)$$$ to $$$(1999999899,0)$$$, so the distance is $$$1999999899-(-100)=1999999999$$$."}, "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 = ni()\n\n case class Seg(l: Int, r: Int) {\n def len = r - l\n }\n\n val S = Array.ofDim[Seg](N)\n rep(N) { i =>\n val l, r = ni()\n S(i) = Seg(l, r)\n }\n\n var l, r = 0\n var sum = S(0).len\n var mx = sum\n var len = 0\n while(l < N) {\n while (r + 1 < N && len + (S(r + 1).l - S(r).r) < H) {\n len += S(r + 1).l - S(r).r\n r += 1\n sum += S(r).len\n }\n mx = max(mx, sum)\n sum -= S(l).len\n if (l + 1 < N) len -= S(l + 1).l - S(l).r\n l += 1\n }\n\n out.println(mx + H)\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": "9d22a23124620f266d700eb8b305eab4"} {"nl": {"description": "You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.", "input_spec": "Input begins with an integer N (2\u2009\u2264\u2009N\u2009\u2264\u20093\u00b7105), the number of days. Following this is a line with exactly N integers p1,\u2009p2,\u2009...,\u2009pN (1\u2009\u2264\u2009pi\u2009\u2264\u2009106). The price of one share of stock on the i-th day is given by pi.", "output_spec": "Print the maximum amount of money you can end up with at the end of N days.", "sample_inputs": ["9\n10 5 4 7 9 12 6 2 10", "20\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4"], "sample_outputs": ["20", "41"], "notes": "NoteIn the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is \u2009-\u20095\u2009-\u20094\u2009+\u20099\u2009+\u200912\u2009-\u20092\u2009+\u200910\u2009=\u200920."}, "positive_code": [{"source_code": "object DD extends App {\n\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 var profit = 0L\n val pq = new java.util.PriorityQueue[Int]\n\n for (p <- ps) {\n pq.add(p)\n if (pq.peek < p) {\n profit += p - pq.poll()\n pq.add(p)\n }\n }\n\n println(profit)\n}\n"}], "negative_code": [], "src_uid": "994bfacedc61a4a67c0997011cadb333"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$m$$$. Calculate the number of pairs of arrays $$$(a, b)$$$ such that: the length of both arrays is equal to $$$m$$$; each element of each array is an integer between $$$1$$$ and $$$n$$$ (inclusive); $$$a_i \\le b_i$$$ for any index $$$i$$$ from $$$1$$$ to $$$m$$$; array $$$a$$$ is sorted in non-descending order; array $$$b$$$ is sorted in non-ascending order. As the result can be very large, you should print it modulo $$$10^9+7$$$.", "input_spec": "The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 1000$$$, $$$1 \\le m \\le 10$$$).", "output_spec": "Print one integer \u2013 the number of arrays $$$a$$$ and $$$b$$$ satisfying the conditions described above modulo $$$10^9+7$$$.", "sample_inputs": ["2 2", "10 1", "723 9"], "sample_outputs": ["5", "55", "157557417"], "notes": "NoteIn the first test there are $$$5$$$ suitable arrays: $$$a = [1, 1], b = [2, 2]$$$; $$$a = [1, 2], b = [2, 2]$$$; $$$a = [2, 2], b = [2, 2]$$$; $$$a = [1, 1], b = [2, 1]$$$; $$$a = [1, 1], b = [1, 1]$$$. "}, "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}"}, {"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 \u2190 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}"}], "negative_code": [], "src_uid": "82293f824c5afbf9dbbb47eac421af33"} {"nl": {"description": "You're given two arrays $$$a[1 \\dots n]$$$ and $$$b[1 \\dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \\le l \\le r \\le n$$$ and $$$k > 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \\ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \\underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \\le i \\le n$$$, $$$a_i = b_i$$$)", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 20$$$) \u2014 the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100\\ 000$$$) \u2014 the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, output one line containing \"YES\" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or \"NO\" if it's impossible. You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n6\n3 7 1 4 1 2\n3 7 3 6 3 2\n5\n1 1 1 1 1\n1 2 1 3 1\n2\n42 42\n42 42\n1\n7\n6"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a directed graph with $$$n$$$ vertices and $$$m$$$ directed edges without self-loops or multiple edges.Let's denote the $$$k$$$-coloring of a digraph as following: you color each edge in one of $$$k$$$ colors. The $$$k$$$-coloring is good if and only if there no cycle formed by edges of same color.Find a good $$$k$$$-coloring of given digraph with minimum possible $$$k$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 5000$$$, $$$1 \\le m \\le 5000$$$) \u2014 the number of vertices and edges in the digraph, respectively. Next $$$m$$$ lines contain description of edges \u2014 one per line. Each edge is a pair of integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\ne v$$$) \u2014 there is directed edge from $$$u$$$ to $$$v$$$ in the graph. It is guaranteed that each ordered pair $$$(u, v)$$$ appears in the list of edges at most once.", "output_spec": "In the first line print single integer $$$k$$$ \u2014 the number of used colors in a good $$$k$$$-coloring of given graph. In the second line print $$$m$$$ integers $$$c_1, c_2, \\dots, c_m$$$ ($$$1 \\le c_i \\le k$$$), where $$$c_i$$$ is a color of the $$$i$$$-th edge (in order as they are given in the input). If there are multiple answers print any of them (you still have to minimize $$$k$$$).", "sample_inputs": ["4 5\n1 2\n1 3\n3 4\n2 4\n1 4", "3 3\n1 2\n2 3\n3 1"], "sample_outputs": ["1\n1 1 1 1 1", "2\n1 1 2"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 => // \u9806\u5e8f\u7dad\u6301\u3059\u308b\n p(from(i)) -= 1\n t(from(i))(p(from(i))) = to(i)\n }\n t\n }\n /**\n * @return \u9589\u8def\u306e\u5834\u5408\u306fnull\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 // \u9589\u8def\u30c1\u30a7\u30c3\u30af\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 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 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 @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"}, {"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"}], "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"} {"nl": {"description": "Roy and Biv have a set of n points on the infinite number line.Each point has one of 3 colors: red, green, or blue.Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).Help them compute the minimum cost way to choose edges to satisfy the above constraints.", "input_spec": "The first line will contain an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300\u2009000), the number of points. The next n lines will contain two tokens pi and ci (pi is an integer, 1\u2009\u2264\u2009pi\u2009\u2264\u2009109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.", "output_spec": "Print a single integer, the minimum cost way to solve the problem.", "sample_inputs": ["4\n1 G\n5 R\n10 B\n15 G", "4\n1 G\n2 R\n3 B\n10 G"], "sample_outputs": ["23", "12"], "notes": "NoteIn the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively."}, "positive_code": [{"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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 = Array.ofDim[Long](n)\n val cs = Array.ofDim[Char](n)\n\n for (i <- 0 until n) {\n val Array(p, c) = readLine.split(\" \")\n ps(i) = p.toLong\n cs(i) = c.head\n }\n\n var prevG = -1L\n var firstR, firstB, lastR, lastB = -1L\n\n var i = 0\n while (i < n && prevG < 0) {\n val pos = ps(i)\n cs(i) match {\n\n case 'R' =>\n if (firstR < 0) firstR = pos\n lastR = pos\n\n case 'B' =>\n if (firstB < 0) firstB = pos\n lastB = pos\n\n case 'G' =>\n prevG = pos\n }\n i += 1\n }\n\n var sum = 0L\n\n if (prevG >= 0) {\n if (firstR >= 0) sum += prevG - firstR\n if (firstB >= 0) sum += prevG - firstB\n } else {\n if (firstR >= 0) sum += lastR - firstR\n if (firstB >= 0) sum += lastB - firstB\n }\n\n var prevB, prevR = prevG\n var maxGapR, maxGapB = 0L\n\n while (i < n) {\n val pos = ps(i)\n cs(i) match {\n\n case 'R' =>\n val gapR = pos - prevR\n if (gapR > maxGapR) maxGapR = gapR\n prevR = pos\n\n case 'B' =>\n val gapB = pos - prevB\n if (gapB > maxGapB) maxGapB = gapB\n prevB = pos\n\n case 'G' =>\n\n val gapR = pos - prevR\n if (gapR > maxGapR) maxGapR = gapR\n\n val gapB = pos - prevB\n if (gapB > maxGapB) maxGapB = gapB\n\n val gapG = pos - prevG\n val sum1 = 2 * gapG\n val sum2 = 3 * gapG - maxGapR - maxGapB\n sum += Math.min(sum1, sum2)\n\n maxGapB = 0\n maxGapR = 0\n prevR = pos\n prevB = pos\n prevG = pos\n }\n\n i += 1\n }\n\n sum += prevR - prevG\n sum += prevB - prevG\n\n println(sum)\n}\n"}], "negative_code": [{"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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 = Array.ofDim[Long](n)\n val cs = Array.ofDim[Char](n)\n\n for (i <- 0 until n) {\n val Array(p, c) = readLine.split(\" \")\n ps(i) = p.toLong\n cs(i) = c.head\n }\n\n var prevG = -1L\n var firstR, firstB = -1L\n\n var i = 0\n while (i < n && prevG < 0) {\n val pos = ps(i)\n cs(i) match {\n\n case 'R' =>\n if (firstR < 0) firstR = pos\n\n case 'B' =>\n if (firstB < 0) firstB = pos\n\n case 'G' =>\n prevG = pos\n }\n i += 1\n }\n\n var sum = 0L\n if (firstR >= 0) sum += prevG - firstR\n if (firstB >= 0) sum += prevG - firstB\n\n var prevB, prevR = prevG\n var maxGapR, maxGapB = 0L\n\n while (i < n) {\n val pos = ps(i)\n cs(i) match {\n\n case 'R' =>\n val gapR = pos - prevR\n if (gapR > maxGapR) maxGapR = gapR\n prevR = pos\n\n case 'B' =>\n val gapB = pos - prevB\n if (gapB > maxGapB) maxGapB = gapB\n prevB = pos\n\n case 'G' =>\n\n val gapR = pos - prevR\n if (gapR > maxGapR) maxGapR = gapR\n\n val gapB = pos - prevB\n if (gapB > maxGapB) maxGapB = gapB\n\n val gapG = pos - prevG\n val sum1 = 2 * gapG\n val sum2 = 3 * gapG - maxGapR - maxGapB\n sum += Math.min(sum1, sum2)\n\n maxGapB = 0\n maxGapR = 0\n prevR = pos\n prevB = pos\n prevG = pos\n }\n\n i += 1\n }\n\n sum += prevR - prevG\n sum += prevB - prevG\n\n println(sum)\n}\n"}], "src_uid": "ebb9e236b6370a9cba9ffcd77fe4c97e"} {"nl": {"description": "Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1,\u2009i,\u2009r1,\u2009i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2,\u2009i,\u2009r2,\u2009i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1,\u2009r1) and (l2,\u2009r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i\u2009-\u2009j|, where l1\u2009\u2264\u2009i\u2009\u2264\u2009r1 and l2\u2009\u2264\u2009j\u2009\u2264\u2009r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1,\u2009i and r1,\u2009i (1\u2009\u2264\u2009l1,\u2009i\u2009\u2264\u2009r1,\u2009i\u2009\u2264\u2009109)\u00a0\u2014 the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2,\u2009i and r2,\u2009i (1\u2009\u2264\u2009l2,\u2009i\u2009\u2264\u2009r2,\u2009i\u2009\u2264\u2009109)\u00a0\u2014 the i-th variant of a period of time when Anton can attend programming classes.", "output_spec": "Output one integer\u00a0\u2014 the maximal possible distance between time periods.", "sample_inputs": ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"], "sample_outputs": ["3", "0"], "notes": "NoteIn the first sample Anton can attend chess classes in the period (2,\u20093) and attend programming classes in the period (6,\u20098). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0."}, "positive_code": [{"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"}, {"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 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"}, {"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": "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"}], "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"} {"nl": {"description": "On a random day, Neko found $$$n$$$ treasure chests and $$$m$$$ keys. The $$$i$$$-th chest has an integer $$$a_i$$$ written on it and the $$$j$$$-th key has an integer $$$b_j$$$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.The $$$j$$$-th key can be used to unlock the $$$i$$$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $$$a_i + b_j \\equiv 1 \\pmod{2}$$$. One key can be used to open at most one chest, and one chest can be opened at most once.Find the maximum number of chests Neko can open.", "input_spec": "The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^5$$$)\u00a0\u2014 the number of chests and the number of keys. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the numbers written on the treasure chests. The third line contains $$$m$$$ integers $$$b_1, b_2, \\ldots, b_m$$$ ($$$1 \\leq b_i \\leq 10^9$$$)\u00a0\u2014 the numbers written on the keys.", "output_spec": "Print the maximum number of chests you can open.", "sample_inputs": ["5 4\n9 14 6 2 11\n8 4 7 20", "5 1\n2 4 6 8 10\n5", "1 4\n10\n20 30 40 50"], "sample_outputs": ["3", "1", "0"], "notes": "NoteIn the first example, one possible way to unlock $$$3$$$ chests is as follows: Use first key to unlock the fifth chest, Use third key to unlock the second chest, Use fourth key to unlock the first chest. In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).In the third example, no key can unlock the given chest."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "bc532d5c9845940b5f59485394187bf6"} {"nl": {"description": "We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $$$a$$$ yuan for $$$b$$$ kilos (You don't need to care about what \"yuan\" is), the same as $$$a/b$$$ yuan for a kilo.Now imagine you'd like to buy $$$m$$$ kilos of apples. You've asked $$$n$$$ supermarkets and got the prices. Find the minimum cost for those apples.You can assume that there are enough apples in all supermarkets.", "input_spec": "The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n \\leq 5\\,000$$$, $$$1 \\leq m \\leq 100$$$), denoting that there are $$$n$$$ supermarkets and you want to buy $$$m$$$ kilos of apples. The following $$$n$$$ lines describe the information of the supermarkets. Each line contains two positive integers $$$a, b$$$ ($$$1 \\leq a, b \\leq 100$$$), denoting that in this supermarket, you are supposed to pay $$$a$$$ yuan for $$$b$$$ kilos of apples.", "output_spec": "The only line, denoting the minimum cost for $$$m$$$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $$$10^{-6}$$$. Formally, let your answer be $$$x$$$, and the jury's answer be $$$y$$$. Your answer is considered correct if $$$\\frac{|x - y|}{\\max{(1, |y|)}} \\le 10^{-6}$$$.", "sample_inputs": ["3 5\n1 2\n3 4\n1 3", "2 1\n99 100\n98 99"], "sample_outputs": ["1.66666667", "0.98989899"], "notes": "NoteIn the first sample, you are supposed to buy $$$5$$$ kilos of apples in supermarket $$$3$$$. The cost is $$$5/3$$$ yuan.In the second sample, you are supposed to buy $$$1$$$ kilo of apples in supermarket $$$2$$$. The cost is $$$98/99$$$ yuan."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "3bbe48918a7bf3faf01c74cb7296f6e0"} {"nl": {"description": "Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000)\u00a0\u2014 the number of balls. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u2009n) where ti is the color of the i-th ball.", "output_spec": "Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.", "sample_inputs": ["4\n1 2 1 2", "3\n1 1 1"], "sample_outputs": ["7 3 0 0", "6 0 0"], "notes": "NoteIn the first sample, color 2 is dominant in three intervals: An interval [2,\u20092] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4,\u20094] contains one ball, with color 2 again. An interval [2,\u20094] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them."}, "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 - 1)\n val colors = Array.ofDim[Int](n)\n\n def dom(i: Int) {\n val map = Array.ofDim[Int](n)\n var index = 0\n (i until n).foreach { j =>\n map(line(j)) += 1\n val candidate = map(line(j))\n if (candidate > map(index) || (candidate == map(index) && line(j) < index))\n index = line(j)\n colors(index) += 1\n }\n }\n\n (0 until n).foreach(i => dom(i))\n println(colors.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "f292c099e4eac9259a5bc9e42ff6d1b5"} {"nl": {"description": "There is an infinite sequence consisting of all positive integers in the increasing order: p\u2009=\u2009{1,\u20092,\u20093,\u2009...}. We performed n swap operations with this sequence. A swap(a,\u2009b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i,\u2009j), that i\u2009<\u2009j and pi\u2009>\u2009pj.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009109, ai\u2009\u2260\u2009bi)\u00a0\u2014 the arguments of the swap operation.", "output_spec": "Print a single integer \u2014 the number of inversions in the resulting sequence.", "sample_inputs": ["2\n4 2\n1 4", "3\n1 6\n3 4\n2 5"], "sample_outputs": ["4", "15"], "notes": "NoteIn the first sample the sequence is being modified as follows: . It has 4 inversions formed by index pairs (1,\u20094), (2,\u20093), (2,\u20094) and (3,\u20094)."}, "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._\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 = nextInt\n val a = Array.ofDim[Int](n)\n val b = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n a(i) = nextInt\n b(i) = nextInt\n }\n val pos_set: Set[Int] = a.toSet | b.toSet\n val p = pos_set.toArray.sorted\n val v = pos_set.toArray.sorted\n for (i <- 0 until n) {\n val pa = lowerBound(p, a(i))\n val pb = lowerBound(p, b(i))\n val tuple = (v(pa), v(pb)).swap\n v(pa) = tuple._1\n v(pb) = tuple._2\n }\n var res: Long = 0\n for (i <- 0 until p.length) {\n res += math.abs(p(i) - v(i)) - math.abs(i - lowerBound(p, v(i)))\n }\n for (i <- 0 until p.length) {\n val cur_p = lowerBound(p, v(i)) + 1\n res += getRange(cur_p, N - 1)\n addBit(cur_p, 1)\n }\n out.println(res)\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": "f6cd855ceda6029fc7d14daf2c9bb7dc"} {"nl": {"description": "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 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 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 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 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 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 guaranteed that at the end of the game at least one player has a positive number of points.", "input_spec": "The first line contains an integer number n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u20091000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in \"name score\" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.", "output_spec": "Print the name of the winner.", "sample_inputs": ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"], "sample_outputs": ["andrew", "andrew"], "notes": null}, "positive_code": [{"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 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"}, {"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 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"}, {"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": "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 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 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"}], "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"} {"nl": {"description": "The 2050 volunteers are organizing the \"Run! Chase the Rising Sun\" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.There are $$$n+1$$$ checkpoints on the trail. They are numbered by $$$0$$$, $$$1$$$, ..., $$$n$$$. A runner must start at checkpoint $$$0$$$ and finish at checkpoint $$$n$$$. No checkpoint is skippable\u00a0\u2014 he must run from checkpoint $$$0$$$ to checkpoint $$$1$$$, then from checkpoint $$$1$$$ to checkpoint $$$2$$$ and so on. Look at the picture in notes section for clarification.Between any two adjacent checkpoints, there are $$$m$$$ different paths to choose. For any $$$1\\le i\\le n$$$, to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$, a runner can choose exactly one from the $$$m$$$ possible paths. The length of the $$$j$$$-th path between checkpoint $$$i-1$$$ and $$$i$$$ is $$$b_{i,j}$$$ for any $$$1\\le j\\le m$$$ and $$$1\\le i\\le n$$$.To test the trail, we have $$$m$$$ runners. Each runner must run from the checkpoint $$$0$$$ to the checkpoint $$$n$$$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length $$$l_i$$$ between checkpoint $$$i-1$$$ and $$$i$$$ ($$$1\\le i\\le n$$$), his tiredness is $$$$$$\\min_{i=1}^n l_i,$$$$$$ i.\u00a0e. the minimum length of the paths he takes.Please arrange the paths of the $$$m$$$ runners to minimize the sum of tiredness of them.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n,m \\leq 100$$$). The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$b_{i,1}$$$, $$$b_{i,2}$$$, ..., $$$b_{i,m}$$$ ($$$1 \\le b_{i,j} \\le 10^9$$$). It is guaranteed that the sum of $$$n\\cdot m$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case, output $$$n$$$ lines. The $$$j$$$-th number in the $$$i$$$-th line should contain the length of the path that runner $$$j$$$ chooses to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$. There should be exactly $$$m$$$ integers in the $$$i$$$-th line and these integers should form a permuatation of $$$b_{i, 1}$$$, ..., $$$b_{i, m}$$$ for all $$$1\\le i\\le n$$$. If there are multiple answers, print any.", "sample_inputs": ["2\n2 3\n2 3 4\n1 3 5\n3 2\n2 3\n4 1\n3 5"], "sample_outputs": ["2 3 4\n5 3 1\n2 3\n4 1\n3 5"], "notes": "NoteIn the first case, the sum of tiredness is $$$\\min(2,5) + \\min(3,3) + \\min(4,1) = 6$$$. In the second case, the sum of tiredness is $$$\\min(2,4,3) + \\min(3,1,5) = 3$$$."}, "positive_code": [{"source_code": "import scala.collection._\r\nimport scala.collection.mutable.TreeSet\r\nimport scala.collection.mutable.HashSet\r\nimport scala.collection.mutable.ArrayBuffer\r\nimport scala.io.StdIn._\r\nimport scala.util._\r\n\r\nobject Jogging {\r\n def main(args: Array[String]): Unit = {\r\n val t = readInt()\r\n\r\n\r\n (0 until t).foreach( _ => {\r\n val line = readLine().split(\" \").map(v => v.toInt)\r\n val n = line(0)\r\n val m = line(1)\r\n\r\n val set = TreeSet[(Int, Int, Int)]()(Ordering[(Int, Int, Int)].on((x: (Int, Int, Int)) => (x._1, x._2, x._3)))\r\n val sets = Array.ofDim[TreeSet[(Int, Int, Int)]](n)\r\n\r\n for (i <- 0 until n) {\r\n var count = -1\r\n val routes = readLine().split(\" \").map(v => {\r\n count += 1\r\n (v.toInt, i, count)\r\n })\r\n\r\n for (v <- routes) {\r\n set.add(v)\r\n }\r\n\r\n sets(i) = TreeSet[(Int, Int, Int)]()\r\n\r\n for (v <- routes) {\r\n sets(i).add(v)\r\n }\r\n }\r\n\r\n val used = mutable.HashSet[(Int, Int, Int)]()\r\n for (i <- 0 until m) {\r\n val e = set.head\r\n used += e\r\n set.remove(e)\r\n }\r\n\r\n val runnerpath = Array.ofDim[ArrayBuffer[Int]](m)\r\n val runnerfoundopt = Array.ofDim[Boolean](m)\r\n (0 until m).foreach(v => runnerpath(v) = ArrayBuffer[Int]())\r\n (0 until m).foreach(v => runnerfoundopt(v) = false)\r\n \r\n for (runner <- 0 until m) {\r\n for (node <- 0 until n) {\r\n var continue = true\r\n if (!runnerfoundopt(runner)) {\r\n for (p <- sets(node) ; if continue) {\r\n if (used.contains(p)) {\r\n runnerpath(runner) += p._1\r\n runnerfoundopt(runner) = true\r\n used -= p\r\n sets(node).remove(p)\r\n continue = false\r\n }\r\n }\r\n }\r\n\r\n if (continue) {\r\n for (p <- sets(node) ; if continue) {\r\n if (!used.contains(p)) {\r\n runnerpath(runner) += p._1\r\n sets(node).remove(p)\r\n continue = false\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (node <- 0 until n) {\r\n for (runner <- 0 until m) {\r\n print(runnerpath(runner)(node))\r\n\r\n if (runner != m - 1) {\r\n print(\" \")\r\n }\r\n }\r\n println()\r\n }\r\n })\r\n }\r\n}"}], "negative_code": [], "src_uid": "a9021fed22299e90aaef50c4d0d9f5b2"} {"nl": {"description": "You are given two integers $$$x$$$ and $$$y$$$. You want to choose two strictly positive (greater than zero) integers $$$a$$$ and $$$b$$$, and then apply the following operation to $$$x$$$ exactly $$$a$$$ times: replace $$$x$$$ with $$$b \\cdot x$$$.You want to find two positive integers $$$a$$$ and $$$b$$$ such that $$$x$$$ becomes equal to $$$y$$$ after this process. If there are multiple possible pairs, you can choose any of them. If there is no such pair, report it.For example: if $$$x = 3$$$ and $$$y = 75$$$, you may choose $$$a = 2$$$ and $$$b = 5$$$, so that $$$x$$$ becomes equal to $$$3 \\cdot 5 \\cdot 5 = 75$$$; if $$$x = 100$$$ and $$$y = 100$$$, you may choose $$$a = 3$$$ and $$$b = 1$$$, so that $$$x$$$ becomes equal to $$$100 \\cdot 1 \\cdot 1 \\cdot 1 = 100$$$; if $$$x = 42$$$ and $$$y = 13$$$, there is no answer since you cannot decrease $$$x$$$ with the given operations. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x, y \\le 100$$$).", "output_spec": "If it is possible to choose a pair of positive integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$ after the aforementioned process, print these two integers. The integers you print should be not less than $$$1$$$ and not greater than $$$10^9$$$ (it can be shown that if the answer exists, there is a pair of integers $$$a$$$ and $$$b$$$ meeting these constraints). If there are multiple such pairs, print any of them. If it is impossible to choose a pair of integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$, print the integer $$$0$$$ twice.", "sample_inputs": ["3\n\n3 75\n\n100 100\n\n42 13"], "sample_outputs": ["2 5\n3 1\n0 0"], "notes": null}, "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(x: Int, y: Int) = {\r\n if (x > y) println(\"0 0\")\r\n else if (x == y) println(\"1 1\")\r\n else if (y % x != 0) println(\"0 0\")\r\n else println(s\"1 ${y / x} \")\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 a = rsi()\r\n ) solve(a(0), a(1))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "f7defb09175c842de490aa13a4f5a0c9"} {"nl": {"description": "Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.Return the maximum number of rows that she can make completely clean.", "input_spec": "The first line of input will be a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.", "output_spec": "The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.", "sample_inputs": ["4\n0101\n1000\n1111\n0101", "3\n111\n111\n111"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.In the second sample, everything is already clean, so Ohana doesn't need to do anything."}, "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": "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"}, {"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"} {"nl": {"description": "You are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of elements in the given array. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of the array a.", "output_spec": "Print integer k on the first line \u2014 the least number of elements needed to add to the array a to make it co-prime. The second line should contain n\u2009+\u2009k integers aj \u2014 the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it. If there are multiple answers you can print any one of them.", "sample_inputs": ["3\n2 7 28"], "sample_outputs": ["1\n2 7 9 28"], "notes": null}, "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\n def factorize(a : Int): Set[Int] = {\n if (a == 1) Set.empty\n else if (a % 2 == 0) Set(2) ++ factorize(a / 2)\n else (3 to Math.sqrt(a).toInt by 2)\n .find(i => a % i == 0)\n .map(i => Set(i) ++ factorize(a / i))\n .getOrElse(Set(a))\n }\n\n\n if (n == 1) {\n println(0)\n println(data.head)\n }\n else {\n val factors = data.map(i => factorize(i))\n val result = data.head :: factors.zip(data).sliding(2).flatMap{\n case Array((s1, v1), (s2, v2)) =>\n if (s1.intersect(s2).nonEmpty)\n List(1 , v2)\n else\n List(v2)\n }.toList\n println(result.length - n)\n println(result.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\n def factorize(a : Int): Set[Int] = {\n if (a % 2 == 0) Set(a) ++ factorize(a / 2)\n else (3 to Math.sqrt(a).toInt by 2).find(i => a % i == 0).map(i => Set(i) ++ factorize(a / i)).getOrElse(Set.empty)\n }\n\n\n if (n == 1) {\n println(0)\n println(data.head)\n }\n else {\n val factors = data.map(i => factorize(i))\n val result = data.head :: factors.zip(data).sliding(2).flatMap{\n case Array((s1, v1), (s2, v2)) =>\n if (s1.intersect(s2).nonEmpty)\n List(1 , v2)\n else\n List(v2)\n }.toList\n println(result.length - n)\n println(result.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\n def factorize(a : Int): Set[Int] = {\n if (a % 2 == 0) Set(a) ++ factorize(a / 2)\n else (3 to a by 2).find(i => a % i == 0).map(i => Set(i) ++ factorize(a / i)).getOrElse(Set.empty)\n }\n\n\n if (n == 1) {\n println(0)\n println(data.head)\n }\n else {\n val factors = data.map(i => factorize(i))\n val result = data.head :: factors.zip(data).sliding(2).flatMap{\n case Array((s1, v1), (s2, v2)) =>\n if (s1.intersect(s2).nonEmpty)\n List(1 , v2)\n else\n List(v2)\n }.toList\n println(result.length - n)\n println(result.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\n def factorize(a : Int): Set[Int] = {\n if (a % 2 == 0) Set(a) ++ factorize(a / 2)\n else (3 to a by 2).find(i => a % i == 0).map(i => Set(i) ++ factorize(a / i)).getOrElse(Set.empty)\n }\n\n\n if (n == 1) {\n println(1)\n println(data.head)\n }\n else {\n val factors = data.map(i => factorize(i))\n val result = data.head :: factors.zip(data).sliding(2).flatMap{\n case Array((s1, v1), (s2, v2)) =>\n if (s1.intersect(s2).nonEmpty)\n List(1 , v2)\n else\n List(v2)\n }.toList\n println(result.length - n)\n println(result.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\n def factorize(a : Int): Set[Int] = {\n if (a == 1) Set.empty\n else if (a % 2 == 0) Set(a) ++ factorize(a / 2)\n else (3 to Math.sqrt(a).toInt by 2)\n .find(i => a % i == 0)\n .map(i => Set(i) ++ factorize(a / i))\n .getOrElse(Set(a))\n }\n\n\n if (n == 1) {\n println(0)\n println(data.head)\n }\n else {\n val factors = data.map(i => factorize(i))\n val result = data.head :: factors.zip(data).sliding(2).flatMap{\n case Array((s1, v1), (s2, v2)) =>\n if (s1.intersect(s2).nonEmpty)\n List(1 , v2)\n else\n List(v2)\n }.toList\n println(result.length - n)\n println(result.mkString(\" \"))\n }\n}\n"}], "src_uid": "b0b4cadc46f9fd056bf7dc36d1cf51f2"} {"nl": {"description": "Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.Help Yaroslav.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of elements in the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 the array elements.", "output_spec": "In the single line print \"YES\" (without the quotes) if Yaroslav can obtain the array he needs, and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["1\n1", "3\n1 1 2", "4\n7 7 7 7"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first sample the initial array fits well.In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.In the third sample Yarosav can't get the array he needs. "}, "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(\" \").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"}, {"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"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\dots , p_n$$$ (an array where each integer from $$$1$$$ to $$$n$$$ appears exactly once). The weight of the $$$i$$$-th element of this permutation is $$$a_i$$$.At first, you separate your permutation into two non-empty sets \u2014 prefix and suffix. More formally, the first set contains elements $$$p_1, p_2, \\dots , p_k$$$, the second \u2014 $$$p_{k+1}, p_{k+2}, \\dots , p_n$$$, where $$$1 \\le k < n$$$.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay $$$a_i$$$ dollars to move the element $$$p_i$$$.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if $$$p = [3, 1, 2]$$$ and $$$a = [7, 1, 4]$$$, then the optimal strategy is: separate $$$p$$$ into two parts $$$[3, 1]$$$ and $$$[2]$$$ and then move the $$$2$$$-element into first set (it costs $$$4$$$). And if $$$p = [3, 5, 1, 6, 2, 4]$$$, $$$a = [9, 1, 9, 9, 1, 9]$$$, then the optimal strategy is: separate $$$p$$$ into two parts $$$[3, 5, 1]$$$ and $$$[6, 2, 4]$$$, and then move the $$$2$$$-element into first set (it costs $$$1$$$), and $$$5$$$-element into second set (it also costs $$$1$$$).Calculate the minimum number of dollars you have to spend.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of permutation. The second line contains $$$n$$$ integers $$$p_1, p_2, \\dots , p_n$$$ ($$$1 \\le p_i \\le n$$$). It's guaranteed that this sequence contains each element from $$$1$$$ to $$$n$$$ exactly once. The third line contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print one integer \u2014 the minimum number of dollars you have to spend.", "sample_inputs": ["3\n3 1 2\n7 1 4", "4\n2 4 1 3\n5 9 8 3", "6\n3 5 1 6 2 4\n9 1 9 9 1 9"], "sample_outputs": ["4", "3", "2"], "notes": null}, "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 def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n\n\n val n = in.nextInt()\n val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray\n val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray\n\n\n\n\n val pos: Array[Int] = Array.fill(n)(0)\n p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}\n\n\n val st = new SegmentTree(n)\n\n val initialBuild = w.scanLeft(0L)(_ + _).tail\n\n st.build(initialBuild)\n\n val initialRes = st.query(0,n-1)\n\n val res = (0 until n).foldLeft(initialRes){\n case (currentRes, v) => {\n val k = pos(v)\n //0 k> += w(k)\n //[k oo] -= w(k)\n\n if(k>0)\n st.update(0,k,w(k))\n if(k\n def + (other: A): A\n def value: T\n def addLazy(lazyVal: Long): A\n }\n trait LazyValue[A,L]{ self: A =>\n def value: Option[L]\n def + (other: A): A\n }\n\n\n\n\n class SegmentTree(maxN: Int){\n val defaultLazy = 0L\n val minimos = Array.fill(maxN*4)(0L)\n\n\n val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n build(nodes,0,N,0)\n lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)\n }\n private def build(nodes: Array[Long], l: Int, r: Int, v: Int): Unit ={\n\n if(l+1 == r){\n minimos(v) = nodes(l)\n\n }else{\n val m = (l+r)/2\n build(nodes,l,m,v*2+1)\n build(nodes,m,r,v*2+2)\n minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))\n\n }\n }\n\n def query(left: Int, right: Int): Long = query(0,0,N,left,right)\n private def query(v: Int, l: Int, r: Int, L: Int, R: Int): Long = {\n\n if(L >= R){\n Long.MaxValue\n }else{\n push(v,l,r)\n if(l == l && r == R)\n minimos(v)\n else{\n val mid = (l+r)/2\n val a = query(v*2+1,l,mid,L,Math.min(R,mid))\n val b = query(v*2+2,mid,r,Math.max(L,mid),R)\n Math.min(a,b)\n }\n }\n\n }\n\n def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)\n\n private def push(v: Int, l: Int, r: Int): Unit = {\n if(lazyValue(v) != 0){\n if(r-l > 1){\n lazyValue(v*2+1) += lazyValue(v)\n minimos(v*2+1) += lazyValue(v)\n\n lazyValue(v*2+2) += lazyValue(v)\n minimos(v*2+2) += lazyValue(v)\n\n }\n lazyValue(v) = 0\n }\n\n\n }\n\n\n private def update(v: Int, l: Int, r: Int, L: Int, R: Int, x: Long): Unit = {\n\n if(L < R){\n\n if(l == L && r == R){\n lazyValue(v) += x\n minimos(v) += x\n push(v,l,r)\n }else{\n\n push(v,l,r)\n val mid = (l+r)/2\n update(v*2+1,l,mid,L,Math.min(mid,R),x)\n update(v*2+2,mid,r,Math.max(mid,L),R,x)\n minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))\n\n }\n\n\n }\n\n }\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": [{"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 def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n\n\n val n = in.nextInt()\n val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray\n val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray\n\n\n\n\n val pos: Array[Int] = Array.fill(n)(0)\n p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}\n\n\n val st = new SegmentTree(n)\n\n val initialBuild = w.scanLeft(0L)(_ + _).tail\n\n st.build(initialBuild)\n\n\n\n val res = (0 until n).foldLeft(Long.MaxValue){\n case (currentRes, v) => {\n val k = pos(v)\n //0 k> += w(k)\n //[k oo] -= w(k)\n\n if(k>0)\n st.update(0,k,w(k))\n if(k\n def + (other: A): A\n def value: T\n def addLazy(lazyVal: Long): A\n }\n trait LazyValue[A,L]{ self: A =>\n def value: Option[L]\n def + (other: A): A\n }\n\n\n\n\n class SegmentTree(maxN: Int){\n val defaultLazy = 0L\n val minimos = Array.fill(maxN*4)(0L)\n\n\n val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n build(nodes,0,N,0)\n lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)\n }\n private def build(nodes: Array[Long], l: Int, r: Int, v: Int): Unit ={\n\n if(l+1 == r){\n minimos(v) = nodes(l)\n\n }else{\n val m = (l+r)/2\n build(nodes,l,m,v*2+1)\n build(nodes,m,r,v*2+2)\n minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))\n\n }\n }\n\n def query(left: Int, right: Int): Long = query(0,0,N,left,right)\n private def query(v: Int, l: Int, r: Int, L: Int, R: Int): Long = {\n\n if(L >= R){\n Long.MaxValue\n }else{\n push(v,l,r)\n if(l == l && r == R)\n minimos(v)\n else{\n val mid = (l+r)/2\n val a = query(v*2+1,l,mid,L,Math.min(R,mid))\n val b = query(v*2+2,mid,r,Math.max(L,mid),R)\n Math.min(a,b)\n }\n }\n\n }\n\n def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)\n\n private def push(v: Int, l: Int, r: Int): Unit = {\n if(lazyValue(v) != 0){\n if(r-l > 1){\n lazyValue(v*2+1) += lazyValue(v)\n minimos(v*2+1) += lazyValue(v)\n\n lazyValue(v*2+2) += lazyValue(v)\n minimos(v*2+2) += lazyValue(v)\n\n }\n lazyValue(v) = 0\n }\n\n\n }\n\n\n private def update(v: Int, l: Int, r: Int, L: Int, R: Int, x: Long): Unit = {\n\n if(L < R){\n\n if(l == L && r == R){\n lazyValue(v) += x\n minimos(v) += x\n push(v,l,r)\n }else{\n\n push(v,l,r)\n val mid = (l+r)/2\n update(v*2+1,l,mid,L,Math.min(mid,R),x)\n update(v*2+2,mid,r,Math.max(mid,L),R,x)\n minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))\n\n }\n\n\n }\n\n }\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}"}, {"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 def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n\n\n val n = in.nextInt()\n val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray\n val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray\n\n\n\n\n val pos: Array[Int] = Array.fill(n)(0)\n p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}\n\n\n val st = new SegmentTree(n)\n\n val initialBuild = w.scanLeft(0L)(_ + _).tail\n\n st.build(initialBuild)\n\n\n\n val res = (0 until n).foldLeft(Long.MaxValue){\n case (currentRes, v) => {\n val k = pos(v)\n //0 k> += w(k)\n //[k oo] -= w(k)\n\n if(k>0)\n st.update(0,k,w(k))\n if(k\n def + (other: A): A\n def value: T\n def addLazy(lazyVal: Long): A\n }\n trait LazyValue[A,L]{ self: A =>\n def value: Option[L]\n def + (other: A): A\n }\n\n\n\n\n class SegmentTree(maxN: Int){\n val defaultLazy = 0L\n val minimos = Array.fill(maxN*4)(0L)\n\n\n val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n build(nodes,0,N,0)\n lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)\n }\n private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={\n\n if(left+1 == right){\n minimos(n) = nodes(left)\n\n }else{\n val m = (left+right)/2\n build(nodes,left,m,n*2+1)\n build(nodes,m,right,n*2+2)\n minimos(n) = Math.min(minimos(n*2+1),minimos(n*2+2))\n\n }\n }\n\n def query(left: Int, right: Int): Long = query(0,0,N,left,right)\n private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): Long = {\n\n minimos(n) = minimos(n) + lazyValue(n)\n// override def addLazy(lazyVal: Long): MinSumLengthNode = MinSumLengthNode(min+lazyVal,sum+lazyVal*len,len)\n\n if(n0+1 != nn){\n push(n)\n }\n\n lazyValue(n) = defaultLazy\n\n\n if(n0 == left && nn == right) {\n\n minimos(n)\n\n\n } else{\n val m = (n0+nn)/2\n if(left >= m){\n query(n*2+2,m,nn,left,right)\n }else{\n if( right <= m){\n query(n*2+1,n0,m,left,right)\n }else{\n val a = query(n*2+1,n0,m,left,m)\n val b = query(n*2+2,m,nn,m,right)\n Math.min(a,b)\n }\n }\n\n }\n }\n\n def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)\n\n private def push(n: Int): Unit = {\n lazyValue(n*2+1) = lazyValue(n*2+1) + lazyValue(n)\n lazyValue(n*2+2) = lazyValue(n*2+2) + lazyValue(n)\n\n }\n\n\n private def update(n: Int,n0: Int, nn: Int, left: Int, right: Int, valueToUpdate: Long): Unit = {\n\n minimos(n) = minimos(n) + lazyValue(n)\n\n\n if(n0+1 != nn){\n push(n)\n }\n\n lazyValue(n) = defaultLazy\n\n\n\n\n if(n0 == left && nn == right) {\n minimos(n) = minimos(n) + valueToUpdate\n\n if(n0+1 != nn){\n lazyValue(n) = valueToUpdate\n push(n)\n lazyValue(n) = defaultLazy\n }\n\n } else{\n val m = (n0+nn)/2\n\n push(n)\n\n if(left >= m){\n\n update(n*2+2,m,nn,left,right,valueToUpdate)\n\n }else{\n if( right <= m){\n\n update(n*2+1,n0,m,left,right,valueToUpdate)\n }else{\n update(n*2+1,n0,m,left,m,valueToUpdate)\n update(n*2+2,m,nn,m,right,valueToUpdate)\n\n }\n }\n val a0 = minimos(n*2+1) + lazyValue(n*2+1)\n val a1 = minimos(n*2+2) + lazyValue(n*2+2)\n\n\n minimos(n) = Math.min(a0,a1)\n }\n\n }\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}"}, {"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 def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n\n\n val n = in.nextInt()\n val p: Array[Int] = (1 to n).map(_ => in.nextInt()).toArray\n val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray\n\n\n\n\n val pos: Array[Int] = Array.fill(n+1)(0)\n p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}\n\n\n val st = new SegmentTree(n+2)\n\n val initialBuild = w.scanLeft(0L)(_ + _).tail\n\n st.build(initialBuild)\n\n\n\n val res = (1 to n).foldLeft(Long.MaxValue){\n case (currentRes, v) => {\n val k = pos(v)\n //0 k> += w(k)\n //[k oo] -= w(k)\n\n if(k>0)\n st.update(0,k,w(k))\n if(k\n def + (other: A): A\n def value: T\n def addLazy(lazyVal: Long): A\n }\n trait LazyValue[A,L]{ self: A =>\n def value: Option[L]\n def + (other: A): A\n }\n\n\n\n\n class SegmentTree(maxN: Int){\n val defaultLazy = 0L\n val minimos = Array.fill(maxN*4+2)(0L)\n val sumas = Array.fill(maxN*4+2)(0L)\n val longitudes = Array.fill(maxN*4+2)(0)\n\n val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n build(nodes,0,N,0)\n lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)\n }\n private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={\n\n if(left+1 == right){\n minimos(n) = nodes(left)\n sumas(n) = nodes(left)\n longitudes(n) = 1\n }else{\n val m = (left+right)/2\n build(nodes,left,m,n*2+1)\n build(nodes,m,right,n*2+2)\n minimos(n) = Math.min(minimos(n*2+1),minimos(n*2+2))\n sumas(n) = sumas(n*2+1)+sumas(n*2+2)\n longitudes(n) = longitudes(n*2+1)+longitudes(n*2+2)\n }\n }\n\n def query(left: Int, right: Int): Long = query(0,0,N,left,right)\n private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): Long = {\n\n minimos(n) = minimos(n) + lazyValue(n)\n sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)\n// override def addLazy(lazyVal: Long): MinSumLengthNode = MinSumLengthNode(min+lazyVal,sum+lazyVal*len,len)\n\n if(n0+1 != nn){\n push(n)\n }\n\n lazyValue(n) = defaultLazy\n\n\n if(n0 == left && nn == right) {\n\n minimos(n)\n\n\n } else{\n val m = (n0+nn)/2\n if(left >= m){\n query(n*2+2,m,nn,left,right)\n }else{\n if( right <= m){\n query(n*2+1,n0,m,left,right)\n }else{\n val a = query(n*2+1,n0,m,left,m)\n val b = query(n*2+2,m,nn,m,right)\n Math.min(a,b)\n }\n }\n\n }\n }\n\n def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)\n\n private def push(n: Int): Unit = {\n lazyValue(n*2+1) = lazyValue(n*2+1) + lazyValue(n)\n lazyValue(n*2+2) = lazyValue(n*2+2) + lazyValue(n)\n\n }\n\n\n private def update(n: Int,n0: Int, nn: Int, left: Int, right: Int, valueToUpdate: Long): Unit = {\n\n minimos(n) = minimos(n) + lazyValue(n)\n sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)\n\n\n if(n0+1 != nn){\n push(n)\n }\n\n lazyValue(n) = defaultLazy\n\n\n\n\n if(n0 == left && nn == right) {\n minimos(n) = minimos(n) + valueToUpdate\n sumas(n) = sumas(n)+valueToUpdate*longitudes(n)\n\n if(n0+1 != nn){\n lazyValue(n) = valueToUpdate\n push(n)\n lazyValue(n) = defaultLazy\n }\n\n } else{\n val m = (n0+nn)/2\n\n push(n)\n\n if(left >= m){\n\n update(n*2+2,m,nn,left,right,valueToUpdate)\n\n }else{\n if( right <= m){\n\n update(n*2+1,n0,m,left,right,valueToUpdate)\n }else{\n update(n*2+1,n0,m,left,m,valueToUpdate)\n update(n*2+2,m,nn,m,right,valueToUpdate)\n\n }\n }\n val a0 = minimos(n*2+1) + lazyValue(n*2+1)\n val a1 = minimos(n*2+2) + lazyValue(n*2+2)\n\n val b0 = sumas(n*2+1)+longitudes(n*2+1)*lazyValue(n*2+1)\n val b1 = sumas(n*2+2)+longitudes(n*2+2)*lazyValue(n*2+2)\n\n minimos(n) = Math.min(a0,a1)\n sumas(n) = b0+b1\n }\n\n }\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}"}, {"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 def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n\n\n val n = in.nextInt()\n val p: Array[Int] = (1 to n).map(_ => in.nextInt()).toArray\n val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray\n\n\n\n\n val pos: Array[Int] = Array.fill(n+1)(0)\n p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}\n\n\n val st = new SegmentTree(n+2)\n\n val initialBuild = w.scanLeft(0L)(_ + _).tail\n\n st.build(initialBuild)\n\n\n\n val res = (1 to n).foldLeft(Long.MaxValue){\n case (currentRes, v) => {\n val k = pos(v)\n //0 k> += w(k)\n //[k oo] -= w(k)\n\n if(k>0)\n st.update(0,k,w(k))\n if(k\n def + (other: A): A\n def value: T\n def addLazy(lazyVal: Long): A\n }\n trait LazyValue[A,L]{ self: A =>\n def value: Option[L]\n def + (other: A): A\n }\n\n\n\n\n class SegmentTree(maxN: Int){\n val defaultLazy = 0L\n val minimos = Array.fill(maxN*4+2)(0L)\n val sumas = Array.fill(maxN*4+2)(0L)\n val longitudes = Array.fill(maxN*4+2)(0)\n\n val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n build(nodes,0,N,0)\n lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)\n }\n private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={\n\n if(left+1 == right){\n minimos(n) = nodes(left)\n sumas(n) = nodes(left)\n longitudes(n) = 1\n }else{\n val m = (left+right)/2\n build(nodes,left,m,n*2+1)\n build(nodes,m,right,n*2+2)\n minimos(n) = Math.min(minimos(n*2+1),minimos(n*2+2))\n sumas(n) = sumas(n*2+1)+sumas(n*2+2)\n longitudes(n) = longitudes(n*2+1)+longitudes(n*2+2)\n }\n }\n\n def query(left: Int, right: Int): Long = query(0,0,N,left,right)\n private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): Long = {\n\n minimos(n) = minimos(n) + lazyValue(n)\n sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)\n// override def addLazy(lazyVal: Long): MinSumLengthNode = MinSumLengthNode(min+lazyVal,sum+lazyVal*len,len)\n\n if(n0+1 != nn){\n push(n)\n }\n\n lazyValue(n) = defaultLazy\n\n\n if(n0 == left && nn == right) {\n\n minimos(n)\n\n\n } else{\n val m = (n0+nn)/2\n if(left >= m){\n query(n*2+2,m,nn,left,right)\n }else{\n if( right <= m){\n query(n*2+1,n0,m,left,right)\n }else{\n val a = query(n*2+1,n0,m,left,m)\n val b = query(n*2+2,m,nn,m,right)\n Math.min(a,b)\n }\n }\n\n }\n }\n\n def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)\n\n private def push(n: Int): Unit = {\n lazyValue(n*2+1) = lazyValue(n*2+1) + lazyValue(n)\n lazyValue(n*2+2) = lazyValue(n*2+2) + lazyValue(n)\n\n }\n\n\n private def update(n: Int,n0: Int, nn: Int, left: Int, right: Int, valueToUpdate: Long): Unit = {\n\n minimos(n) = minimos(n) + lazyValue(n)\n sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)\n\n\n if(n0+1 != nn){\n push(n)\n }\n\n lazyValue(n) = defaultLazy\n\n\n\n\n if(n0 == left && nn == right) {\n minimos(n) = minimos(n) + valueToUpdate\n sumas(n) = sumas(n)+valueToUpdate*longitudes(n)\n\n if(n0+1 != nn){\n lazyValue(n) = valueToUpdate\n push(n)\n lazyValue(n) = defaultLazy\n }\n\n } else{\n val m = (n0+nn)/2\n\n push(n)\n\n if(left >= m){\n\n update(n*2+2,m,nn,left,right,valueToUpdate)\n\n }else{\n if( right <= m){\n\n update(n*2+1,n0,m,left,right,valueToUpdate)\n }else{\n update(n*2+1,n0,m,left,m,valueToUpdate)\n update(n*2+2,m,nn,m,right,valueToUpdate)\n\n }\n }\n val a0 = minimos(n*2+1) + lazyValue(n*2+1)\n val a1 = minimos(n*2+2) + lazyValue(n*2+2)\n\n val b0 = sumas(n*2+1)+longitudes(n*2+1)*lazyValue(n*2+1)\n val b1 = sumas(n*2+2)+longitudes(n*2+2)*lazyValue(n*2+2)\n\n minimos(n) = Math.min(a0,a1)\n sumas(n) = b0+b1\n }\n\n }\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}"}, {"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 def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n\n\n val n = in.nextInt()\n val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray\n val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray\n\n\n\n\n val pos: Array[Int] = Array.fill(n)(0)\n p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}\n\n\n val st = new SegmentTree(n)\n\n val initialBuild = w.scanLeft(0L)(_ + _).tail\n\n st.build(initialBuild)\n\n\n\n val res = (0 until n).foldLeft(Long.MaxValue){\n case (currentRes, v) => {\n val k = pos(v)\n //0 k> += w(k)\n //[k oo] -= w(k)\n\n if(k>0)\n st.update(0,k,w(k))\n if(k\n def + (other: A): A\n def value: T\n def addLazy(lazyVal: Long): A\n }\n trait LazyValue[A,L]{ self: A =>\n def value: Option[L]\n def + (other: A): A\n }\n\n\n\n\n class SegmentTree(maxN: Int){\n val defaultLazy = 0L\n val minimos = Array.fill(maxN*4)(0L)\n\n\n val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)\n var N: Int = 0\n def build(nodes: Array[Long]): Unit = {\n N = nodes.length\n build(nodes,0,N,0)\n lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)\n }\n private def build(nodes: Array[Long], l: Int, r: Int, v: Int): Unit ={\n\n if(l+1 == r){\n minimos(v) = nodes(l)\n\n }else{\n val m = (l+r)/2\n build(nodes,l,m,v*2+1)\n build(nodes,m,r,v*2+2)\n minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))\n\n }\n }\n\n def query(left: Int, right: Int): Long = query(0,0,N,left,right)\n private def query(v: Int, l: Int, r: Int, L: Int, R: Int): Long = {\n\n if(L >= R){\n Long.MaxValue\n }else{\n push(v,l,r)\n if(l == l && r == R)\n minimos(v)\n else{\n val mid = (l+r)/2\n val a = query(v*2+1,l,mid,L,Math.min(R,mid))\n val b = query(v*2+2,mid,r,Math.max(L,mid),R)\n Math.min(a,b)\n }\n }\n\n }\n\n def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)\n\n private def push(v: Int, l: Int, r: Int): Unit = {\n if(lazyValue(v) != 0){\n if(r-l > 1){\n lazyValue(v*2+1) += lazyValue(v)\n minimos(v*2+1) += lazyValue(v)\n\n lazyValue(v*2+2) += lazyValue(v)\n minimos(v*2+2) += lazyValue(v)\n\n }\n lazyValue(v) = 0\n }\n\n\n }\n\n\n private def update(v: Int, l: Int, r: Int, L: Int, R: Int, x: Long): Unit = {\n\n if(L < R){\n\n if(l == L && r == R){\n lazyValue(v) += x\n minimos(v) += x\n push(v,l,r)\n }else{\n\n push(v,l,r)\n val mid = (l+r)/2\n update(v*2+1,l,mid,L,Math.min(mid,R),x)\n update(v*2+2,mid,r,Math.max(mid,L),R,x)\n minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))\n\n }\n\n\n }\n\n }\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}"}], "src_uid": "0859ea756740bfa67b35fadfb194257e"} {"nl": {"description": "Bob is playing with $$$6$$$-sided dice. A net of such standard cube is shown below.He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.For example, the number of visible pips on the tower below is $$$29$$$ \u2014 the number visible on the top is $$$1$$$, from the south $$$5$$$ and $$$3$$$, from the west $$$4$$$ and $$$2$$$, from the north $$$2$$$ and $$$4$$$ and from the east $$$3$$$ and $$$5$$$.The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.Bob also has $$$t$$$ favourite integers $$$x_i$$$, and for every such integer his goal is to build such a tower that the number of visible pips is exactly $$$x_i$$$. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of favourite integers of Bob. The second line contains $$$t$$$ space-separated integers $$$x_i$$$ ($$$1 \\leq x_i \\leq 10^{18}$$$)\u00a0\u2014 Bob's favourite integers.", "output_spec": "For each of Bob's favourite integers, output \"YES\" if it is possible to build the tower, or \"NO\" otherwise (quotes for clarity).", "sample_inputs": ["4\n29 34 19 38"], "sample_outputs": ["YES\nYES\nYES\nNO"], "notes": "NoteThe first example is mentioned in the problem statement.In the second example, one can build the tower by flipping the top dice from the previous tower.In the third example, one can use a single die that has $$$5$$$ on top.The fourth example is impossible."}, "positive_code": [{"source_code": "object _1266B 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 x = io.read[Long]\n val ans = (15 to 20).exists(top => (x - top) >= 0 && (x - top)%14 == 0)\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"}], "negative_code": [{"source_code": "object _1266B 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 x = io.read[Long]\n val ans = 1 <= x%14 && x%14 <= 6\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"}], "src_uid": "840a4e16454290471faa5a27a3c795d9"} {"nl": {"description": "A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: \"fced\", \"xyz\", \"r\" and \"dabcef\". The following string are not diverse: \"az\", \"aa\", \"bad\" and \"babc\". Note that the letters 'a' and 'z' are not adjacent.Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).You are given a sequence of strings. For each string, if it is diverse, print \"Yes\". Otherwise, print \"No\".", "input_spec": "The first line contains integer $$$n$$$ ($$$1 \\le n \\le 100$$$), denoting the number of strings to process. The following $$$n$$$ lines contains strings, one string per line. Each string contains only lowercase Latin letters, its length is between $$$1$$$ and $$$100$$$, inclusive.", "output_spec": "Print $$$n$$$ lines, one line per a string in the input. The line should contain \"Yes\" if the corresponding string is diverse and \"No\" if the corresponding string is not diverse. You can print each letter in any case (upper or lower). For example, \"YeS\", \"no\" and \"yES\" are all acceptable.", "sample_inputs": ["8\nfced\nxyz\nr\ndabcef\naz\naa\nbad\nbabc"], "sample_outputs": ["Yes\nYes\nYes\nYes\nNo\nNo\nNo\nNo"], "notes": null}, "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": "/**\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"}, {"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"} {"nl": {"description": "Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \\leq k \\leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \\leq i \\leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^{5}$$$)\u00a0\u2014 the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-1 \\leq a_i \\leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \\cdot 10 ^ {5}$$$.", "output_spec": "Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \\leq k \\leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.", "sample_inputs": ["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"], "sample_outputs": ["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"], "notes": "NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$."}, "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 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"}, {"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"} {"nl": {"description": "Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message \u2014 string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully \"YAY!\", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says \"WHOOPS\".Tanya wants to make such message that lets her shout \"YAY!\" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says \"WHOOPS\". Your task is to help Tanya make the message.", "input_spec": "The first line contains line s (1\u2009\u2264\u2009|s|\u2009\u2264\u20092\u00b7105), consisting of uppercase and lowercase English letters \u2014 the text of Tanya's message. The second line contains line t (|s|\u2009\u2264\u2009|t|\u2009\u2264\u20092\u00b7105), consisting of uppercase and lowercase English letters \u2014 the text written in the newspaper. Here |a| means the length of the string a.", "output_spec": "Print two integers separated by a space: the first number is the number of times Tanya shouts \"YAY!\" while making the message, the second number is the number of times Tanya says \"WHOOPS\" while making the message. ", "sample_inputs": ["AbC\nDCbA", "ABC\nabc", "abacaba\nAbaCaBA"], "sample_outputs": ["3 0", "0 3", "3 4"], "notes": null}, "positive_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 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"}, {"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 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}"}], "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"} {"nl": {"description": "Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.", "input_spec": "The first line contains the integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the maximum number of sections which can be highlighted on the display.", "output_spec": "Print the maximum integer which can be shown on the display of Stepan's newest device.", "sample_inputs": ["2", "3"], "sample_outputs": ["1", "7"], "notes": null}, "positive_code": [{"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 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}"}, {"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}"}, {"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}"}], "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 \u306b break \u306e\u30ad\u30fc\u30ef\u30fc\u30c9\u306f\u306a\u3044\u3089\u3057\u3044...\n var i = 9\n while( i >= 0 ) {\n if( N >= cost( i ) ) { // [] \u3067\u306f\u306a\u304f () \u306a\u3093\u3067\u3059\u306d...\n print( i )\n N -= cost( i )\n i = -1 // break \u3068\u3059\u308b\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"} {"nl": {"description": "Polycarp has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.Determine the longest time segment when Polycarp can sleep, i.\u00a0e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of alarms. Each of the next n lines contains a description of one alarm. Each description has a format \"hh:mm\", where hh is the hour when the alarm rings, and mm is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary. Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i.\u00a0e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.", "output_spec": "Print a line in format \"hh:mm\", denoting the maximum time Polycarp can sleep continuously. hh denotes the number of hours, and mm denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.", "sample_inputs": ["1\n05:43", "4\n22:00\n03:21\n16:03\n09:59"], "sample_outputs": ["23:59", "06:37"], "notes": "NoteIn the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time."}, "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"}, {"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"} {"nl": {"description": "Blake is a CEO of a large company called \"Blake Technologies\". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.We define function f(x,\u2009l,\u2009r) as a bitwise OR of integers xl,\u2009xl\u2009+\u20091,\u2009...,\u2009xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a,\u2009l,\u2009r)\u2009+\u2009f(b,\u2009l,\u2009r) among all possible 1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n. ", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the length of the arrays. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line contains n integers bi (0\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "Print a single integer\u00a0\u2014 the maximum value of sum f(a,\u2009l,\u2009r)\u2009+\u2009f(b,\u2009l,\u2009r) among all possible 1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n.", "sample_inputs": ["5\n1 2 4 3 2\n2 3 3 12 1", "10\n13 2 7 11 8 4 9 8 5 1\n5 7 18 9 2 3 0 11 8 6"], "sample_outputs": ["22", "46"], "notes": "NoteBitwise OR of two non-negative integers a and b is the number c\u2009=\u2009a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.In the first sample, one of the optimal answers is l\u2009=\u20092 and r\u2009=\u20094, because f(a,\u20092,\u20094)\u2009+\u2009f(b,\u20092,\u20094)\u2009=\u2009(2 OR 4 OR 3)\u2009+\u2009(3 OR 3 OR 12)\u2009=\u20097\u2009+\u200915\u2009=\u200922. Other ways to get maximum value is to choose l\u2009=\u20091 and r\u2009=\u20094, l\u2009=\u20091 and r\u2009=\u20095, l\u2009=\u20092 and r\u2009=\u20094, l\u2009=\u20092 and r\u2009=\u20095, l\u2009=\u20093 and r\u2009=\u20094, or l\u2009=\u20093 and r\u2009=\u20095.In the second sample, the maximum value is obtained for l\u2009=\u20091 and r\u2009=\u20099."}, "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": "\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"}, {"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"} {"nl": {"description": "Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.Help Amr by choosing the smallest subsegment possible.", "input_spec": "The first line contains one number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the size of the array. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106), representing elements of the array.", "output_spec": "Output two integers l,\u2009r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), the beginning and the end of the subsegment chosen respectively. If there are several possible answers you may output any of them. ", "sample_inputs": ["5\n1 1 2 2 1", "5\n1 2 2 3 1", "6\n1 2 2 1 1 2"], "sample_outputs": ["1 5", "2 3", "1 5"], "notes": "NoteA subsegment B of an array A from l to r is an array of size r\u2009-\u2009l\u2009+\u20091 where Bi\u2009=\u2009Al\u2009+\u2009i\u2009-\u20091 for all 1\u2009\u2264\u2009i\u2009\u2264\u2009r\u2009-\u2009l\u2009+\u20091"}, "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 \u21d2 {\n val (x, i) = xi._1 \u2192 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 \u21d2 kv._2.counter)\n val best = beautyMap\n .filter(_._2.counter == maxElem._2.counter)\n .minBy(kv \u21d2 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 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"}, {"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 \u21d2 {\n val (x, i) = xi._1 \u2192 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 \u21d2 kv._2.counter)\n val best = beautyMap.filter(_._2 == maxElem._2).maxBy(kv \u21d2 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 \u21d2 {\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 \u21d2 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 \u21d2 {\n val (x, i) = xi._1 \u2192 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 \u21d2 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"} {"nl": {"description": "Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.", "input_spec": "The first line of the input contains two integers, n and w (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009w\u2009\u2264\u2009109)\u00a0\u2014 the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109, 1\u2009\u2264\u2009i\u2009\u2264\u20092n)\u00a0\u2014\u00a0the capacities of Pasha's tea cups in milliliters.", "output_spec": "Print a single real number \u2014 the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"], "sample_outputs": ["3", "18", "4.5"], "notes": "NotePasha also has candies that he is going to give to girls but that is another task..."}, "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"}, {"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"}], "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"} {"nl": {"description": "Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1,\u2009a2,\u2009...,\u2009an.While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1,\u2009b2,\u2009...,\u2009bn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.", "input_spec": "The first line contains three integers n, l, r (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) \u2014 the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.", "output_spec": "Print \"LIE\" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print \"TRUTH\" (without quotes).", "sample_inputs": ["5 2 4\n3 4 2 3 1\n3 2 3 4 1", "3 1 2\n1 2 3\n3 1 2", "4 2 4\n1 1 1 1\n1 1 1 1"], "sample_outputs": ["TRUTH", "LIE", "TRUTH"], "notes": "NoteIn the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]).In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother.In the third example for any values l and r there is a situation when Stepan said the truth."}, "positive_code": [{"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 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}"}, {"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 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"} {"nl": {"description": "There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091), such that ai\u2009+\u20091\u2009>\u2009ai.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of painting. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000), where ai means the beauty of the i-th painting.", "output_spec": "Print one integer\u00a0\u2014 the maximum possible number of neighbouring pairs, such that ai\u2009+\u20091\u2009>\u2009ai, after the optimal rearrangement.", "sample_inputs": ["5\n20 30 10 50 40", "4\n200 100 100 200"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first sample, the optimal order is: 10,\u200920,\u200930,\u200940,\u200950.In the second sample, the optimal order is: 100,\u2009200,\u2009100,\u2009200."}, "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": "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"}, {"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"} {"nl": {"description": "As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1\u2009\u2264\u2009fi\u2009\u2264\u2009n and fi\u2009\u2260\u2009i.We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20095000)\u00a0\u2014 the number of planes. The second line contains n integers f1,\u2009f2,\u2009...,\u2009fn (1\u2009\u2264\u2009fi\u2009\u2264\u2009n, fi\u2009\u2260\u2009i), meaning that the i-th plane likes the fi-th.", "output_spec": "Output \u00abYES\u00bb if there is a love triangle consisting of planes on Earth. Otherwise, output \u00abNO\u00bb. You can output any letter in lower case or in upper case.", "sample_inputs": ["5\n2 4 5 1 3", "5\n5 5 5 5 1"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.In second example there are no love triangles."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You can perform operations on it.In one operation you can replace any element of the array $$$a_i$$$ with $$$\\lfloor \\frac{a_i}{2} \\rfloor$$$, that is, by an integer part of dividing $$$a_i$$$ by $$$2$$$ (rounding down).See if you can apply the operation some number of times (possible $$$0$$$) to make the array $$$a$$$ become a permutation of numbers from $$$1$$$ to $$$n$$$\u00a0\u2014that is, so that it contains all numbers from $$$1$$$ to $$$n$$$, each exactly once.For example, if $$$a = [1, 8, 25, 2]$$$, $$$n = 4$$$, then the answer is yes. You could do the following: Replace $$$8$$$ with $$$\\lfloor \\frac{8}{2} \\rfloor = 4$$$, then $$$a = [1, 4, 25, 2]$$$. Replace $$$25$$$ with $$$\\lfloor \\frac{25}{2} \\rfloor = 12$$$, then $$$a = [1, 4, 12, 2]$$$. Replace $$$12$$$ with $$$\\lfloor \\frac{12}{2} \\rfloor = 6$$$, then $$$a = [1, 4, 6, 2]$$$. Replace $$$6$$$ with $$$\\lfloor \\frac{6}{2} \\rfloor = 3$$$, then $$$a = [1, 4, 3, 2]$$$. ", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014the number of test cases. Each test case contains exactly two lines. The first one contains an integer $$$n$$$ ($$$1 \\le n \\le 50$$$), the second one contains integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "For each test case, output on a separate line: YES if you can make the array $$$a$$$ become a permutation of numbers from $$$1$$$ to $$$n$$$, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["6\n\n4\n\n1 8 25 2\n\n2\n\n1 1\n\n9\n\n9 8 3 4 2 7 1 5 6\n\n3\n\n8 2 1\n\n4\n\n24 7 16 7\n\n5\n\n22 6 22 4 22"], "sample_outputs": ["YES\nNO\nYES\nNO\nNO\nYES"], "notes": "NoteThe first test case is explained in the text of the problem statement.In the second test case, it is not possible to get a permutation."}, "positive_code": [{"source_code": "import java.io._\r\nimport java.nio.file._\r\nimport java.util.StringTokenizer\r\nimport java.lang.System\r\n\r\nimport scala.+:\r\nimport scala.io.Codec\r\nimport scala.annotation.tailrec\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\r\n val pw = new PrintWriter(System.out, false)\r\n\r\n val t = sc.nextInt()\r\n var i = 0\r\n for (i <- 0 to (t-1)) {\r\n Solver.solve(sc, pw, i)\r\n }\r\n pw.flush()\r\n }\r\n}\r\n\r\n/**\r\n * Actual solution\r\n */\r\nobject Solver {\r\n def solve(sc: Scanner, pw: PrintWriter, testcast: Int): Unit = {\r\n val n = sc.nextInt()\r\n val L = sc.nextLine.split(\" \").map(Integer.parseInt _).toList.sorted.reverse\r\n \r\n collect(n, L, new Array[Boolean](n + 1)) match {\r\n case true => pw.println(\"YES\")\r\n case false => pw.println(\"NO\")\r\n }\r\n }\r\n\r\n def collect(n: Int, L: List[Int], used: Array[Boolean]): Boolean = {\r\n L match {\r\n case Nil => true\r\n case 0 :: _ => false\r\n case head :: tail if head > n || used(head) => collect(n, (head / 2) :: tail, used)\r\n case head :: tail => collect(n, tail, used.updated(head, true))\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scala implementation of a faster java.util.Scanner\r\n * See: http://codeforces.com/blog/entry/7018\r\n */\r\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\r\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\r\n def this(reader: Reader) = this(new BufferedReader(reader))\r\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\r\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\r\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\r\n def this(str: String) = this(new StringReader(str))\r\n\r\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\r\n private[this] var current: Option[StringTokenizer] = None\r\n\r\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\r\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\r\n current\r\n }\r\n\r\n /**\r\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\r\n * @see line() if you want the Java behaviour\r\n */\r\n def nextLine(): String = {\r\n current = None // reset\r\n reader.readLine()\r\n }\r\n def lineNumber: Int = reader.getLineNumber\r\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\r\n def nextString(): String = next()\r\n def nextChar(): Char = next().ensuring(_.length == 1).head\r\n def nextBoolean(): Boolean = next().toBoolean\r\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\r\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\r\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\r\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\r\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\r\n def nextFloat(): Float = next().toFloat\r\n def nextDouble(): Double = next().toDouble\r\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n override def close() = reader.close()\r\n}\r\n"}], "negative_code": [], "src_uid": "645459e0a41ec63b13648ea8dbe0f053"} {"nl": {"description": "Gerald plays the following game. He has a checkered field of size n\u2009\u00d7\u2009n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n\u2009-\u20091 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.", "input_spec": "The first line contains two space-separated integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20091000, 0\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) \u2014 the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns \u2014 from left to right from 1 to n.", "output_spec": "Print a single integer \u2014 the maximum points Gerald can earn in this game.", "sample_inputs": ["3 1\n2 2", "3 0", "4 3\n3 1\n3 2\n3 3"], "sample_outputs": ["0", "1", "1"], "notes": "NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4)."}, "positive_code": [{"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": "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"}, {"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": "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"} {"nl": {"description": "A sequence $$$a_1, a_2, \\dots, a_k$$$ is called an arithmetic progression if for each $$$i$$$ from $$$1$$$ to $$$k$$$ elements satisfy the condition $$$a_i = a_1 + c \\cdot (i - 1)$$$ for some fixed $$$c$$$.For example, these five sequences are arithmetic progressions: $$$[5, 7, 9, 11]$$$, $$$[101]$$$, $$$[101, 100, 99]$$$, $$$[13, 97]$$$ and $$$[5, 5, 5, 5, 5]$$$. And these four sequences aren't arithmetic progressions: $$$[3, 1, 2]$$$, $$$[1, 2, 4, 8]$$$, $$$[1, -1, 1, -1]$$$ and $$$[1, 2, 3, 3, 3]$$$.You are given a sequence of integers $$$b_1, b_2, \\dots, b_n$$$. Find any index $$$j$$$ ($$$1 \\le j \\le n$$$), such that if you delete $$$b_j$$$ from the sequence, you can reorder the remaining $$$n-1$$$ elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2\\cdot10^5$$$) \u2014 length of the sequence $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$-10^9 \\le b_i \\le 10^9$$$) \u2014 elements of the sequence $$$b$$$.", "output_spec": "Print such index $$$j$$$ ($$$1 \\le j \\le n$$$), so that if you delete the $$$j$$$-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.", "sample_inputs": ["5\n2 6 8 7 4", "8\n1 2 3 4 5 6 7 8", "4\n1 2 4 8"], "sample_outputs": ["4", "1", "-1"], "notes": "NoteNote to the first example. If you delete the $$$4$$$-th element, you can get the arithmetic progression $$$[2, 4, 6, 8]$$$.Note to the second example. The original sequence is already arithmetic progression, so you can delete $$$1$$$-st or last element and you will get an arithmetical progression again."}, "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[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\ncase class Entry(i: Int, v: 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val A = Array.ofDim[Entry](N)\n REP(N) { i =>\n A(i) = Entry(i, ni())\n }\n\n sort(A, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)\n })\n\n def test(s: Int, d: Int, del: Boolean): Option[Int] = {\n debug(s\"test($s, $d, $del)\")\n var prev = A(s).v\n var skip = -1\n TO(s + 1, N - 1) { i =>\n if (A(i).v - prev != d) {\n if (skip != -1 || !del) {\n return None\n } else {\n skip = A(i).i\n }\n } else {\n prev = A(i).v\n }\n }\n Some(skip)\n }\n\n test(0, A(1).v - A(0).v, del = true) orElse {\n if (N == 2) None\n else {\n test(1, A(2).v - A(1).v, del = false).map(_ => A(0).i).orElse(\n test(0, A(2).v - A(0).v, del = true)\n )\n }\n } match {\n case Some(i) =>\n val ans = if (i == -1) A(0).i + 1 else i + 1\n out.println(ans)\n\n case None => out.println(-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 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[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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n\n def test(s: Int, d: Int, del: Boolean): Option[Int] = {\n debug(s\"test($s, $d, $del)\")\n var prev = A(s)\n var skip = -1\n TO(s + 1, N - 1) { i =>\n if (A(i) - prev != d) {\n if (skip != -1 || !del) return None\n skip = i\n } else {\n prev = A(i)\n }\n }\n Some(skip)\n }\n\n test(0, A(1) - A(0), del = true) orElse {\n if (N == 2) None\n else {\n test(1, A(2) - A(1), del = false).map(_ => 0).orElse(\n test(0, A(2) - A(0), del = false).map(_ => 1)\n )\n }\n } match {\n case Some(i) =>\n val ans = if (i == -1) 1 else i + 1\n out.println(ans)\n\n case None => out.println(-1)\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[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\ncase class Entry(i: Int, v: 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val A = Array.ofDim[Entry](N)\n REP(N) { i =>\n A(i) = Entry(i, ni())\n }\n\n sort(A, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)\n })\n\n def test(s: Int, d: Int, del: Boolean): Option[Int] = {\n debug(s\"test($s, $d, $del)\")\n var prev = A(s).v\n var skip = -1\n TO(s + 1, N - 1) { i =>\n if (A(i).v - prev != d) {\n if (skip != -1 || !del) return None\n skip = A(i).i\n } else {\n prev = A(i).v\n }\n }\n Some(skip)\n }\n\n test(0, A(1).v - A(0).v, del = true) orElse {\n if (N == 2) None\n else {\n test(1, A(2).v - A(1).v, del = false).map(_ => A(0).i).orElse(\n test(0, A(2).v - A(0).v, del = true)\n )\n }\n } match {\n case Some(i) =>\n val ans = if (i == -1) 1 else i + 1\n out.println(ans)\n\n case None => out.println(-1)\n }\n }\n}"}], "src_uid": "6946f088e462d12da47419f492ad51ea"} {"nl": {"description": "You are given a string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in it no more than twice.Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.It can be shown that the answer always exists. If there are multiple answers, print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$)\u00a0\u2014 the number of testcases. Each testcase consists of a non-empty string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in the string no more than twice. The length of the string doesn't exceed $$$52$$$.", "output_spec": "For each testcase, print a single string. Every letter should appear in it the same number of times as it appears in string $$$s$$$. For each pair of letters that appear exactly twice, the distance between the letters in the pair should be the same. If there are multiple answers, print any of them.", "sample_inputs": ["3\n\noelhl\n\nabcdcba\n\nac"], "sample_outputs": ["hello\nababcdc\nac"], "notes": "NoteIn the first testcase of the example, the only letter that appears exactly twice is letter 'l'. You can rearrange the letters arbitrarily, since there are no distances to compare.In the second testcase of the example, the letters that appear exactly twice are 'a', 'b' and 'c'. Initially, letters 'a' are distance $$$6$$$ apart, letters 'b' are distance $$$4$$$ apart and letters 'c' are distance $$$2$$$ apart. They are not the same, so we have to rearrange the letters. After rearrangement, letters 'a' are distance $$$2$$$ apart, letters 'b' are distance $$$2$$$ apart and letters 'c' are distance $$$2$$$ apart. They are all the same, so the answer is valid.In the third testcase of the example, there are no letters that appear exactly twice. Thus, any rearrangement is valid. Including not changing the string at all."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "28102f75e0798960740e5a2625393c8f"} {"nl": {"description": "Alice received a set of Toy Train\u2122 from Bob. It consists of one train and a connected railway network of $$$n$$$ stations, enumerated from $$$1$$$ through $$$n$$$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $$$i$$$ is station $$$i+1$$$ if $$$1 \\leq i < n$$$ or station $$$1$$$ if $$$i = n$$$. It takes the train $$$1$$$ second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver $$$m$$$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $$$1$$$ through $$$m$$$. Candy $$$i$$$ ($$$1 \\leq i \\leq m$$$), now at station $$$a_i$$$, should be delivered to station $$$b_i$$$ ($$$a_i \\neq b_i$$$). The blue numbers on the candies correspond to $$$b_i$$$ values. The image corresponds to the $$$1$$$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.", "input_spec": "The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \\leq n \\leq 5\\,000$$$; $$$1 \\leq m \\leq 20\\,000$$$) \u2014 the number of stations and the number of candies, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq n$$$; $$$a_i \\neq b_i$$$) \u2014 the station that initially contains candy $$$i$$$ and the destination station of the candy, respectively.", "output_spec": "In the first and only line, print $$$n$$$ space-separated integers, the $$$i$$$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $$$i$$$.", "sample_inputs": ["5 7\n2 4\n5 1\n2 3\n3 4\n4 1\n5 3\n3 5", "2 3\n1 2\n1 2\n1 2"], "sample_outputs": ["10 9 10 10 9", "5 6"], "notes": "NoteConsider the second sample.If the train started at station $$$1$$$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $$$2$$$. This step takes $$$1$$$ second. Deliver the first candy. Proceed to station $$$1$$$. This step takes $$$1$$$ second. Load the second candy onto the train. Proceed to station $$$2$$$. This step takes $$$1$$$ second. Deliver the second candy. Proceed to station $$$1$$$. This step takes $$$1$$$ second. Load the third candy onto the train. Proceed to station $$$2$$$. This step takes $$$1$$$ second. Deliver the third candy. Hence, the train needs $$$5$$$ seconds to complete the tasks.If the train were to start at station $$$2$$$, however, it would need to move to station $$$1$$$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $$$5+1 = 6$$$ seconds."}, "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 C = Array.ofDim[Int](N)\n val last = Array.fill[Int](N)(-1)\n\n def dist(i: Int, j: Int): Int = (j + N - i) % N\n\n def compare(i: Int, j1: Int, j2: Int): Int = {\n Integer.compare(dist(i, j1), dist(i, j2))\n }\n\n REP(M) { _ =>\n val a, b = ni() - 1\n C(a) += 1\n\n // \u6700\u5f8c\u306b\u6301\u3061\u51fa\u3059\u98f4\u306f\u6642\u8a08\u56de\u308a\u3067\u3061\u304b\u3044\u3082\u306e\u304c\u3044\u3044\n if (last(a) == -1 || compare(a, b, last(a)) < 0) {\n last(a) = b\n }\n }\n\n debug(\"C\")\n debug(C)\n debug(\"last\")\n debug(last)\n\n case class Max(cnt: Int, dist: Int, j: Int)\n def comp(v1: Max, v2: Max): Int = {\n if (v1.cnt == v2.cnt) Integer.compare(v1.dist, v2.dist)\n else Integer.compare(v1.cnt, v2.cnt)\n }\n\n def findMx(i: Int): Max = {\n var mx: Max = null\n REP(N) { j =>\n val v = Max(C(j), dist(i, j), j)\n if (mx == null || comp(v, mx) > 0) {\n mx = v\n }\n }\n mx\n }\n\n val ans = ArrayBuffer[Int]()\n val loaded = Array.ofDim[Boolean](N) // \u4f7f\u3044\u7d42\u308f\u3063\u305f\u3089\u304b\u306a\u3089\u305a\u5168\u90e8false\u306b\u306a\u3063\u3066\u308b\uff01\u7d20\u6575\uff01\n REP(N) { i =>\n val Max(mx, _, mxIx) = findMx(i)\n\n debug(s\"i:$i mx:$mx mxIx:$mxIx\")\n\n // \u4e00\u756a\u6700\u5f8c\u306b\u98f4\u3092\u3068\u308b\u3068\u304d\u304b\u3089\u3061\u3087\u3046\u3069\u4e00\u5468\u524d\u304b\u3089\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u3059\u308b\n var move = max(-1, (mx - 2) * N + dist(i, mxIx)) // \u6700\u521d\u306b\uff11\u6b69\u9032\u3080\u306e\u3067-1\u304c\u4e0b\u9650\u306a\u306e\u304c\u59a5\u5f53\n var j = (i + move) % N\n var lastCandyLoaded = false\n var candyCnt = 0\n\n // \u7a4d\u3080\u98f4\u304c\u307e\u3060\u6b8b\u3063\u3066\u3044\u308b\u304b\u3001\u30ad\u30e3\u30f3\u30c7\u30a3\u3092\u307e\u3060\u7a4d\u3093\u3067\u3044\u308b\u306a\u3089\u5468\u56de\u3092\u3064\u3065\u3051\u308b\n while(!lastCandyLoaded || candyCnt > 0) {\n j = j + 1\n if (j >= N) j -= N\n move += 1\n val m = move / N + 1 // \u5468\u56de\n\n debug(s\"step $j $move m:$m\")\n\n // \u3053\u306e\u5468\u56de\u3067\u307e\u3060\u8f09\u305b\u308b\u30ad\u30e3\u30f3\u30c7\u30a3\u30fc\u304c\u6b8b\u3063\u3066\u3044\u308b\u306a\u3089\u8f09\u305b\u308b\u3002\u305f\u3060\u3057\u540c\u3058\u7a2e\u985e\u306a\u3089\u610f\u5473\u306a\u3044\u306e\u3067\u7121\u8996\u3059\u308b\n if (C(j) >= m && !loaded(last(j))) {\n debug(s\"load ${last(j)}\")\n loaded(last(j)) = true\n candyCnt += 1\n }\n\n // \u964d\u308d\u3059\n if (loaded(j)) {\n debug(s\"unload\")\n loaded(j) = false\n candyCnt -= 1\n }\n\n if (j == mxIx) lastCandyLoaded = true\n }\n\n ans += move\n }\n\n 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 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": [], "src_uid": "ecda736a0caa924ebd5f8f133586d542"} {"nl": {"description": "This problem is same as the next one, but has smaller constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \\ldots, u_n$$$ ($$$1 \\leq u_i \\leq 10$$$)\u00a0\u2014 the colors of the ribbons the cats wear. ", "output_spec": "Print a single integer $$$x$$$\u00a0\u2014 the largest possible streak of days.", "sample_inputs": ["13\n1 1 1 2 2 2 3 3 3 4 4 4 5", "5\n10 2 5 4 1", "1\n10", "7\n3 2 1 1 4 5 1", "6\n1 1 1 2 2 2"], "sample_outputs": ["13", "5", "1", "6", "5"], "notes": "NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"}, {"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"}], "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"} {"nl": {"description": "The life goes up and down, just like nice sequences. Sequence t1,\u2009t2,\u2009...,\u2009tn is called nice if the following two conditions are satisfied: ti\u2009<\u2009ti\u2009+\u20091 for each odd i\u2009<\u2009n; ti\u2009>\u2009ti\u2009+\u20091 for each even i\u2009<\u2009n. For example, sequences (2,\u20098), (1,\u20095,\u20091) and (2,\u20095,\u20091,\u2009100,\u200999,\u2009120) are nice, while (1,\u20091), (1,\u20092,\u20093) and (2,\u20095,\u20093,\u20092) are not.Bear Limak has a sequence of positive integers t1,\u2009t2,\u2009...,\u2009tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i\u2009<\u2009j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.", "input_spec": "The first line of the input contains one integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009150\u2009000)\u00a0\u2014 the length of the sequence. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u2009150\u2009000) \u2014 the initial sequence. It's guaranteed that the given sequence is not nice.", "output_spec": "Print the number of ways to swap two elements exactly once in order to get a nice sequence.", "sample_inputs": ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"], "sample_outputs": ["2", "1", "8", "0"], "notes": "NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2\u2009=\u20098 with t4\u2009=\u20097. Swap t1\u2009=\u20092 with t5\u2009=\u20097. In the second sample, there is only one way\u00a0\u2014 Limak should swap t1\u2009=\u2009200 with t4\u2009=\u200950."}, "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.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[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.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"}], "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//}\u0451\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"} {"nl": {"description": "Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\leq 200\\,000$$$)\u00a0\u2014 the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \\ldots, k_q$$$ ($$$1 \\leq k_i \\leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.", "output_spec": "Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.", "sample_inputs": ["5 5\n1 2 1 2 1\n3 10 1 1 1", "4 4\n1 2 3 4\n9 1 10 6"], "sample_outputs": ["3\n5\n4\n4\n3", "1\n4\n4\n1"], "notes": "NoteIn the first example: after the 1-st minute, the 1-st and 2-nd warriors die. after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5\u00a0\u2014 all warriors are alive. after the 3-rd minute, the 1-st warrior dies. after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1. after the 5-th minute, the 2-nd warrior dies. "}, "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val r = new Reader\n val n, q = r.read[Int]\n val as = r.read[Array[Long]](n).scanLeft(0L){ case (acc, a) => a + acc }\n val ks = r.read[Array[Long]](q)\n \n ks.foldLeft((0, 0L)) {\n case ((i, d), k) => {\n val kd = k + d\n if (as(n) <= kd) {\n println(n)\n (0, 0)\n } else {\n val j = lb(as(_) >= kd, i, n)\n if (as(j+1) == kd) {\n println(n-j-1)\n (j+1, kd)\n } else {\n println(n-j)\n (j, kd)\n }\n }\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\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": "23d69ae8b432111c4291e7b767443925"} {"nl": {"description": "You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \\&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \\&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \\&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \\&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.", "output_spec": "Print the answer to this problem in decimal notation modulo $$$998244353$$$.", "sample_inputs": ["4 4\n1010\n1101", "4 5\n1001\n10101"], "sample_outputs": ["12", "11"], "notes": "NoteThe algorithm for the first example: add to the answer $$$1010_2~ \\&~ 1101_2 = 1000_2 = 8_{10}$$$ and set $$$b := 110$$$; add to the answer $$$1010_2~ \\&~ 110_2 = 10_2 = 2_{10}$$$ and set $$$b := 11$$$; add to the answer $$$1010_2~ \\&~ 11_2 = 10_2 = 2_{10}$$$ and set $$$b := 1$$$; add to the answer $$$1010_2~ \\&~ 1_2 = 0_2 = 0_{10}$$$ and set $$$b := 0$$$. So the answer is $$$8 + 2 + 2 + 0 = 12$$$.The algorithm for the second example: add to the answer $$$1001_2~ \\&~ 10101_2 = 1_2 = 1_{10}$$$ and set $$$b := 1010$$$; add to the answer $$$1001_2~ \\&~ 1010_2 = 1000_2 = 8_{10}$$$ and set $$$b := 101$$$; add to the answer $$$1001_2~ \\&~ 101_2 = 1_2 = 1_{10}$$$ and set $$$b := 10$$$; add to the answer $$$1001_2~ \\&~ 10_2 = 0_2 = 0_{10}$$$ and set $$$b := 1$$$; add to the answer $$$1001_2~ \\&~ 1_2 = 1_2 = 1_{10}$$$ and set $$$b := 0$$$. So the answer is $$$1 + 8 + 1 + 0 + 1 = 11$$$."}, "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 val pow2 = Array.ofDim[Long](2e5.toInt + 1)\n pow2(0) = 1\n rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n val N, M = ni()\n val A = ns(N)\n val B = ns(M)\n\n val cum = Array.ofDim[Int](M + 1)\n rep(M) { i =>\n cum(i + 1) = cum(i) + (if (B(i) == '1') 1 else 0)\n }\n var ans = 0L\n val diff = M - N\n rep(N) { i =>\n val k = N - 1 - i\n if (A(i) == '1') {\n val cnt = if (i + 1 + diff >= 0) cum(i + 1 + diff) else 0\n ans = (ans + pow2(k) * cnt) % MOD\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}"}], "negative_code": [], "src_uid": "d2fe5a201d1ec20c5b32cd99b54e13d0"} {"nl": {"description": "Toad Zitz has an array of integers, each integer is between $$$0$$$ and $$$m-1$$$ inclusive. The integers are $$$a_1, a_2, \\ldots, a_n$$$.In one operation Zitz can choose an integer $$$k$$$ and $$$k$$$ indices $$$i_1, i_2, \\ldots, i_k$$$ such that $$$1 \\leq i_1 < i_2 < \\ldots < i_k \\leq n$$$. He should then change $$$a_{i_j}$$$ to $$$((a_{i_j}+1) \\bmod m)$$$ for each chosen integer $$$i_j$$$. The integer $$$m$$$ is fixed for all operations and indices.Here $$$x \\bmod y$$$ denotes the remainder of the division of $$$x$$$ by $$$y$$$.Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 300\\,000$$$)\u00a0\u2014 the number of integers in the array and the parameter $$$m$$$. The next line contains $$$n$$$ space-separated integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i < m$$$)\u00a0\u2014 the given array.", "output_spec": "Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print $$$0$$$. It is easy to see that with enough operations Zitz can always make his array non-decreasing.", "sample_inputs": ["5 3\n0 0 0 1 2", "5 7\n0 6 1 3 2"], "sample_outputs": ["0", "1"], "notes": "NoteIn the first example, the array is already non-decreasing, so the answer is $$$0$$$.In the second example, you can choose $$$k=2$$$, $$$i_1 = 2$$$, $$$i_2 = 5$$$, the array becomes $$$[0,0,1,3,3]$$$. It is non-decreasing, so the answer is $$$1$$$."}, "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(n, m) = readInts(2)\n val as = readInts(n)\n\n def can(lim: Long): Boolean = {\n var prev = 0L\n var ok = true\n for (a <- as) {\n val max = if (a + lim >= m && (a + lim) % m >= prev) prev\n else if (a < prev && a + lim >= prev) prev\n else a\n if (max < prev) ok = false\n prev = max\n }\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(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val res = binSearch(0, m)\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "16e9f127f58c7682d372863d1d6a3bf1"} {"nl": {"description": "You are given the array $$$a$$$ consisting of $$$n$$$ elements and the integer $$$k \\le n$$$.You want to obtain at least $$$k$$$ equal elements in the array $$$a$$$. In one move, you can make one of the following two operations: Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $$$a$$$ is $$$mn$$$ then you choose such index $$$i$$$ that $$$a_i = mn$$$ and set $$$a_i := a_i + 1$$$); take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $$$a$$$ is $$$mx$$$ then you choose such index $$$i$$$ that $$$a_i = mx$$$ and set $$$a_i := a_i - 1$$$). Your task is to calculate the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$ and the required number of equal elements. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer \u2014 the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.", "sample_inputs": ["6 5\n1 2 2 4 2 3", "7 5\n3 3 2 1 1 1 3"], "sample_outputs": ["3", "4"], "notes": null}, "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(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"}, {"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"} {"nl": {"description": "You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the sizes of arrays a and b. The second line contains n integers \u2014 the elements of array a (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line contains m integers \u2014 the elements of array b (\u2009-\u2009109\u2009\u2264\u2009bj\u2009\u2264\u2009109).", "output_spec": "Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.", "sample_inputs": ["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"], "sample_outputs": ["3 2 1 4", "4 2 4 2 5"], "notes": null}, "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": "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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!To compose a story, Stephen wrote out $$$n$$$ words consisting of the first $$$5$$$ lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.For example, the story consisting of three words \"bac\", \"aaada\", \"e\" is interesting (the letter 'a' occurs $$$5$$$ times, all other letters occur $$$4$$$ times in total). But the story consisting of two words \"aba\", \"abcde\" is not (no such letter that it occurs more than all other letters in total).You are given a sequence of $$$n$$$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $$$0$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of the words in the sequence. Then $$$n$$$ lines follow, each of them contains a word \u2014 a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i.\u2009e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$; the sum of the lengths of all words over all test cases doesn't exceed $$$4 \\cdot 10^5$$$.", "output_spec": "For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story.", "sample_inputs": ["6\n3\nbac\naaada\ne\n3\naba\nabcde\naba\n2\nbaba\nbaba\n4\nab\nab\nc\nbc\n5\ncbdca\nd\na\nd\ne\n3\nb\nc\nca"], "sample_outputs": ["3\n2\n0\n2\n3\n2"], "notes": "NoteIn the first test case of the example, all $$$3$$$ words can be used to make an interesting story. The interesting story is \"bac aaada e\".In the second test case of the example, the $$$1$$$-st and the $$$3$$$-rd words can be used to make an interesting story. The interesting story is \"aba aba\". Stephen can't use all three words at the same time.In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is $$$0$$$.In the fourth test case of the example, Stephen can use the $$$3$$$-rd and the $$$4$$$-th words to make an interesting story. The interesting story is \"c bc\"."}, "positive_code": [{"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 val dp = Map[Char, ArrayBuffer[Int]]()\r\n val chars = Array('a', 'b', 'c', 'd', 'e')\r\n val ans = Map[Char, Int]()\r\n chars.foreach(x => dp(x) = new ArrayBuffer[Int]())\r\n var str = \"\"\r\n for (tt <- 1 to t) {\r\n chars.foreach(x => dp(x).clear())\r\n val n = readInt()\r\n for (i <- 1 to n) {\r\n str = readString()\r\n chars.foreach(x => dp(x).append(2*str.count(_ == x)-str.length))\r\n }\r\n chars.foreach(x => dp(x) = dp(x).sortWith(_>_))\r\n chars.foreach(x => {\r\n var cnt = 0\r\n var po = 0\r\n while (po < n && cnt + dp(x)(po) > 0){\r\n cnt += dp(x)(po)\r\n po += 1\r\n }\r\n ans(x) = po\r\n })\r\n writer.println(ans.values.max)\r\n writer.flush()\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "18ac51a009c907fe8e4cd2bb8612da20"} {"nl": {"description": "This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions: The length of $$$t$$$ does not exceed the length of $$$s$$$. $$$t$$$ is a palindrome. There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( \"$$$+$$$\" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$. ", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$10^6$$$.", "output_spec": "For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.", "sample_inputs": ["5\na\nabcdfdcecba\nabbaxyzyx\ncodeforces\nacbba"], "sample_outputs": ["a\nabcdfdcba\nxyzyx\nc\nabba"], "notes": "NoteIn the first test, the string $$$s = $$$\"a\" satisfies all conditions.In the second test, the string \"abcdfdcba\" satisfies all conditions, because: Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$. It is a palindrome. \"abcdfdcba\" $$$=$$$ \"abcdfdc\" $$$+$$$ \"ba\", and \"abcdfdc\" is a prefix of $$$s$$$ while \"ba\" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string \"c\" is correct, because \"c\" $$$=$$$ \"c\" $$$+$$$ \"\" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is \"s\"."}, "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\n val M = 1000000009L\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)).reverse.find{d =>isPal(L+d,L)}.get\n\n\n\n val r1 = (0 to (N-2*L)).reverse.find{d =>isPal(L,L+d)}.get\n\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": [{"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)).reverse.find{d =>isPal(L+d,L)}.get\n\n\n\n val r1 = (0 to (N-2*L)).reverse.find{d =>isPal(L,L+d)}.get\n\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}"}], "src_uid": "beaccd2c0213a330538fe741d1f4b5bf"} {"nl": {"description": "Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special \u2014 it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.", "input_spec": "The first line of input contains two integers n and s (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009s\u2009\u2264\u20091000)\u00a0\u2014 the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1\u2009\u2264\u2009fi\u2009\u2264\u2009s, 1\u2009\u2264\u2009ti\u2009\u2264\u20091000)\u00a0\u2014 the floor and the time of arrival in seconds for the passenger number i.", "output_spec": "Print a single integer\u00a0\u2014 the minimum amount of time in seconds needed to bring all the passengers to floor 0.", "sample_inputs": ["3 7\n2 1\n3 8\n5 2", "5 10\n2 77\n3 33\n8 21\n9 12\n10 64"], "sample_outputs": ["11", "79"], "notes": "NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2\u2009+\u20092\u2009+\u20094\u2009+\u20091\u2009+\u20092\u2009=\u200911 seconds."}, "positive_code": [{"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": "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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "This problem is given in two editions, which differ exclusively in the constraints on the number $$$n$$$.You are given an array of integers $$$a[1], a[2], \\dots, a[n].$$$ A block is a sequence of contiguous (consecutive) elements $$$a[l], a[l+1], \\dots, a[r]$$$ ($$$1 \\le l \\le r \\le n$$$). Thus, a block is defined by a pair of indices $$$(l, r)$$$.Find a set of blocks $$$(l_1, r_1), (l_2, r_2), \\dots, (l_k, r_k)$$$ such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $$$(l_i, r_i)$$$ and $$$(l_j, r_j$$$) where $$$i \\neq j$$$ either $$$r_i < l_j$$$ or $$$r_j < l_i$$$. For each block the sum of its elements is the same. Formally, $$$$$$a[l_1]+a[l_1+1]+\\dots+a[r_1]=a[l_2]+a[l_2+1]+\\dots+a[r_2]=$$$$$$ $$$$$$\\dots =$$$$$$ $$$$$$a[l_k]+a[l_k+1]+\\dots+a[r_k].$$$$$$ The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $$$(l_1', r_1'), (l_2', r_2'), \\dots, (l_{k'}', r_{k'}')$$$ satisfying the above two requirements with $$$k' > k$$$. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.", "input_spec": "The first line contains integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the length of the given array. The second line contains the sequence of elements $$$a[1], a[2], \\dots, a[n]$$$ ($$$-10^5 \\le a_i \\le 10^5$$$).", "output_spec": "In the first line print the integer $$$k$$$ ($$$1 \\le k \\le n$$$). The following $$$k$$$ lines should contain blocks, one per line. In each line print a pair of indices $$$l_i, r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) \u2014 the bounds of the $$$i$$$-th block. You can print blocks in any order. If there are multiple answers, print any of them.", "sample_inputs": ["7\n4 1 2 2 1 5 3", "11\n-5 -4 -3 -2 -1 0 1 2 3 4 5", "4\n1 1 1 1"], "sample_outputs": ["3\n7 7\n2 3\n4 5", "2\n3 4\n1 1", "4\n4 4\n1 1\n2 2\n3 3"], "notes": null}, "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) //\u3000\u7d42\u7aef\u3067\u6607\u9806\u30bd\u30fc\u30c8\u3059\u308b\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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 // \u4f5c\u308b\u3068\u304d\u306bR\u9806\u306b\u306a\u308b\u3088\u3046\u306b\u3059\u308b\u3002id\u3092\u632f\u308b\u306e\u304c\u9006\u9806\u306a\u306e\u3067R\u3092\u9006\u9806\u3067\u30eb\u30fc\u30d7\u3059\u308b\n REP_r(N, 1) { r =>\n // L\u306f\u3069\u3046\u3067\u3082\u3044\u3044\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"}], "negative_code": [], "src_uid": "3e834f89ecedc5f210e680f24e40ba19"} {"nl": {"description": "You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \\dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \\le i \\le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible: initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$; $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$; $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$; $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$3 \\le n \\le 3 \\cdot 10^4$$$)\u00a0\u2014 the length of the array $$$a$$$. It is guaranteed that the number $$$n$$$ is divisible by $$$3$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 100$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$150\\,000$$$.", "output_spec": "For each test case, output one integer\u00a0\u2014 the minimum number of moves that must be made for the $$$a$$$ array to make it have balanced remainders.", "sample_inputs": ["4\n6\n0 2 5 5 4 8\n6\n2 0 2 1 0 0\n9\n7 1 3 4 2 10 3 9 6\n6\n0 1 2 3 4 5"], "sample_outputs": ["3\n1\n3\n0"], "notes": "NoteThe first test case is explained in the statements.In the second test case, you need to make one move for $$$i=2$$$.The third test case you need to make three moves: the first move: $$$i=9$$$; the second move: $$$i=9$$$; the third move: $$$i=2$$$. In the fourth test case, the values $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ initially equal to each other, so the array $$$a$$$ already has balanced remainders."}, "positive_code": [{"source_code": "import java.util.Scanner\nobject Main extends App{\n def compute: Int = {\n val n = scanner.nextInt()\n var count0 = 0\n var count1 = 0\n var count2 = 0\n for(i <- 0 to n - 1){\n val temp = scanner.nextInt()\n val remainder = temp % 3\n (temp % 3) match {\n case 0 => count0 += 1\n case 1 => count1 += 1\n case 2 => count2 += 1\n }\n }\n scanner.nextLine()\n var ans = 0\n if(count0 > n / 3) {\n if(count1 < n / 3){\n val temp = n / 3 - count1\n val r = Math.min(temp, count0 - n / 3)\n ans += r\n count0 -= r\n count1 += r\n }\n if(count2 < n / 3){\n val temp = n / 3 - count2\n val r = Math.min(temp, count0 - n / 3)\n ans += (2 * r)\n count0 -= r\n count2 += r\n }\n }\n if(count2 > n / 3) {\n if(count0 < n / 3){\n val temp = n / 3 - count0\n val r = Math.min(temp, count2 - n / 3)\n ans += r\n count2 -= r\n count0 += r\n }\n if(count1 < n / 3){\n val temp = n / 3 - count1\n val r = Math.min(temp, count2 - n / 3)\n ans += (2 * r)\n count2 -= r\n count1 += r\n }\n }\n if(count1 > n / 3){\n if(count2 < n / 3){\n val temp = n / 3 - count2\n val r = Math.min(temp, count1 - n / 3)\n ans += r\n count1 -= r\n count2 += r\n }\n if(count0 < n / 3){\n val temp = n / 3 - count0\n val r = Math.min(temp, count1 - n / 3)\n ans += (2 * r)\n count1 -= r\n count0 += r\n }\n }\n return ans\n }\n val scanner = new Scanner(System.in)\n val t = scanner.nextInt()\n for (i <- 0 to t - 1) {\n println(compute)\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\r\nobject Main extends App{\r\n def compute: Int = {\r\n val n = scanner.nextInt()\r\n var count0 = 0\r\n var count1 = 0\r\n var count2 = 0\r\n for(i <- 0 to n - 1){\r\n val temp = scanner.nextInt()\r\n val remainder = temp % 3\r\n (temp % 3) match {\r\n case 0 => count0 += 1\r\n case 1 => count1 += 1\r\n case 2 => count2 += 1\r\n }\r\n }\r\n scanner.nextLine()\r\n var ans = 0\r\n if(count0 > n / 3) {\r\n if(count1 < n / 3){\r\n val temp = n / 3 - count1\r\n val r = Math.min(temp, count0 - n / 3)\r\n ans += r\r\n count0 -= r\r\n }\r\n if(count2 < n / 3){\r\n val temp = n / 3 - count2\r\n val r = Math.min(temp, count0 - n / 3)\r\n ans += (2 * r)\r\n count0 -= r\r\n }\r\n }\r\n if(count2 > n / 3) {\r\n if(count1 < n / 3){\r\n val temp = n / 3 - count1\r\n val r = Math.min(temp, count2 - n / 3)\r\n ans += r\r\n count2 -= r\r\n }\r\n if(count0 < n / 3){\r\n val temp = n / 3 - count0\r\n val r = Math.min(temp, count2 - n / 3)\r\n ans += (2 * r)\r\n count2 -= r\r\n }\r\n }\r\n if(count1 > n / 3){\r\n ans += (count1 - n / 3)\r\n }\r\n return ans\r\n }\r\n val scanner = new Scanner(System.in)\r\n val t = scanner.nextInt()\r\n for (i <- 0 to t - 1) {\r\n println(compute)\r\n }\r\n}\r\n"}], "src_uid": "e0de8a6441614d1e41a53223b5fa576b"} {"nl": {"description": "Let's call some positive integer classy if its decimal representation contains no more than $$$3$$$ non-zero digits. For example, numbers $$$4$$$, $$$200000$$$, $$$10203$$$ are classy and numbers $$$4231$$$, $$$102306$$$, $$$7277420000$$$ are not.You are given a segment $$$[L; R]$$$. Count the number of classy integers $$$x$$$ such that $$$L \\le x \\le R$$$.Each testcase contains several segments, for each of them you are required to solve the problem separately.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 10^4$$$) \u2014 the number of segments in a testcase. Each of the next $$$T$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$1 \\le L_i \\le R_i \\le 10^{18}$$$).", "output_spec": "Print $$$T$$$ lines \u2014 the $$$i$$$-th line should contain the number of classy integers on a segment $$$[L_i; R_i]$$$.", "sample_inputs": ["4\n1 1000\n1024 1024\n65536 65536\n999999 1000001"], "sample_outputs": ["1000\n1\n0\n2"], "notes": null}, "positive_code": [{"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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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\u4ee5\u964d\u306e\u5024\u304c\u56fa\u5b9a\u306e\u5834\u5408\u300110^6\u4ee5\u4e0b\u306e\u5024\u3082\u5236\u9650\u3055\u308c\u308b\n REP(4 - len(q)) { i =>\n res += C(m)(i)\n }\n\n // x-1 \u4ee5\u4e0b\u306e\u306e\u5834\u5408\u306f10^6\u4ee5\u4e0b\u304c\u81ea\u7531\u306b\u306a\u308b\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\u4ee5\u964d\u306e\u5024\u304c\u56fa\u5b9a\u306e\u5834\u5408\u300110^12\u4ee5\u4e0b\u306e\u5024\u3082\u5236\u9650\u3055\u308c\u308b\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 \u4ee5\u4e0b\u306e\u306e\u5834\u5408\u306f10^6\u4ee5\u4e0b\u304c\u81ea\u7531\u306b\u306a\u308b\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 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\u4ee5\u5916\u306e\u6642k\u306e\u5024\u3092\u6e1b\u3089\u3059\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\u306e\u6574\u6570\u5024, \u6700\u5927\u6841\u306e\u5024)\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}"}], "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\u4ee5\u964d\u306e\u5024\u304c\u56fa\u5b9a\u306e\u5834\u5408\u300110^6\u4ee5\u4e0b\u306e\u5024\u3082\u5236\u9650\u3055\u308c\u308b\n REP(4 - len(q)) { i =>\n res += C(m)(i)\n }\n\n // x-1 \u4ee5\u4e0b\u306e\u306e\u5834\u5408\u306f10^6\u4ee5\u4e0b\u304c\u81ea\u7531\u306b\u306a\u308b\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\u4ee5\u964d\u306e\u5024\u304c\u56fa\u5b9a\u306e\u5834\u5408\u300110^6\u4ee5\u4e0b\u306e\u5024\u3082\u5236\u9650\u3055\u308c\u308b\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 \u4ee5\u4e0b\u306e\u306e\u5834\u5408\u306f10^6\u4ee5\u4e0b\u304c\u81ea\u7531\u306b\u306a\u308b\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\u4ee5\u964d\u306e\u5024\u304c\u56fa\u5b9a\u306e\u5834\u5408\u300110^6\u4ee5\u4e0b\u306e\u5024\u3082\u5236\u9650\u3055\u308c\u308b\n REP(4 - len(q)) { i =>\n res += C(m)(i)\n }\n\n // x-1 \u4ee5\u4e0b\u306e\u306e\u5834\u5408\u306f10^6\u4ee5\u4e0b\u304c\u81ea\u7531\u306b\u306a\u308b\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\u4ee5\u964d\u306e\u5024\u304c\u56fa\u5b9a\u306e\u5834\u5408\u300110^6\u4ee5\u4e0b\u306e\u5024\u3082\u5236\u9650\u3055\u308c\u308b\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 \u4ee5\u4e0b\u306e\u306e\u5834\u5408\u306f10^6\u4ee5\u4e0b\u304c\u81ea\u7531\u306b\u306a\u308b\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"} {"nl": {"description": "There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i\u2009+\u20091 are neighbours for all i from 1 to n\u2009-\u20091. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si\u00b7sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.", "input_spec": "The first line of the input contains two space-separated integers n and p (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20092\u2009\u2264\u2009p\u2009\u2264\u2009109)\u00a0\u2014 the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark\u00a0\u2014 two space-separated integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.", "output_spec": "Print a single real number \u2014 the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 2\n1 2\n420 421\n420420 420421", "3 5\n1 4\n2 3\n11 14"], "sample_outputs": ["4500.0", "0.0"], "notes": "NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0,\u2009s1,\u2009s2) each shark grows: (1,\u2009420,\u2009420420): note that s0\u00b7s1\u2009=\u2009420, s1\u00b7s2\u2009=\u2009176576400, and s2\u00b7s0\u2009=\u2009420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1,\u2009420,\u2009420421): now, the product s2\u00b7s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1,\u2009421,\u2009420420): total is 4000 (1,\u2009421,\u2009420421): total is 0. (2,\u2009420,\u2009420420): total is 6000. (2,\u2009420,\u2009420421): total is 6000. (2,\u2009421,\u2009420420): total is 6000. (2,\u2009421,\u2009420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money."}, "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"}, {"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}"}], "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"} {"nl": {"description": "In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma\u2009-\u2009mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.", "input_spec": "The first line contains positive number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of the servers. The second line contains the sequence of non-negative integers m1,\u2009m2,\u2009...,\u2009mn (0\u2009\u2264\u2009mi\u2009\u2264\u20092\u00b7104), where mi is the number of tasks assigned to the i-th server.", "output_spec": "Print the minimum number of seconds required to balance the load.", "sample_inputs": ["2\n1 6", "7\n10 11 10 11 10 11 11", "5\n1 2 3 4 5"], "sample_outputs": ["2", "0", "3"], "notes": "NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is: move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5); then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4); then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.There are $$$n$$$ solutions, the $$$i$$$-th of them should be tested on $$$a_i$$$ tests, testing one solution on one test takes $$$1$$$ second. The solutions are judged in the order from $$$1$$$ to $$$n$$$. There are $$$k$$$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.At any time moment $$$t$$$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $$$i$$$, then it is being tested on the first test from time moment $$$t$$$ till time moment $$$t + 1$$$, then on the second test till time moment $$$t + 2$$$ and so on. This solution is fully tested at time moment $$$t + a_i$$$, and after that the testing process immediately starts testing another solution.Consider some time moment, let there be exactly $$$m$$$ fully tested solutions by this moment. There is a caption \"System testing: $$$d$$$%\" on the page with solutions, where $$$d$$$ is calculated as$$$$$$d = round\\left(100\\cdot\\frac{m}{n}\\right),$$$$$$where $$$round(x) = \\lfloor{x + 0.5}\\rfloor$$$ is a function which maps every real to the nearest integer.Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $$$q$$$, and the caption says \"System testing: $$$q$$$%\". Find the number of interesting solutions.Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.", "input_spec": "The first line contains two positive integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 1000$$$, $$$1 \\le k \\le 100$$$) standing for the number of submissions and the number of testing processes respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 150$$$), where $$$a_i$$$ is equal to the number of tests the $$$i$$$-th submission is to be run on.", "output_spec": "Output the only integer\u00a0\u2014 the number of interesting submissions.", "sample_inputs": ["2 2\n49 100", "4 2\n32 100 33 1", "14 5\n48 19 6 9 50 20 3 42 38 43 36 21 44 6"], "sample_outputs": ["1", "2", "5"], "notes": "NoteConsider the first example. At time moment $$$0$$$ both solutions start testing. At time moment $$$49$$$ the first solution is fully tested, so at time moment $$$49.5$$$ the second solution is being tested on the test $$$50$$$, and the caption says \"System testing: $$$50$$$%\" (because there is one fully tested solution out of two). So, the second solution is interesting.Consider the second example. At time moment $$$0$$$ the first and the second solutions start testing. At time moment $$$32$$$ the first solution is fully tested, the third solution starts testing, the caption says \"System testing: $$$25$$$%\". At time moment $$$32 + 24.5 = 56.5$$$ the third solutions is being tested on test $$$25$$$, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment $$$32 + 33 = 65$$$, the fourth solution is fully tested at time moment $$$65 + 1 = 66$$$. The captions becomes \"System testing: $$$75$$$%\", and at time moment $$$74.5$$$ the second solution is being tested on test $$$75$$$. So, this solution is also interesting. Overall, there are two interesting solutions."}, "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, K = ni()\n val A = na(N)\n var p = 0\n val W = Array.ofDim[Int](K, 3) // (cur, size, pos)\n\n var m = -K // \u6700\u521d\u306b\u8aad\u307f\u8fbc\u3080\u5206\u6e1b\u3089\u3057\u3066\u304a\u304f\n val end = Array.ofDim[Boolean](K)\n val interesting = Array.ofDim[Boolean](N)\n var t = 0\n while(m < N) {\n REP(K) { i =>\n if (!end(i) && W(i)(0) >= W(i)(1)) {\n m += 1\n if (p == N) {\n end(i) = true\n debug(s\"$t m:$m\")\n } else {\n W(i)(0) = 1\n W(i)(1) = A(p) + 1\n W(i)(2) = p\n p += 1\n debug(s\"$t: p:$p\")\n }\n }\n }\n\n val caption = math.round(100.toDouble * m / N)\n// debug(s\"$t $caption\")\n REP(K) { i =>\n if (!end(i) && caption == W(i)(0)) {\n debug(s\"$t: caption:$caption ${W(i)(0)} ${W(i)(1)} ${W(i)(2)}\")\n interesting(W(i)(2)) = true\n }\n }\n\n REP(K) { i =>\n if (!end(i)) W(i)(0) += 1\n }\n t += 1\n }\n\n val ans = interesting.count(identity)\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": "b17eaccfd447b11c4f9297e3276a3ca9"} {"nl": {"description": "You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is a vertex number $$$1$$$.A tree is a connected undirected graph with $$$n-1$$$ edges.You are given $$$m$$$ queries. The $$$i$$$-th query consists of the set of $$$k_i$$$ distinct vertices $$$v_i[1], v_i[2], \\dots, v_i[k_i]$$$. Your task is to say if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices in the tree and the number of queries. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \\le u_i, v_i \\le n, u_i \\ne v_i$$$). It is guaranteed that the given edges form a tree. The next $$$m$$$ lines describe queries. The $$$i$$$-th line describes the $$$i$$$-th query and starts with the integer $$$k_i$$$ ($$$1 \\le k_i \\le n$$$) \u2014 the number of vertices in the current query. Then $$$k_i$$$ integers follow: $$$v_i[1], v_i[2], \\dots, v_i[k_i]$$$ ($$$1 \\le v_i[j] \\le n$$$), where $$$v_i[j]$$$ is the $$$j$$$-th vertex of the $$$i$$$-th query. It is guaranteed that all vertices in a single query are distinct. It is guaranteed that the sum of $$$k_i$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum\\limits_{i=1}^{m} k_i \\le 2 \\cdot 10^5$$$).", "output_spec": "For each query, print the answer \u2014 \"YES\", if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path and \"NO\" otherwise.", "sample_inputs": ["10 6\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n7 8\n7 9\n9 10\n4 3 8 9 10\n3 2 4 6\n3 2 1 5\n3 4 8 2\n2 6 10\n3 5 4 7"], "sample_outputs": ["YES\nYES\nYES\nYES\nNO\nNO"], "notes": "NoteThe picture corresponding to the example:Consider the queries.The first query is $$$[3, 8, 9, 10]$$$. The answer is \"YES\" as you can choose the path from the root $$$1$$$ to the vertex $$$u=10$$$. Then vertices $$$[3, 9, 10]$$$ belong to the path from $$$1$$$ to $$$10$$$ and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which also belongs to this path.The second query is $$$[2, 4, 6]$$$. The answer is \"YES\" as you can choose the path to the vertex $$$u=2$$$. Then the vertex $$$4$$$ has distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$6$$$ has distance $$$1$$$ to the vertex $$$2$$$ which belongs to this path.The third query is $$$[2, 1, 5]$$$. The answer is \"YES\" as you can choose the path to the vertex $$$u=5$$$ and all vertices of the query belong to this path.The fourth query is $$$[4, 8, 2]$$$. The answer is \"YES\" as you can choose the path to the vertex $$$u=9$$$ so vertices $$$2$$$ and $$$4$$$ both have distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which belongs to this path.The fifth and the sixth queries both have answer \"NO\" because you cannot choose suitable vertex $$$u$$$."}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, m = nextInt\n\n val adjs = {\n val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }\n for (_ <- 1 until n) {\n val u, v = nextInt - 1\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n adjBuilders.map(_.result())\n }\n\n val depths, parents, tIn, tOut = Array.fill(n)(0)\n var t = 0\n\n def dfs(u: Int, p: Int, depth: Int): Unit = {\n tIn(u) = t\n t += 1\n parents(u) = p\n depths(u) = depth\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != p) {\n dfs(v, u, depth + 1)\n }\n i += 1\n }\n tOut(u) = t\n t += 1\n }\n\n dfs(0, 0, 0)\n\n for (_ <- 1 to m) {\n val k = nextInt\n val vs = nextInts(k).map(_ - 1)\n val deepest = vs.maxBy(depths)\n val hasAll = vs.forall { v =>\n val p = parents(v)\n tIn(p) <= tIn(deepest) && tOut(p) >= tOut(deepest)\n }\n out.println(if (hasAll) \"YES\" else \"NO\")\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": "import scala.collection.mutable\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n \n val n, m = nextInt\n val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n for (_ <- 1 until n) {\n val u, v = nextInt - 1\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n val adjs = adjBuilders.map(_.result())\n\n val depths = Array.fill(n)(0)\n val pathSets = Array.ofDim[Set[Int]](n)\n\n def dfs(u: Int, p: Int, depth: Int, pathSet: Set[Int]): Unit = {\n //parents(u) = p\n depths(u) = depth\n var pathSetHere = pathSet\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != p) {\n pathSetHere += v\n }\n i += 1\n }\n pathSets(u) = pathSetHere\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (v != p) {\n dfs(v, u, depth + 1, pathSetHere)\n }\n i += 1\n }\n }\n\n dfs(0, -1, 0, Set(0))\n\n for (_ <- 1 to m) {\n val k = nextInt\n val vs = nextInts(k)\n var i = 0\n var node = 0\n while (i < vs.length) {\n val v = vs(i) - 1\n if (depths(v) > depths(node)) node = v\n i += 1\n }\n val pathSet = pathSets(node)\n val hasAll = vs.forall(pathSet)\n out.println(if (hasAll) \"YES\" else \"NO\")\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"}], "src_uid": "8dcf63e0e4584df7a471c84ce3ca8fe1"} {"nl": {"description": "Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak\u2009+\u20091 and ak\u2009-\u20091 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "Print a single integer \u2014 the maximum number of points that Alex can earn.", "sample_inputs": ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"], "sample_outputs": ["2", "4", "10"], "notes": "NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,\u20092,\u20092,\u20092]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points."}, "positive_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, 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": "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 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.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"}, {"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"}, {"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": "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": "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 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"}], "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"} {"nl": {"description": "Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves: Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$; Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$; Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example: Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$; Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the power of the stones.", "output_spec": "For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.", "sample_inputs": ["5\n5\n1 5 4 3 2\n8\n2 1 3 4 5 6 8 7\n8\n4 2 3 1 8 6 7 5\n4\n3 4 2 1\n4\n2 3 1 4"], "sample_outputs": ["2\n4\n5\n3\n2"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of round participants. Each of the next n lines contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20094126)\u00a0\u2014 the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.", "output_spec": "If the round is rated for sure, print \"rated\". If the round is unrated for sure, print \"unrated\". If it's impossible to determine whether the round is rated or not, print \"maybe\".", "sample_inputs": ["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"], "sample_outputs": ["rated", "unrated", "maybe"], "notes": "NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not."}, "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;\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}"}, {"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"} {"nl": {"description": "Screen resolution of Polycarp's monitor is $$$a \\times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \\le x < a, 0 \\le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows\u00a0\u2014 from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.", "input_spec": "In the first line you are given an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the test. In the next lines you are given descriptions of $$$t$$$ test cases. Each test case contains a single line which consists of $$$4$$$ integers $$$a, b, x$$$ and $$$y$$$ ($$$1 \\le a, b \\le 10^4$$$; $$$0 \\le x < a$$$; $$$0 \\le y < b$$$)\u00a0\u2014 the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $$$a+b>2$$$ (e.g. $$$a=b=1$$$ is impossible).", "output_spec": "Print $$$t$$$ integers\u00a0\u2014 the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.", "sample_inputs": ["6\n8 8 0 0\n1 10 0 3\n17 31 10 4\n2 1 0 0\n5 10 3 9\n10 10 4 8"], "sample_outputs": ["56\n6\n442\n1\n45\n80"], "notes": "NoteIn the first test case, the screen resolution is $$$8 \\times 8$$$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. "}, "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 (a,b,x,y) = (in.nextInt(),in.nextInt(),in.nextInt(),in.nextInt())\n val a0 = b*(x)\n val a1 = b*(a-x-1)\n val a2 = a*(y)\n val a3 = a*(b-y-1)\n out.println(List(a0,a1,a2,a3).max)\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": "ccb7b8c0c389ea771f666c236c1cba5f"} {"nl": {"description": "Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1,\u2009a2,\u2009...,\u2009an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1,\u2009b2,\u2009...,\u2009bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.", "input_spec": "The first line contains two numbers n and m\u00a0(2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the dimensions of the matrix. The second line contains n numbers a1,\u2009a2,\u2009...,\u2009an\u00a0(0\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the xor of all elements in row i. The third line contains m numbers b1,\u2009b2,\u2009...,\u2009bm\u00a0(0\u2009\u2264\u2009bi\u2009\u2264\u2009109), where bi is the xor of all elements in column i.", "output_spec": "If there is no matrix satisfying the given constraints in the first line, output \"NO\". Otherwise, on the first line output \"YES\", and then n rows of m numbers in each ci1,\u2009ci2,\u2009... ,\u2009cim\u00a0(0\u2009\u2264\u2009cij\u2009\u2264\u20092\u00b7109) \u2014 the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.", "sample_inputs": ["2 3\n2 9\n5 3 13", "3 3\n1 7 6\n2 15 12"], "sample_outputs": ["YES\n3 4 5\n6 7 8", "NO"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of training sessions. The second line contains n integers a1, a2, ..., an (0\u2009\u2264\u2009ai\u2009\u2264\u200910\u2009000)\u00a0\u2014 the number of teams that will be present on each of the days.", "output_spec": "If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print \"YES\" (without quotes) in the only line of output. Otherwise, print \"NO\" (without quotes).", "sample_inputs": ["4\n1 2 1 2", "3\n1 0 1"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days."}, "positive_code": [{"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 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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "This problem differs from one which was on the online contest.The sequence a1,\u2009a2,\u2009...,\u2009an is called increasing, if ai\u2009<\u2009ai\u2009+\u20091 for i\u2009<\u2009n.The sequence s1,\u2009s2,\u2009...,\u2009sk is called the subsequence of the sequence a1,\u2009a2,\u2009...,\u2009an, if there exist such a set of indexes 1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik\u2009\u2264\u2009n that aij\u2009=\u2009sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500) \u2014 the length of the first sequence. The second line contains n space-separated integers from the range [0,\u2009109] \u2014 elements of the first sequence. The third line contains an integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009500) \u2014 the length of the second sequence. The fourth line contains m space-separated integers from the range [0,\u2009109] \u2014 elements of the second sequence.", "output_spec": "In the first line output k \u2014 the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.", "sample_inputs": ["7\n2 3 1 6 5 4 6\n4\n1 3 5 6", "5\n1 2 0 2 1\n3\n1 0 1"], "sample_outputs": ["3\n3 5 6", "2\n0 1"], "notes": null}, "positive_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 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}"}, {"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"} {"nl": {"description": "While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i,\u2009j) such that ai\u2009\u2264\u2009aj and there are exactly k integers y such that ai\u2009\u2264\u2009y\u2009\u2264\u2009aj and y is divisible by x.In this problem it is meant that pair (i,\u2009j) is equal to (j,\u2009i) only if i is equal to j. For example pair (1,\u20092) is not the same as (2,\u20091).", "input_spec": "The first line contains 3 integers n,\u2009x,\u2009k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009x\u2009\u2264\u2009109,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009109), where n is the size of the array a and x and k are numbers from the statement. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of the array a.", "output_spec": "Print one integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["4 2 1\n1 3 5 7", "4 2 0\n5 3 1 7", "5 3 1\n3 3 3 3 3"], "sample_outputs": ["3", "4", "25"], "notes": "NoteIn first sample there are only three suitable pairs of indexes\u00a0\u2014 (1,\u20092),\u2009(2,\u20093),\u2009(3,\u20094).In second sample there are four suitable pairs of indexes(1,\u20091),\u2009(2,\u20092),\u2009(3,\u20093),\u2009(4,\u20094).In third sample every pair (i,\u2009j) is suitable, so the answer is 5\u2009*\u20095\u2009=\u200925."}, "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, x, k) = readInts(3)\n val as = readInts(n).sorted\n\n var res = 0L\n var r1, r2 = 0\n\n for (l <- as.indices) {\n val a = as(l)\n val from = (a - 1) / x\n while (r1 < n && (as(r1) < as(l) || as(r1) / x < from + k)) r1 += 1\n r2 = r1 max r2\n while (r2 < n && as(r2) / x <= from + k) r2 += 1\n res += (r2 - r1)\n }\n\n println(res)\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, x, k) = readInts(3)\n val as = readLongs(n)\n\n val untils = as.map(a => (a - 1) / x)\n val tos = as.map(a => a / x)\n//println(untils.mkString(\" \"))\n //println(tos.mkString(\" \"))\n val countByTo = tos.groupBy(identity).map {\n case (kk, v) => kk -> v.length.toLong\n }\n\n var res = 0L\n\n if (x == 1) {\n for {\n i <- as.indices\n } {\n val u = untils(i)\n //println(i, as(i), u, countByTo.get(k + u))\n if (k > 0) res += countByTo.getOrElse(k + u, 0L)\n }\n } else {\n for {\n i <- as.indices\n } {\n val u = untils(i)\n //println(i, as(i), u, countByTo.get(k + u))\n res += countByTo.getOrElse(k + u, 0L)\n }\n }\n\n println(res)\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, x, k) = readInts(3)\n val as = readInts(n).sorted\n\n var res = 0L\n var r1, r2 = 0\n\n for (l <- as.indices) {\n val a = as(l)\n val from = (a - 1) / x\n while (r1 < n && as(r1) / x < from + k) r1 += 1\n r2 = r1\n while (r2 < n && as(r2) / x <= from + k) r2 += 1\n res += (r2 - r1)\n }\n\n println(res)\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, x, k) = readInts(3)\n val as = readLongs(n)\n\n val untils = as.map(a => (a - 1) / x)\n val tos = as.map(a => a / x)\n//println(untils.mkString(\" \"))\n //println(tos.mkString(\" \"))\n val countByTo = tos.groupBy(identity).map {\n case (kk, v) => kk -> v.length.toLong\n }\n\n var res = 0L\n\n for {\n i <- as.indices\n } {\n val u = untils(i)\n res += countByTo.getOrElse(k + u, 0L)\n }\n\n println(res)\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, x, k) = readInts(3)\n val as = readInts(n)\n\n val untils = as.map(a => (a - 1) / x)\n val tos = as.map(a => a / x)\n\n val countByTo = tos.groupBy(identity).map {\n case (k, v) => k -> v.length\n }\n\n var res = 0L\n\n for {\n i <- as.indices\n } {\n val u = untils(i)\n res += countByTo.getOrElse(k + u, 0)\n }\n\n println(res)\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, x, k) = readInts(3)\n val as = readLongs(n)\n\n val untils = as.map(a => (a - 1) / x)\n val tos = as.map(a => a / x)\n//println(untils.mkString(\" \"))\n// println(tos.mkString(\" \"))\n val countByTo = tos.groupBy(identity).map {\n case (kk, v) => kk -> v.length.toLong\n }\n\n var res = 0L\n\n /*if (x == 1) {\n for {\n i <- as.indices\n } {\n val u = untils(i)\n //println(i, as(i), u, countByTo.get(k + u))\n if (k > 0) res += countByTo.getOrElse(k + u, 0L)\n }\n } else {*/\n for {\n i <- as.indices\n } {\n val u = untils(i)\n //println(i, as(i), u, countByTo.get(k + u))\n if (as(i) % x > 0 || k > 0) res += countByTo.getOrElse(k + u, 0L)\n }\n //}\n\n println(res)\n}\n"}], "src_uid": "6fbcc92541705a63666701238778a04a"} {"nl": {"description": "You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf cur = init ok = true for i = 1 to |s| res = res + 1 if s[i] == '+' cur = cur + 1 else cur = cur - 1 if cur < 0 ok = false break if ok breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The only lines of each test case contains string $$$s$$$ ($$$1 \\le |s| \\le 10^6$$$) consisting only of characters + and -. It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.", "output_spec": "For each test case print one integer \u2014 the value of the $$$res$$$ after the process ends.", "sample_inputs": ["3\n--+-\n---\n++--+-"], "sample_outputs": ["7\n9\n6"], "notes": null}, "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 s = readLine()\n\n val res = s.zipWithIndex\n .foldLeft((s.length.toLong, 0)) {\n case ((res, airbag), (c, i)) =>\n c match {\n case '+' => (res, airbag + 1)\n case '-' =>\n if (airbag > 0) (res, airbag - 1)\n else (res + i + 1, airbag)\n }\n }\n ._1\n\n println(res)\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 s = readLine()\n\n val res = s.zipWithIndex\n .foldLeft((s.length, 0)) {\n case ((res, airbag), (c, i)) =>\n c match {\n case '+' => (res, airbag + 1)\n case '-' =>\n if (airbag > 0) (res, airbag - 1)\n else (res + i + 1, airbag)\n }\n }\n ._1\n\n println(res)\n }\n}\n"}], "src_uid": "07eecfe948aa78623586b5e30e84e415"} {"nl": {"description": "The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1,\u2009p2,\u2009...,\u2009pn. You are to choose k pairs of integers: [l1,\u2009r1],\u2009[l2,\u2009r2],\u2009...,\u2009[lk,\u2009rk]\u00a0(1\u2009\u2264\u2009l1\u2009\u2264\u2009r1\u2009<\u2009l2\u2009\u2264\u2009r2\u2009<\u2009...\u2009<\u2009lk\u2009\u2264\u2009rk\u2009\u2264\u2009n;\u00a0ri\u2009-\u2009li\u2009+\u20091\u2009=\u2009m),\u2009in such a way that the value of sum is maximal possible. Help George to cope with the task.", "input_spec": "The first line contains three integers n, m and k (1\u2009\u2264\u2009(m\u2009\u00d7\u2009k)\u2009\u2264\u2009n\u2009\u2264\u20095000). The second line contains n integers p1,\u2009p2,\u2009...,\u2009pn (0\u2009\u2264\u2009pi\u2009\u2264\u2009109).", "output_spec": "Print an integer in a single line \u2014 the maximum possible value of sum.", "sample_inputs": ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"], "sample_outputs": ["9", "61"], "notes": null}, "positive_code": [{"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 data = in.next().split(' ').map(_.toInt)\n val psumR = Array.ofDim[Long](n + 1)\n (1 to n).foreach { i => psumR(i) = psumR(i - 1) + data(i - 1) }\n// println(psumR.mkString(\" \"))\n var prev = Array.ofDim[Long](n + 1)\n var current = Array.ofDim[Long](n + 1)\n var i = 1\n while (i <= k) {\n var j = m\n prev = current\n current = Array.ofDim[Long](n + 1)\n while (j <= n) {\n current(j) = Math.max(current(j - 1), prev(j - m) + psumR(j) - psumR(j - m))\n j += 1\n }\n// println(current.mkString(\" \"))\n i += 1\n }\n// println(current.mkString(\" \"))\n// println(dp.map(_.mkString(\" \")).mkString(\"\\n\"))\n println(current(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, k) = in.next().split(' ').map(_.toInt)\n val data = in.next().split(' ').map(_.toInt)\n val psumR = Array.ofDim[Long](n)\n psumR(0) = data.head\n (1 until n).foreach { i => psumR(i) = psumR(i - 1) + data(i) }\n val dp = Array.ofDim[Long](k + 1, n)\n (1 to k).foreach { i =>\n (1 until n).foreach { j =>\n if (i * m <= j)\n dp(i)(j) = Math.max(dp(i)(j - 1), dp(i - 1)(j - 1) + psumR(j) - psumR(j - m))\n }\n }\n println(dp(k)(n - 1))\n\n}\n"}], "src_uid": "ee3c228cc817536bf6c10ea4508d786f"} {"nl": {"description": "A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1,\u2009y1), and the distress signal came from the point (x2,\u2009y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx,\u2009vy) for the nearest t seconds, and then will change to (wx,\u2009wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x,\u2009y), while its own velocity relative to the air is equal to zero and the wind (ux,\u2009uy) is blowing, then after seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.", "input_spec": "The first line of the input contains four integers x1, y1, x2, y2 (|x1|,\u2009\u2009|y1|,\u2009\u2009|x2|,\u2009\u2009|y2|\u2009\u2264\u200910\u2009000)\u00a0\u2014 the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively. The second line contains two integers and t (0\u2009<\u2009v,\u2009t\u2009\u2264\u20091000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively. Next follow one per line two pairs of integer (vx,\u2009vy) and (wx,\u2009wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that and .", "output_spec": "Print a single real value\u00a0\u2014 the minimum time the rescuers need to get to point (x2,\u2009y2). You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["0 0 5 5\n3 2\n-1 -1\n-1 0", "0 0 0 1000\n100 1000\n-50 0\n50 0"], "sample_outputs": ["3.729935587093555327", "11.547005383792516398"], "notes": null}, "positive_code": [{"source_code": "import scala.collection._\n\nobject D 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(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-6) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-6) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1: Double, yDir: Double): Double = {\n val vy1 = yDir * Math.sqrt(sqr(vMax) - sqr(vx1))\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, Double.MaxValue)\n }\n\n def getMinT2(from: Double, to: Double, yDir: Double): Double = {\n var l = from\n var r = to\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1, yDir)\n val tr1 = compute(r1, yDir)\n if (math.abs(tl1 - tr1) < 1E-7) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n val t2 = getMinT2(-vMax, 0d, 1d) min getMinT2(-vMax, 0d, -1d) min getMinT2(0, vMax, 1d) min getMinT2(0, vMax, -1d)\n println(t2)\n }\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1: Double): Double = {\n val vy1 = Math.sqrt(sqr(vMax) - sqr(vx1))\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, 1e10)\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var l = 0d\n var r = vMax\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-9) {\n val t2 = compute((l + r) / 2d)\n println(t + t2)\n System.exit(0)\n }\n if (tl1 < tr1) r = r1\n else l = l1\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1s: Double): Double = {\n val vx1 = Math.sqrt(vx1s)\n val vy1 = Math.sqrt(sqr(vMax) - vx1s)\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, 1e10)\n }\n\n def getMinT2(vx1From: Double, vx2To: Double): Double = {\n var l = vx1From\n var r = vx2To\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-8) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var min = Double.MaxValue\n val n = 1\n val vMaxS = sqr(vMax)\n for (i <- 0 until n) {\n val vx1From = i * vMax / n\n val vx1To = (i + 1) * vMaxS / n\n val t2 = getMinT2(vx1From, vx1To)\n if (t2 < min) min = t2\n }\n println(min)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1: Double): Double = {\n val vy1 = Math.sqrt(sqr(vMax) - sqr(vx1))\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, Double.MaxValue)\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var l = 0d\n var r = vMax\n while (math.abs(r - l) > 1E-8) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (tl1 < tr1) r = r1\n else l = l1\n }\n val t2 = compute((l + r) / 2d)\n println(t + t2)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-7) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-7) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1s: Double): Double = {\n val vx1 = Math.sqrt(vx1s)\n val vy1 = Math.sqrt(sqr(vMax) - vx1s)\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, 1e8)\n }\n\n def getMinT2(vx1From: Double, vx2To: Double): Double = {\n var l = vx1From\n var r = vx2To\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-7) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var min = Double.MaxValue\n val n = 10000\n val vMaxS = sqr(vMax)\n for (i <- 0 until n) {\n val vx1From = i * vMax / n\n val vx1To = (i + 1) * vMaxS / n\n val t2 = getMinT2(vx1From, vx1To)\n if (t2 < min) min = t2\n }\n println(min)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1s: Double): Double = {\n val vx1 = Math.sqrt(vx1s)\n val vy1 = Math.sqrt(sqr(vMax) - vx1s)\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, Double.MaxValue)\n }\n\n def getMinT2(vx1From: Double, vx2To: Double): Double = {\n var l = vx1From\n var r = vx2To\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-8) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n val n = 1000\n val vMaxS = sqr(vMax)\n var min = getMinT2(0, vMaxS)\n for (i <- 0 until n) {\n val vx1From = i * vMax / n\n val vx1To = (i + 1) * vMaxS / n\n val t2 = getMinT2(vx1From, vx1To)\n if (t2 < min) min = t2\n }\n println(min)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1: Double): Double = {\n val vy1 = Math.sqrt(sqr(vMax) - sqr(vx1))\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, 1e10)\n }\n\n def getMinT2(vx1From: Double, vx2To: Double): Double = {\n var l = 0d\n var r = vMax\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-9) {\n val t2 = compute((l + r) / 2d)\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var min = Double.MaxValue\n val n = 10000\n for (i <- 0 until n) {\n val vx1From = i * vMax / n\n val vx1To = (i + 1) * vMax / n\n val t2 = getMinT2(vx1From, vx1To)\n if (t2 < min) min = t2\n }\n println(min)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-7) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-7) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1: Double, yDir: Double): Double = {\n val vy1 = yDir * Math.sqrt(sqr(vMax) - sqr(vx1))\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, 1e8)\n }\n\n def getMinT2(from: Double, to: Double, yDir: Double): Double = {\n var l = from\n var r = to\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1, yDir)\n val tr1 = compute(r1, yDir)\n if (math.abs(tl1 - tr1) < 1E-7) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n val t2 = getMinT2(-vMax, 0d, 1d) min getMinT2(-vMax, 0d, -1d) min getMinT2(0, vMax, 1d) min getMinT2(0, vMax, -1d)\n println(t2)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-8) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1s: Double): Double = {\n val vx1 = Math.sqrt(vx1s)\n val vy1 = Math.sqrt(sqr(vMax) - vx1s)\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, Double.MaxValue)\n }\n\n def getMinT2(vx1From: Double, vx2To: Double): Double = {\n var l = vx1From\n var r = vx2To\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-8) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var min = Double.MaxValue\n val n = 1\n val vMaxS = sqr(vMax)\n for (i <- 0 until n) {\n val vx1From = i * vMax / n\n val vx1To = (i + 1) * vMaxS / n\n val t2 = getMinT2(vx1From, vx1To)\n if (t2 < min) min = t2\n }\n println(min)\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 readDoubles(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toDouble) }\n\n val Array(x1, y1, x2, y2) = readDoubles(4)\n val Array(vMax, t) = readDoubles(2)\n val Array(vx, vy) = readDoubles(2)\n val Array(wx, wy) = readDoubles(2)\n\n def sqr(x: Double) = x * x\n\n def can1(t0: Double): Boolean = {\n sqr(x2 - x1 - t0 * vx) + sqr(y2 - y1 - t0 * vy) <= sqr(t0 * vMax)\n }\n\n def can2(x0: Double, y0: Double, t0: Double): Boolean = {\n sqr(x2 - x0 - t0 * wx) + sqr(y2 - y0 - t0 * wy) <= sqr(t0 * vMax)\n }\n\n @annotation.tailrec\n def binSearchD1(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-7) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can1(mid)) binSearchD1(mid, hi)\n else binSearchD1(lo, mid)\n }\n }\n\n @annotation.tailrec\n def binSearchD2(x0: Double, y0: Double, lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-7) lo\n else {\n val mid = (lo + hi) / 2d\n if (!can2(x0, y0, mid)) binSearchD2(x0, y0, mid, hi)\n else binSearchD2(x0, y0, lo, mid)\n }\n }\n\n def compute(vx1: Double): Double = {\n val vy1 = Math.sqrt(sqr(vMax) - sqr(vx1))\n val x0 = x1 + t * (vx1 + vx)\n val y0 = y1 + t * (vy1 + vy)\n binSearchD2(x0, y0, 0, 1e8)\n }\n\n def getMinT2(vx1From: Double, vx2To: Double): Double = {\n var l = -vMax\n var r = vMax\n while (true) {\n val l1 = l + (r - l) / 3d\n val r1 = r - (r - l) / 3d\n val tl1 = compute(l1)\n val tr1 = compute(r1)\n if (math.abs(tl1 - tr1) < 1E-7) {\n val t2 = (tl1 + tr1) / 2d\n return t + t2\n }\n if (tl1 < tr1) r = r1\n else l = l1\n }\n 0d\n }\n\n if (can1(t)) {\n val t1 = binSearchD1(0d, t)\n println(t1)\n } else {\n var min = Double.MaxValue\n val n = 1\n for (i <- 0 until n) {\n val vx1From = i * vMax / n\n val vx1To = (i + 1) * vMax / n\n val t2 = getMinT2(vx1From, vx1To)\n if (t2 < min) min = t2\n }\n println(min)\n }\n}\n"}], "src_uid": "b44c6836ee3d597a78d4b6b16ef1d4b3"} {"nl": {"description": "You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way: Choose any positive odd integer $$$x$$$ ($$$x > 0$$$) and replace $$$a$$$ with $$$a+x$$$; choose any positive even integer $$$y$$$ ($$$y > 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.", "sample_inputs": ["5\n2 3\n10 10\n2 4\n7 4\n9 3"], "sample_outputs": ["1\n0\n2\n2\n1"], "notes": "NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "fcd55a1ca29e96c05a3b65b7a8103842"} {"nl": {"description": "Let's assume that we are given a matrix b of size x\u2009\u00d7\u2009y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x\u2009\u00d7\u2009y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x\u2009+\u20091 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x\u2009+\u20091). Sereja has an n\u2009\u00d7\u2009m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?", "input_spec": "The first line contains two integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Each of the next n lines contains m integers \u2014 the elements of matrix a. The i-th line contains integers ai1,\u2009ai2,\u2009...,\u2009aim (0\u2009\u2264\u2009aij\u2009\u2264\u20091) \u2014 the i-th row of the matrix a.", "output_spec": "In the single line, print the answer to the problem \u2014 the minimum number of rows of matrix b.", "sample_inputs": ["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"], "sample_outputs": ["2", "3", "2"], "notes": "NoteIn the first test sample the answer is a 2\u2009\u00d7\u20093 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001"}, "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\n val lines = in.take(n).toList\n\n def count(matrix: List[String]): Int = {\n val candidate = matrix.take(matrix.length / 2)\n if (matrix.length % 2 == 0 && candidate.zip(matrix.drop(matrix.length / 2).reverse).forall(i => i._1 == i._2)) {\n count(candidate)\n } else matrix.length\n }\n\n\n println(count(lines))\n}"}], "negative_code": [], "src_uid": "90125e9d42c6dcb0bf3b2b5e4d0f845e"} {"nl": {"description": "Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. or (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1\u2009\u2009\u2264\u2009\u2009ui,\u2009\u2009vi\u2009\u2009\u2264\u2009\u2009n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.", "output_spec": "If it's impossible to split the graph between Pari and Arya as they expect, print \"-1\" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers\u00a0\u2014 the indices of vertices. Note that because of m\u2009\u2265\u20091, vertex cover cannot be empty.", "sample_inputs": ["4 2\n1 2\n2 3", "3 3\n1 2\n2 3\n1 3"], "sample_outputs": ["1\n2 \n2\n1 3", "-1"], "notes": "NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya."}, "positive_code": [{"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": "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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n\u2009+\u2009m. Then the number of integers i (1\u2009\u2264\u2009i\u2009<\u2009n\u2009+\u2009m) such that positions with indexes i and i\u2009+\u20091 contain children of different genders (position i has a girl and position i\u2009+\u20091 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.", "input_spec": "The single line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), separated by a space.", "output_spec": "Print a line of n\u2009+\u2009m characters. Print on the i-th position of the line character \"B\", if the i-th position of your arrangement should have a boy and \"G\", if it should have a girl. Of course, the number of characters \"B\" should equal n and the number of characters \"G\" should equal m. If there are multiple optimal solutions, print any of them.", "sample_inputs": ["3 3", "4 2"], "sample_outputs": ["GBGBGB", "BGBGBB"], "notes": "NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal."}, "positive_code": [{"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}"}, {"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 java.io.PrintWriter\nimport java.io.File\nimport java.util.Scanner\n\nobject test2 extends App {\n\tval sc=new Scanner(new File(\"input.txt\"))\n\tval out=new PrintWriter(\"output.txt\")\n\tval m=sc.nextInt\n\tval n=sc.nextInt\n\tif(m<=n)\n\t\tout.println(\"GB\"*m+\"G\"*(n-m))\n\telse\n out.println(\"BG\"*n+\"B\"*(m-n))\n out.close\n}\n\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 1) {\r\n c += 1\r\n ls -=1\r\n }\r\n else if (( ls == 1) && (ttt == 1) && (rs > 0)) {\r\n rs-=1\r\n c -= 1\r\n ttt-=1\r\n if (c<0) {\r\n t = false\r\n }\r\n }\r\n else if (ls == 1){\r\n c += 1\r\n ls -=1\r\n }\r\n else {\r\n rs-=1\r\n c -= 1\r\n if (c<0) {\r\n t = false\r\n }\r\n }\r\n }\r\n }\r\n if (cou == 0) {\r\n t = false\r\n }\r\n if (t) {\r\n println(\"NO\")\r\n }\r\n else println(\"YES\")\r\n }\r\n }\r\n}"}], "negative_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 s = tokenizer.nextToken()\r\n var t = true\r\n var r: Long = 0\r\n var l: Long = 0\r\n val len: Long = s.length\r\n val nn: Long = len / 2\r\n for (i <- s) {\r\n if (i.toString == \"(\") {\r\n l+=1\r\n }\r\n else if (i.toString == \")\") {\r\n r+=1\r\n }\r\n }\r\n var rs:Long = nn - r\r\n var ls:Long = nn-l\r\n var ri:Long = 0\r\n var le:Long = 0\r\n for (i <- s) {\r\n if (i.toString == \"(\") {\r\n le+=1\r\n }\r\n else if (i.toString == \")\") {\r\n ri+=1\r\n }\r\n else {\r\n if ((ri != le) && (rs > 0) && (ls > 0)){\r\n t = false\r\n ri +=1\r\n rs -=1\r\n }\r\n else if (ri == le) {\r\n ls -=1\r\n le +=1\r\n }\r\n else if (ls > 0) {\r\n ls -=1\r\n le +=1\r\n }\r\n else {\r\n ri +=1\r\n rs -=1\r\n }\r\n }\r\n }\r\n if (t) {\r\n println(\"YES\")\r\n }\r\n else println(\"NO\")\r\n }\r\n }\r\n}"}, {"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 s = tokenizer.nextToken()\r\n var t = true\r\n var r = 0\r\n var l = 0\r\n val len = s.length\r\n val nn = len / 2\r\n for (i <- s) {\r\n if (i.toString == \"(\") {\r\n l+=1\r\n }\r\n else if (i.toString == \")\") {\r\n r+=1\r\n }\r\n }\r\n var rs = nn - r\r\n var ls = nn-l\r\n var ri = 0\r\n var le = 0\r\n for (i <- s) {\r\n if (i.toString == \"(\") {\r\n le+=1\r\n }\r\n else if (i.toString == \")\") {\r\n ri+=1\r\n }\r\n else {\r\n if ((ri != le) && (rs > 0) && (ls > 0)){\r\n t = false\r\n ri +=1\r\n rs -=1\r\n }\r\n else if (ri == le) {\r\n ls -=1\r\n le +=1\r\n }\r\n else if (ls > 0) {\r\n ls -=1\r\n le +=1\r\n }\r\n else {\r\n ri +=1\r\n rs -=1\r\n }\r\n }\r\n }\r\n if (t) {\r\n println(\"YES\")\r\n }\r\n else println(\"NO\")\r\n }\r\n }\r\n}"}, {"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 s = tokenizer.nextToken()\r\n var t = true\r\n var r = 0\r\n var l = 0\r\n val len = s.length\r\n val nn = len / 2\r\n\r\n for (i <- s) {\r\n if (i.toString == \"(\") {\r\n l+=1\r\n }\r\n else if (i.toString == \")\") {\r\n r+=1\r\n }\r\n }\r\n var rs = nn - r\r\n var ls = nn-l\r\n var ri = 0\r\n var le = 0\r\n for (i <- s) {\r\n if (i.toString == \"(\") {\r\n le+=1\r\n }\r\n else if (i.toString == \")\") {\r\n ri+=1\r\n }\r\n else {\r\n if ((ri != le) && (rs > 0) && (ls > 0)){\r\n t = false\r\n ri +=1\r\n rs -=1\r\n }\r\n else if ((ri == le) || (ls > 0)) {\r\n ls -=1\r\n le +=1\r\n }\r\n else {\r\n ri +=1\r\n rs -=1\r\n }\r\n }\r\n }\r\n if (t) {\r\n println(\"YES\")\r\n }\r\n else println(\"NO\")\r\n }\r\n }\r\n}"}], "src_uid": "e630243546bf46757ba1acdbdfd475c2"} {"nl": {"description": "The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps.", "input_spec": "The first line of input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$x_0$$$ ($$$-10^{14} \\leq x_0 \\leq 10^{14}$$$) and $$$n$$$ ($$$0 \\leq n \\leq 10^{14}$$$)\u00a0\u2014 the coordinate of the grasshopper's initial position and the number of jumps.", "output_spec": "Print exactly $$$t$$$ lines. On the $$$i$$$-th line print one integer\u00a0\u2014 the answer to the $$$i$$$-th test case\u00a0\u2014 the coordinate of the point the grasshopper will be at after making $$$n$$$ jumps from the point $$$x_0$$$.", "sample_inputs": ["9\n0 1\n0 2\n10 10\n10 99\n177 13\n10000000000 987654321\n-433494437 87178291199\n1 0\n-1 1"], "sample_outputs": ["-1\n1\n11\n110\n190\n9012345679\n-87611785637\n1\n0"], "notes": "NoteThe first two test cases in the example correspond to the first two jumps from the point $$$x_0 = 0$$$. Since $$$0$$$ is an even number, the first jump of length $$$1$$$ is made to the left, and the grasshopper ends up at the point $$$0 - 1 = -1$$$.Then, since $$$-1$$$ is an odd number, a jump of length $$$2$$$ is made to the right, bringing the grasshopper to the point with coordinate $$$-1 + 2 = 1$$$."}, "positive_code": [{"source_code": "object _1607B 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 x, n = io.read[Long]\r\n val jump = (n%4 match {\r\n case 0 => 0\r\n case 1 => -n\r\n case 2 => 1\r\n case 3 => n+1\r\n }) * (if (x%2 == 0) 1 else -1)\r\n io.write(x + jump)\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": "dbe12a665c374ce3745e20b4a8262eac"} {"nl": {"description": "Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.Right now he has a map of some imaginary city with $$$n$$$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $$$u$$$ and $$$v$$$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $$$w$$$ that the original map has a tunnel between $$$u$$$ and $$$w$$$ and a tunnel between $$$w$$$ and $$$v$$$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 200\\,000$$$)\u00a0\u2014 the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\leq u_i, v_i \\leq n$$$, $$$u_i \\ne v_i$$$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $$$n$$$ stations and $$$n - 1$$$ tunnels form a tree.", "output_spec": "Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.", "sample_inputs": ["4\n1 2\n1 3\n1 4", "4\n1 2\n2 3\n3 4"], "sample_outputs": ["6", "7"], "notes": "NoteIn the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $$$6$$$.In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $$$(1, 4)$$$. For these two stations the distance is $$$2$$$."}, "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 V, U = Array.ofDim[Int](N - 1)\n rep(N - 1) { i =>\n V(i) = ni() - 1\n U(i) = ni() - 1\n }\n val t = packUGraph(N, V, U)\n val (_, p, q) = traceBfs(t)\n val sum = Array.ofDim[Long](2, 2) // \u30d1\u30b9\u306e\u9577\u3055 (\u5076\u5947) = (\u03a3len, \u03a31)\n val dp = Array.ofDim[Long](N, 2, 2) // \u6df1\u3055 \u5076\u5947 = (\u03a3depth, \u03a31)\n rep_r(N) { i =>\n val v = q(i)\n // v\u3092\u8ffd\u52a0\n dp(v)(0)(1) += 1\n\n t(v) foreach { u =>\n if (p(v) != u) {\n def cl(x: Int) = dp(v)(x)(1)\n def sl(x: Int) = dp(v)(x)(0)\n def cr(x: Int) = dp(u)(x)(1)\n def sr(x: Int) = dp(u)(x)(0) + cr(x) // \u500b\u6570*1\u3092\u8db3\u3059\n\n // u\u5074\u304c\uff11\u6df1\u304f\u306a\u308b\u306e\u3067\u5076\u5947\u304c\u53cd\u8ee2\u3059\u308b\n rep(2) { xl =>\n rep(2) { xr =>\n sum(xl ^ xr ^ 1)(0) += (sl(xl) * cr(xr) + sr(xr) * cl(xl))\n sum(xl ^ xr ^ 1)(1) += cl(xl) * cr(xr)\n }\n }\n\n // dp(v)\u306bdp(u)\u3092\u30de\u30fc\u30b8\u3059\u308b\n rep(2) { x =>\n // 1\u6df1\u304f\u306a\u308b\u306e\u3067\u53cd\u8ee2\u3059\u308b\n dp(v)(x)(0) += sr(x ^ 1)\n dp(v)(x)(1) += cr(x ^ 1)\n }\n }\n }\n }\n\n // { y = \u03a3(2a + 1): \u03a3(a + 1) = (y - cnt) / 2 + cnt }\n val ans = sum(0)(0) / 2 + (sum(1)(0) - sum(1)(1)) / 2 + sum(1)(1)\n out.println(ans)\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 /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: Array[Array[Int]]): (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, 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): 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": "274ae43b10bb15e270788d36590713c7"} {"nl": {"description": "And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is \"How about checking out the elevator?\".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then \u2014 to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m\u2009-\u20091, then to floor m\u2009-\u20092, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si\u2009=\u2009fi), then the time of arrival to the floor fi for this participant is considered equal to ti.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20092\u2009\u2264\u2009m\u2009\u2264\u2009108). Next n lines contain information about the participants in the form of three space-separated integers si fi ti (1\u2009\u2264\u2009si,\u2009fi\u2009\u2264\u2009m,\u20090\u2009\u2264\u2009ti\u2009\u2264\u2009108), described in the problem statement.", "output_spec": "Print n lines each containing one integer \u2014 the time of the arrival for each participant to the required floor.", "sample_inputs": ["7 4\n2 4 3\n1 2 0\n2 2 0\n1 2 1\n4 3 5\n1 2 2\n4 2 0", "5 5\n1 5 4\n1 3 1\n1 3 4\n3 1 5\n4 2 5"], "sample_outputs": ["9\n1\n0\n7\n10\n7\n5", "12\n10\n10\n8\n7"], "notes": "NoteLet's consider the first sample. The first participant starts at floor s\u2009=\u20092 by the time equal to t\u2009=\u20093. To get to the floor f\u2009=\u20094, he has to wait until the time equals 7, that's the time when the elevator will go upwards for the second time. Then the first participant should get on the elevator and go two floors up. In this case the first participant gets to the floor f at time equal to 9. The second participant starts at the time t\u2009=\u20090 on the floor s\u2009=\u20091, enters the elevator immediately, and arrives to the floor f\u2009=\u20092. The third participant doesn't wait for the elevator, because he needs to arrive to the same floor where he starts."}, "positive_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nobject P117A extends App {\n\n def r = readLine.split(\" \").map(_.toInt)\n var entries = ListBuffer[Array[Int]]()\n var Array(n, m) = r\n\n def time2stock(t: Int) = {\n val tmp = (t - 1) % (m - 1)\n if (((t - 1) / (m - 1)) % 2 == 0) 2 + tmp else m - 1 - tmp\n }\n\n def stock2time(start: Int, stock: Int) = {\n val currStock = time2stock(start)\n val direction = currStock < time2stock(start + 1)\n if (direction) {\n if (currStock <= stock) stock - currStock else m - currStock + m - stock\n } else {\n if (currStock >= stock) currStock - stock else currStock + stock - 2\n }\n }\n\n for (i <- 1 to n) {\n val Array(s, f, t) = r\n if (s == f) println(t)\n else {\n val arrival = stock2time(t, s) + t\n println(arrival + stock2time(arrival, f))\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable.ListBuffer\nobject P117A extends App {\n\n def r = readLine.split(\" \").map(_.toInt)\n var entries = ListBuffer[Array[Int]]()\n var Array(n, m) = r\n\n def time2stock(t: Int) = {\n val tmp = (t - 1) % (m - 1)\n if (((t - 1) / (m - 1)) % 2 == 0) 2 + tmp else m - 1 - tmp\n }\n\n def stock2time(start: Int, stock: Int) = {\n val currStock = time2stock(start)\n val direction = currStock < time2stock(start + 1)\n if (direction) {\n if (currStock <= stock) stock - currStock else m - currStock + m - stock - 1\n } else {\n if (currStock >= stock) currStock - stock else currStock + stock - 2\n }\n }\n\n for (i <- 1 to n) {\n val Array(s, f, t) = r\n if (s == f) println(0)\n else {\n val arrival = stock2time(t, s) + t\n println(arrival + stock2time(arrival, f))\n }\n }\n}"}, {"source_code": "import scala.collection.mutable.ListBuffer\nobject P117A extends App {\n\n def r = readLine.split(\" \").map(_.toInt)\n var entries = ListBuffer[Array[Int]]()\n var Array(n, m) = r\n\n def time2stock(t: Int) = {\n val tmp = (t - 1) % (m - 1)\n if (((t - 1) / (m - 1)) % 2 == 0) 2 + tmp else m - 1 - tmp\n }\n\n def stock2time(start: Int, stock: Int) = {\n val currStock = time2stock(start)\n val direction = currStock < time2stock(start + 1)\n if (direction) {\n if (currStock <= stock) stock - currStock else m - currStock + m - stock\n } else {\n if (currStock >= stock) currStock - stock else currStock + stock - 2\n }\n }\n\n for (i <- 1 to n) {\n val Array(s, f, t) = r\n if (s == f) println(0)\n else {\n val arrival = stock2time(t, s) + t\n println(arrival + stock2time(arrival, f))\n }\n }\n}"}], "src_uid": "b8321b0a3fc8c295182a4c2c8d2e9d01"} {"nl": {"description": "Vasya has a tree consisting of $$$n$$$ vertices with root in vertex $$$1$$$. At first all vertices has $$$0$$$ written on it.Let $$$d(i, j)$$$ be the distance between vertices $$$i$$$ and $$$j$$$, i.e. number of edges in the shortest path from $$$i$$$ to $$$j$$$. Also, let's denote $$$k$$$-subtree of vertex $$$x$$$ \u2014 set of vertices $$$y$$$ such that next two conditions are met: $$$x$$$ is the ancestor of $$$y$$$ (each vertex is the ancestor of itself); $$$d(x, y) \\le k$$$. Vasya needs you to process $$$m$$$ queries. The $$$i$$$-th query is a triple $$$v_i$$$, $$$d_i$$$ and $$$x_i$$$. For each query Vasya adds value $$$x_i$$$ to each vertex from $$$d_i$$$-subtree of $$$v_i$$$.Report to Vasya all values, written on vertices of the tree after processing all queries.", "input_spec": "The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 3 \\cdot 10^5$$$) \u2014 number of vertices in the tree. Each of next $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x, y \\le n$$$) \u2014 edge between vertices $$$x$$$ and $$$y$$$. It is guarantied that given graph is a tree. Next line contains single integer $$$m$$$ ($$$1 \\le m \\le 3 \\cdot 10^5$$$) \u2014 number of queries. Each of next $$$m$$$ lines contains three integers $$$v_i$$$, $$$d_i$$$, $$$x_i$$$ ($$$1 \\le v_i \\le n$$$, $$$0 \\le d_i \\le 10^9$$$, $$$1 \\le x_i \\le 10^9$$$) \u2014 description of the $$$i$$$-th query.", "output_spec": "Print $$$n$$$ integers. The $$$i$$$-th integers is the value, written in the $$$i$$$-th vertex after processing all queries.", "sample_inputs": ["5\n1 2\n1 3\n2 4\n2 5\n3\n1 1 1\n2 0 10\n4 10 100", "5\n2 3\n2 1\n5 4\n3 4\n5\n2 0 4\n3 10 1\n1 2 3\n2 3 10\n1 1 7"], "sample_outputs": ["1 11 1 100 0", "10 24 14 11 11"], "notes": "NoteIn the first exapmle initial values in vertices are $$$0, 0, 0, 0, 0$$$. After the first query values will be equal to $$$1, 1, 1, 0, 0$$$. After the second query values will be equal to $$$1, 11, 1, 0, 0$$$. After the third query values will be equal to $$$1, 11, 1, 100, 0$$$."}, "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 (from, to) = na2(N - 1, -1)\n val t = packUGraph(N, from, to)\n val (depth, parent, bfs) = traceBfs(t)\n val deepest = depth(bfs(N - 1))\n\n val M = ni()\n\n case class Query(d: Int, x: Int)\n val Q = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())\n rep(M) { i =>\n val v = ni() - 1\n val d, x = ni()\n Q(v) += Query(d, x)\n }\n\n val adds = new BIT(deepest + 1)\n val ans = Array.ofDim[Long](N)\n\n case class Visit(v: Int) {\n var flg = false\n }\n\n val queue = new java.util.Stack[Visit]()\n queue.push(Visit(0))\n while(!queue.isEmpty) {\n val v = queue.peek()\n\n if (v.flg) {\n rep(Q(v.v).length) { i =>\n val q = Q(v.v)(i)\n adds.add(min(deepest, q.d + depth(v.v)), -q.x)\n }\n queue.pop()\n } else {\n v.flg = true\n rep(Q(v.v).length) { i =>\n val q = Q(v.v)(i)\n adds.add(min(q.d + depth(v.v), deepest), q.x)\n }\n\n ans(v.v) = adds.sum(deepest) - (if (depth(v.v) > 0) adds.sum(depth(v.v) - 1) else 0)\n\n t(v.v).foreach { u =>\n if (u != parent(v.v)) {\n queue.push(Visit(u))\n }\n }\n }\n }\n\n out.println(ans.mkString(\" \"))\n\n }\n\n /**\n * @param n \u30ce\u30fc\u30c9\u6570\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 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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "ac8d0c55535718cff3a8b0cb59ec43a2"} {"nl": {"description": "According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n. ", "output_spec": "Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.", "sample_inputs": ["3\n3 1 2", "5\n4 5 1 2 3"], "sample_outputs": ["3\n\u00a0\n2 1", "5 4\n\u00a0\n\u00a0\n3 2 1"], "notes": "NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\n/**\n * @author traff\n */\n\nobject Main extends App {\n val n = StdIn.readLine().toInt\n\n val a = StdIn.readLine().split(\" \").map(_.toInt)\n\n var i = n\n\n var m = mutable.HashSet[Int]()\n\n for (j <- 1 to n) {\n if (a(j-1) == i) {\n print(a(j-1))\n i-=1\n while (m.contains(i)) {\n print(s\" $i\")\n m.remove(i)\n i-=1\n }\n\n } else {\n m.add(a(j-1))\n }\n println()\n }\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\n\nobject Task1 extends App {\n var pos = 0\n val n = readInt()\n val rawData = readLine()\n val intArray = rawData.split(\" \").map(x => 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"} {"nl": {"description": "Sereja has a bracket sequence s1,\u2009s2,\u2009...,\u2009sn, or, in other words, a string s of length n, consisting of characters \"(\" and \")\".Sereja needs to answer m queries, each of them is described by two integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli,\u2009sli\u2009+\u20091,\u2009...,\u2009sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.", "input_spec": "The first line contains a sequence of characters s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009n\u2009\u2264\u2009106) without any spaces. Each character is either a \"(\" or a \")\". The second line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) \u2014 the description of the i-th query.", "output_spec": "Print the answer to each question on a single line. Print the answers in the order they go in the input.", "sample_inputs": ["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"], "sample_outputs": ["0\n0\n2\n10\n4\n6\n6"], "notes": "NoteA subsequence of length |x| of string s\u2009=\u2009s1s2... s|s| (where |s| is the length of string s) is string x\u2009=\u2009sk1sk2... sk|x| (1\u2009\u2264\u2009k1\u2009<\u2009k2\u2009<\u2009...\u2009<\u2009k|x|\u2009\u2264\u2009|s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters \"1\" and \"+\" between the characters of the string. For example, bracket sequences \"()()\", \"(())\" are correct (the resulting expressions \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.For the third query required sequence will be \u00ab()\u00bb.For the fourth query required sequence will be \u00ab()(())(())\u00bb."}, "positive_code": [{"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}"}, {"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 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}"}], "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"} {"nl": {"description": "You are given a sequence of $$$n$$$ digits $$$d_1d_2 \\dots d_{n}$$$. You need to paint all the digits in two colors so that: each digit is painted either in the color $$$1$$$ or in the color $$$2$$$; if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10000$$$) \u2014 the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) \u2014 the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \\dots d_{n}$$$ ($$$0 \\le d_i \\le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values \u200b\u200bof $$$n$$$ for all test cases in the input does not exceed $$$2\\cdot10^5$$$.", "output_spec": "Print $$$t$$$ lines \u2014 the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \\dots t_n$$$ ($$$1 \\le t_i \\le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign).", "sample_inputs": ["5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987"], "sample_outputs": ["121212211211\n1\n222222222\n21\n-"], "notes": "NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve2(): Unit = {\n val N = ni()\n val D = ns(N).map(_-'0')\n def isSorted2(as: ArrayBuffer[Int]): Boolean = {\n REP(as.length - 1) { i =>\n if (as(i) > as(i + 1)) return false\n }\n true\n }\n\n def isSorted(ones: ArrayBuffer[Int], twos: ArrayBuffer[Int]): Boolean = {\n isSorted2(ones) && isSorted2(twos) && {\n ones.isEmpty || twos.isEmpty || ones.last <= twos.head\n }\n }\n\n def showResult(med: Int, lastOneIx: Int): Unit = {\n val A = Array.ofDim[Int](N)\n REP(N) { i =>\n A(i) = if (D(i) < med) 1\n else if(D(i) > med) 2\n else {\n if (i < lastOneIx) 2 else 1\n }\n }\n out.println(A.mkString)\n }\n\n val ones, twos = ArrayBuffer[Int]()\n REP(10) { med =>\n ones.clear()\n twos.clear()\n var lastOneIx = -1\n REP(N) { i =>\n if (D(i) < med) {\n ones += D(i)\n lastOneIx = i\n }\n }\n TO(if (lastOneIx != - 1) lastOneIx + 1 else 0, N - 1) { i =>\n if (D(i) == med) ones += D(i)\n }\n REP(N) { i =>\n if (D(i) > med || D(i) == med && i < lastOneIx) {\n twos += D(i)\n }\n }\n debug(s\"med:$med\")\n debug(ones.mkString(\" \"))\n debug(twos.mkString(\" \"))\n if (isSorted(ones, twos)) {\n debug(s\"med:$med lastOneIx:$lastOneIx\")\n showResult(med, lastOneIx)\n return\n }\n }\n out.println(\"-\")\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve2(): Unit = {\n val N = ni()\n val D = ns(N).map(_-'0')\n def isSorted2(as: ArrayBuffer[Int]): Boolean = {\n REP(as.length - 1) { i =>\n if (as(i) > as(i + 1)) return false\n }\n true\n }\n\n def isSorted(ones: ArrayBuffer[Int], twos: ArrayBuffer[Int]): Boolean = {\n isSorted2(ones) && isSorted2(twos) && {\n ones.isEmpty || twos.isEmpty || ones.last <= twos.head\n }\n }\n\n def showResult(med: Int, oneMxIx: Int): Unit = {\n val A = Array.ofDim[Int](N)\n REP(N) { i =>\n A(i) = if (D(i) < med) 1\n else if(D(i) > med) 2\n else {\n if (i < oneMxIx) 2 else 1\n }\n }\n out.println(A.mkString)\n }\n\n val ones, twos = ArrayBuffer[Int]()\n REP(10) { med =>\n ones.clear()\n twos.clear()\n var oneMx = -1\n var oneMxIx = -1\n REP(N) { i =>\n if (D(i) < med) {\n ones += D(i)\n if (D(i) > oneMx) {\n oneMx = D(i)\n oneMxIx = i\n }\n }\n }\n if (oneMxIx != -1) {\n TO(oneMxIx + 1, N - 1) { i =>\n if (D(i) == med) ones += D(i)\n }\n }\n REP(N) { i =>\n if (D(i) > med || D(i) == med && i < oneMxIx) {\n twos += D(i)\n }\n }\n debug(ones.mkString(\" \"))\n debug(twos.mkString(\" \"))\n if (isSorted(ones, twos)) {\n showResult(med, oneMxIx)\n return\n }\n }\n out.println(\"-\")\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve2(): Unit = {\n val N = ni()\n val D = ns(N).map(_-'0')\n def isSorted2(as: ArrayBuffer[Int]): Boolean = {\n REP(as.length - 1) { i =>\n if (as(i) > as(i + 1)) return false\n }\n true\n }\n\n def isSorted(ones: ArrayBuffer[Int], twos: ArrayBuffer[Int]): Boolean = {\n isSorted2(ones) && isSorted2(twos) && {\n ones.isEmpty || twos.isEmpty || ones.last <= twos.head\n }\n }\n\n def showResult(med: Int, oneMxIx: Int): Unit = {\n val A = Array.ofDim[Int](N)\n REP(N) { i =>\n A(i) = if (D(i) < med) 1\n else if(D(i) > med) 2\n else {\n if (i < oneMxIx) 2 else 1\n }\n }\n out.println(A.mkString)\n }\n\n val ones, twos = ArrayBuffer[Int]()\n REP(10) { med =>\n ones.clear()\n twos.clear()\n var oneMx = -1\n var oneMxIx = -1\n REP(N) { i =>\n if (D(i) < med) {\n ones += D(i)\n if (D(i) > oneMx) {\n oneMx = D(i)\n oneMxIx = i\n }\n }\n }\n TO(if (oneMxIx != - 1) oneMxIx + 1 else 0, N - 1) { i =>\n if (D(i) == med) ones += D(i)\n }\n REP(N) { i =>\n if (D(i) > med || D(i) == med && i < oneMxIx) {\n twos += D(i)\n }\n }\n debug(ones.mkString(\" \"))\n debug(twos.mkString(\" \"))\n if (isSorted(ones, twos)) {\n debug(s\"med:$med oneMxIx:$oneMxIx\")\n showResult(med, oneMxIx)\n return\n }\n }\n out.println(\"-\")\n }\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n solve2()\n }\n }\n}"}], "src_uid": "886f773e75fa3c770fb70133ff1b595b"} {"nl": {"description": "Alice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains $$$a$$$ stones, the second of them contains $$$b$$$ stones and the third of them contains $$$c$$$ stones.Each time she can do one of two operations: take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $$$0$$$ stones. Can you help her?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. Next $$$t$$$ lines describe test cases in the following format: Line contains three non-negative integers $$$a$$$, $$$b$$$ and $$$c$$$, separated by spaces ($$$0 \\leq a,b,c \\leq 100$$$)\u00a0\u2014 the number of stones in the first, the second and the third heap, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.", "output_spec": "Print $$$t$$$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer \u00a0\u2014 the maximum possible number of stones that Alice can take after making some operations. ", "sample_inputs": ["3\n3 4 5\n1 0 5\n5 3 2"], "sample_outputs": ["9\n0\n6"], "notes": "NoteFor the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $$$9$$$. It is impossible to make some operations to take more than $$$9$$$ stones, so the answer is $$$9$$$."}, "positive_code": [{"source_code": "object _1236A 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 inputs = io.read[Seq[(Int, Int, Int)]]\n\n inputs foreach { case (a, b, c) =>\n var ans = 0\n for {\n x <- 0 to a\n y <- 0 to (c/2)\n if (2*x + y) <= b\n } ans = ans max (3*(x + y))\n\n io.writeLine(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 = 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"}], "negative_code": [], "src_uid": "14fccd50d5dfb557dd53f2896ed844c3"} {"nl": {"description": "A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \\cdot 10^k$$$ for integer $$$k \\ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1\\le T\\leq 1\\,000$$$) denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 10^{18}$$$) denoting the number to be represented.", "output_spec": "For each test case, output the minimum number of 2050-numbers in one line. If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead. ", "sample_inputs": ["6\n205\n2050\n4100\n20500\n22550\n25308639900"], "sample_outputs": ["-1\n1\n2\n1\n2\n36"], "notes": "NoteIn the third case, $$$4100 = 2050 + 2050$$$.In the fifth case, $$$22550 = 20500 + 2050$$$."}, "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.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"}, {"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"} {"nl": {"description": "Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj,\u2009bj) can close marker (xi,\u2009yi) only if their diameters match, that is, bj\u2009=\u2009yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj\u2009=\u2009xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.", "input_spec": "The first input line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of markers and the number of caps, correspondingly. Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u20091000) \u2014 the i-th marker's color and diameter, correspondingly. Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1\u2009\u2264\u2009aj,\u2009bj\u2009\u2264\u20091000) \u2014 the color and diameter of the j-th cap, correspondingly.", "output_spec": "Print two space-separated integers u,\u2009v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.", "sample_inputs": ["3 4\n1 2\n3 4\n2 4\n5 4\n2 4\n1 1\n1 2", "2 2\n1 2\n2 1\n3 4\n5 1"], "sample_outputs": ["3 2", "1 0"], "notes": "NoteIn the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed \u2014 the first and the third markers."}, "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 (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}"}, {"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"} {"nl": {"description": "Consider infinite grid of unit cells. Some of those cells are planets. Meta-universe M\u2009=\u2009{p1,\u2009p2,\u2009...,\u2009pk} is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet pi of meta-universe M on it; 2) there are planets of M located on both sides from this row or column. In this case we can turn the meta-universe M into two non-empty meta-universes M1 and M2 containing planets that are located on respective sides of this row or column. A meta-universe which can't be split using operation above is called a universe. We perform such operations until all meta-universes turn to universes.Given positions of the planets in the original meta-universe, find the number of universes that are result of described process. It can be proved that each universe is uniquely identified not depending from order of splitting.", "input_spec": "The first line of input contains an integer n, (1\u2009\u2264\u2009n\u2009\u2264\u2009105), denoting the number of planets in the meta-universe. The next n lines each contain integers xi and yi, (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109), denoting the coordinates of the i-th planet. All planets are located in different cells.", "output_spec": "Print the number of resulting universes.", "sample_inputs": ["5\n0 0\n0 2\n2 0\n2 1\n2 2", "8\n0 0\n1 0\n0 2\n0 3\n3 0\n3 1\n2 3\n3 3"], "sample_outputs": ["3", "1"], "notes": "NoteThe following figure describes the first test case: "}, "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, 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}"}, {"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"} {"nl": {"description": "The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding\u00a0\u2014 an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.", "output_spec": "Print the new name of the corporation.", "sample_inputs": ["6 1\npolice\np m", "11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b"], "sample_outputs": ["molice", "cdcbcdcfcdc"], "notes": "NoteIn the second sample the name of the corporation consecutively changes as follows: "}, "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 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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n\u2009=\u20094 the sum is equal to \u2009-\u20091\u2009-\u20092\u2009+\u20093\u2009-\u20094\u2009=\u2009\u2009-\u20094, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.", "input_spec": "The first line of the input contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009100) \u2014 the number of values of n to be processed. Each of next t lines contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009109).", "output_spec": "Print the requested sum for each of t integers n given in the input.", "sample_inputs": ["2\n4\n1000000000"], "sample_outputs": ["-4\n499999998352516354"], "notes": "NoteThe answer for the first sample is explained in the statement."}, "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"}, {"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"}], "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"} {"nl": {"description": "It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that n vouchers left. i-th voucher is characterized by three integers li, ri, costi \u2014 day of departure from Vi\u010dkopolis, day of arriving back in Vi\u010dkopolis and cost of the voucher correspondingly. The duration of the i-th voucher is a value ri\u2009-\u2009li\u2009+\u20091.At the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers i and j (i\u2009\u2260\u2009j) so that they don't intersect, sum of their durations is exactly x and their total cost is as minimal as possible. Two vouchers i and j don't intersect if only at least one of the following conditions is fulfilled: ri\u2009<\u2009lj or rj\u2009<\u2009li.Help Leha to choose the necessary vouchers!", "input_spec": "The first line contains two integers n and x (2\u2009\u2264\u2009n,\u2009x\u2009\u2264\u20092\u00b7105) \u2014 the number of vouchers in the travel agency and the duration of Leha's vacation correspondingly. Each of the next n lines contains three integers li, ri and costi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u20092\u00b7105,\u20091\u2009\u2264\u2009costi\u2009\u2264\u2009109) \u2014 description of the voucher.", "output_spec": "Print a single integer \u2014 a minimal amount of money that Leha will spend, or print \u2009-\u20091 if it's impossible to choose two disjoint vouchers with the total duration exactly x.", "sample_inputs": ["4 5\n1 3 4\n1 2 5\n5 6 1\n1 2 4", "3 2\n4 6 3\n2 4 1\n3 5 4"], "sample_outputs": ["5", "-1"], "notes": "NoteIn the first sample Leha should choose first and third vouchers. Hereupon the total duration will be equal to (3\u2009-\u20091\u2009+\u20091)\u2009+\u2009(6\u2009-\u20095\u2009+\u20091)\u2009=\u20095 and the total cost will be 4\u2009+\u20091\u2009=\u20095.In the second sample the duration of each voucher is 3 therefore it's impossible to choose two vouchers with the total duration equal to 2."}, "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, x) = readInts(2)\n case class V(l: Int, r: Int, cost: Long) {\n def len = r - l + 1\n }\n\n val vs = Array.fill(n) {\n val Array(l, r, c) = readInts(3)\n V(l, r, c)\n }\n\n val vsByLen = vs.groupBy(_.len).map {\n case (k, _vs) => k -> _vs.sortBy(_.l)\n }\n\n var res = Long.MaxValue\n\n for (len1 <- vsByLen.keys) {\n val len2 = x - len1\n if (vsByLen.contains(len2)) {\n val vsByLen2 = vsByLen(len2)\n var len2Pos = 0\n var minCostInLen2 = Long.MaxValue\n for (v1 <- vsByLen(len1)) {\n while (len2Pos < vsByLen2.length && vsByLen2(len2Pos).r < v1.l) {\n if (vsByLen2(len2Pos).cost < minCostInLen2) minCostInLen2 = vsByLen2(len2Pos).cost\n len2Pos += 1\n }\n if (minCostInLen2 < Long.MaxValue && v1.cost + minCostInLen2 < res) res = v1.cost + minCostInLen2\n }\n }\n }\n\n if (res == Long.MaxValue) res = -1\n println(res)\n}\n"}], "negative_code": [], "src_uid": "211d872af386c69b9ddaab9d8cf3160f"} {"nl": {"description": "This is the easy version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is \"11001111\", it will be divided into \"11\", \"00\" and \"1111\". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so \"11001111\" is good. Another example, if $$$s$$$ is \"1110011000\", it will be divided into \"111\", \"00\", \"11\" and \"000\", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, \"1110011000\" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1'($$$1 \\leq i \\leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good?", "input_spec": "The first contains a single positive integer $$$t$$$ ($$$1 \\leq t \\leq 10\\,000$$$)\u00a0\u2014 the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single line with one integer\u00a0\u2014 the minimum number of operations to make $$$s$$$ good.", "sample_inputs": ["5\n10\n1110011000\n8\n11001111\n2\n00\n2\n11\n6\n100110"], "sample_outputs": ["3\n0\n0\n0\n3"], "notes": "NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes \"1100000000\", it can be divided into \"11\" and \"00000000\", which lengths are $$$2$$$ and $$$8$$$ respectively. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as \"1111110000\", \"1100001100\", \"1111001100\".In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required."}, "positive_code": [{"source_code": "object Task2 extends App {\r\n\r\n import scala.io.StdIn\r\n\r\n def readLine: String = StdIn.readLine()\r\n\r\n def readNum: Int = StdIn.readLine().toInt\r\n\r\n val testCases = readNum\r\n\r\n for (_ <- 0 until testCases) {\r\n readLine\r\n val inputString = readLine.toCharArray\r\n var pos = 1\r\n var totalOpsCount = 0\r\n\r\n do {\r\n if (inputString(pos - 1) != inputString(pos)) {\r\n totalOpsCount += 1\r\n }\r\n pos += 2\r\n } while (pos <= inputString.length)\r\n\r\n println(totalOpsCount)\r\n }\r\n}"}], "negative_code": [], "src_uid": "aded139ff4d3f313f8e4d81559760f12"} {"nl": {"description": "You are given an n\u2009\u00d7\u2009m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijk\u00a0we obtain the table:acdefghjk\u00a0A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.", "input_spec": "The first line contains two integers \u00a0\u2014 n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Next n lines contain m small English letters each\u00a0\u2014 the characters of the table.", "output_spec": "Print a single number\u00a0\u2014 the minimum number of columns that you need to remove in order to make the table good.", "sample_inputs": ["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"], "sample_outputs": ["0", "2", "4"], "notes": "NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t."}, "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 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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Two people are playing a game with a string $$$s$$$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to \"xaax\" than there is only one possible turn: delete \"aa\", so the string will become \"xx\". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally.", "input_spec": "The only line contains the string $$$s$$$, consisting of lowercase latin letters ($$$1 \\leq |s| \\leq 100\\,000$$$), where $$$|s|$$$ means the length of a string $$$s$$$.", "output_spec": "If the first player wins, print \"Yes\". If the second player wins, print \"No\".", "sample_inputs": ["abacaba", "iiq", "abba"], "sample_outputs": ["No", "Yes", "No"], "notes": "NoteIn the first example the first player is unable to make a turn, so he loses.In the second example first player turns the string into \"q\", then second player is unable to move, so he loses."}, "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 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}"}, {"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": "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}"}], "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"} {"nl": {"description": "Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?", "input_spec": "The first line contains two integers n, l (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009l\u2009\u2264\u2009109)\u00a0\u2014 the number of lanterns and the length of the street respectively. The next line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.", "output_spec": "Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20099.", "sample_inputs": ["7 15\n15 5 3 7 9 14 0", "2 5\n2 5"], "sample_outputs": ["2.5000000000", "2.0000000000"], "notes": "NoteConsider the second sample. At d\u2009=\u20092 the first lantern will light the segment [0,\u20094] of the street, and the second lantern will light segment [3,\u20095]. Thus, the whole street will be lit."}, "positive_code": [{"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"}, {"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 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"}, {"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"}], "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"} {"nl": {"description": "After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.", "input_spec": "First line contains number $$$N$$$ ($$$1 \\leq N \\leq 200\\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \\leq a_i \\leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \\leq f < x \\leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. ", "output_spec": "Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.", "sample_inputs": ["3\n13 7 6\n6 2"], "sample_outputs": ["4"], "notes": "NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4."}, "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 x, f = ni()\n\n var ans = 0L\n val c = x + f\n rep(N) { i =>\n ans += A(i) / c\n val r = A(i) % c\n if (r > x) ans += 1\n }\n\n out.println(ans * f)\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": "8a3e8a5db6d7d668ffea0f59e2639e87"} {"nl": {"description": "The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti \u2014 the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that: the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n), the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism \u2014 find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.", "input_spec": "The first input line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u200920000) \u2014 the initial number of sculptures. The second line contains a sequence of integers t1,\u2009t2,\u2009...,\u2009tn, ti \u2014 the degree of the i-th sculpture's attractiveness (\u2009-\u20091000\u2009\u2264\u2009ti\u2009\u2264\u20091000). The numbers on the line are separated by spaces.", "output_spec": "Print the required maximum sum of the sculptures' attractiveness.", "sample_inputs": ["8\n1 2 -3 4 -5 5 2 3", "6\n1 -2 3 -4 5 -6", "6\n1 2 3 4 5 6"], "sample_outputs": ["14", "9", "21"], "notes": "NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 \u0438 3."}, "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 {\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"}, {"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"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string \"forces\" is substring of string \"codeforces\", but string \"coder\" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in $$$s$$$.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo $$$998244353$$$.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of the string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in $$$s$$$.", "output_spec": "Print one integer \u2014 the number of ways modulo $$$998244353$$$ to remove exactly one substring from $$$s$$$ in such way that all remaining characters are equal.", "sample_inputs": ["4\nabaa", "7\naacdeee", "2\naz"], "sample_outputs": ["6", "6", "3"], "notes": "NoteLet $$$s[l; r]$$$ be the substring of $$$s$$$ from the position $$$l$$$ to the position $$$r$$$ inclusive.Then in the first example you can remove the following substrings: $$$s[1; 2]$$$; $$$s[1; 3]$$$; $$$s[1; 4]$$$; $$$s[2; 2]$$$; $$$s[2; 3]$$$; $$$s[2; 4]$$$. In the second example you can remove the following substrings: $$$s[1; 4]$$$; $$$s[1; 5]$$$; $$$s[1; 6]$$$; $$$s[1; 7]$$$; $$$s[2; 7]$$$; $$$s[3; 7]$$$. In the third example you can remove the following substrings: $$$s[1; 1]$$$; $$$s[1; 2]$$$; $$$s[2; 2]$$$. "}, "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 // \u5168\u90e8\u4e00\u7dd2\n (N.toLong * (N + 1) / 2 - 1) % MOD\n\n } else if (S(0) == S(N - 1)) {\n // \u5de6\u53f3\u304c\u4e00\u7dd2\n val l = countL()\n val r = countR()\n (l + 1).toLong * (r + 1) % MOD\n } else {\n // \u5de6\u53f3\u3067\u9055\u3046\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: 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"}], "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 // \u5168\u90e8\u4e00\u7dd2\n N.toLong * (N + 1) / 2\n\n } else if (S(0) == S(N - 1)) {\n // \u5de6\u53f3\u304c\u4e00\u7dd2\n val l = countL()\n val r = countR()\n (l + 1).toLong * (r + 1)\n } else {\n // \u5de6\u53f3\u3067\u9055\u3046\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"} {"nl": {"description": "You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (xi,\u2009yi). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0,\u20090). Initially, the robot is at point with coordinates (0,\u20090). Also, let's mark the robot's current position as (x,\u2009y). In order to destroy all the bombs, the robot can perform three types of operations: Operation has format \"1 k dir\". To perform the operation robot have to move in direction dir k (k\u2009\u2265\u20091) times. There are only 4 directions the robot can move in: \"R\", \"L\", \"U\", \"D\". During one move the robot can move from the current point to one of following points: (x\u2009+\u20091,\u2009y), (x\u2009-\u20091,\u2009y), (x,\u2009y\u2009+\u20091), (x,\u2009y\u2009-\u20091) (corresponding to directions). It is forbidden to move from point (x,\u2009y), if at least one point on the path (besides the destination point) contains a bomb. Operation has format \"2\". To perform the operation robot have to pick a bomb at point (x,\u2009y) and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point (x,\u2009y) has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container. Operation has format \"3\". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point (0,\u20090). It is forbidden to perform the operation if the container has no bomb. Help the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of bombs on the coordinate plane. Next n lines contain two integers each. The i-th line contains numbers (xi,\u2009yi) (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109) \u2014 the coordinates of the i-th bomb. It is guaranteed that no two bombs are located at the same point and no bomb is at point (0,\u20090). ", "output_spec": "In a single line print a single integer k \u2014 the minimum number of operations needed to destroy all bombs. On the next lines print the descriptions of these k operations. If there are multiple sequences, you can print any of them. It is guaranteed that there is the solution where k\u2009\u2264\u2009106.", "sample_inputs": ["2\n1 1\n-1 -1", "3\n5 0\n0 5\n1 0"], "sample_outputs": ["12\n1 1 R\n1 1 U\n2\n1 1 L\n1 1 D\n3\n1 1 L\n1 1 D\n2\n1 1 R\n1 1 U\n3", "12\n1 1 R\n2\n1 1 L\n3\n1 5 R\n2\n1 5 L\n3\n1 5 U\n2\n1 5 D\n3"], "notes": null}, "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.take(n).map(line => line.split(' ').map(_.toInt)).map(i => (i.head, i.last)).toList\n val result = line\n .sortBy(i => (Math.min(Math.abs(i._1), Math.abs(i._2)), Math.max(Math.abs(i._1), Math.abs(i._2))))\n .map {\n case (x, y) if x == 0 =>\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(y)} $down\\n3\"\n case (x, y) if y == 0 =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n s\"1 ${Math.abs(x)} $right\\n2\\n1 ${Math.abs(x)} $left\\n3\"\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(x)} $right\\n1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(x)} $left\\n1 ${Math.abs(y)} $down\\n3\"\n }\n println(result.length * 6 - 2 * line.count(i => i._1 == 0 || i._2 == 0))\n println(result.mkString(\"\\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.take(n).map(line => line.split(' ').map(_.toInt)).map(i => (i.head, i.last)).toList\n val result = line\n .sortBy(i => (Math.min(Math.abs(i._1), Math.abs(i._2)), Math.max(Math.abs(i._1), Math.abs(i._2))))\n .map {\n case (x, y) if x == 0 =>\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(y)} $down\\n3\"\n case (x, y) if y == 0 =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n s\"1 ${Math.abs(x)} $right\\n2\\n1 ${Math.abs(x)} $left\\n3\"\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(x)} $right\\n1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(x)} $left\\n1 ${Math.abs(y)} $down\\n3\"\n }\n println(result.length * 6 - 2 * line.count(i => i._1 == 0 || i._2 == 9))\n println(result.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val set = in.take(n).map(line => line.split(' ').map(_.toInt)).map(i => (i.head, i.last)).toSet\n val sorted = set.toList.sortBy(i => Math.min(i._1, i._2))\n val result = sorted.flatMap {\n case (x, y) =>\n val there = (if (x != 0) List(s\"1 $x R\") else Nil) ::: (if (y != 0) List(s\"1 $y U\") else Nil)\n val back = (if (x != 0) List(s\"1 $x L\") else Nil) ::: (if (y != 0) List(s\"1 $y D\") else Nil)\n there ::: List(\"2\") ::: back ::: List(\"3\")\n }\n println(result.length)\n println(result.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val result = in.take(n).map(line => line.split(' ').map(_.toInt))\n .map(i => (i.head, i.last)).toList\n .sortBy(i => (Math.min(Math.abs(i._1), Math.abs(i._2)), Math.max(Math.abs(i._1), Math.abs(i._2))))\n .map {\n case (x, y) if x == 0 =>\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(y)} $down\\n3\"\n case (x, y) if y == 0 =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n s\"1 ${Math.abs(x)} $right\\n2\\n1 ${Math.abs(x)} $left\\n3\"\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(x)} $right\\n1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(x)} $left\\n1 ${Math.abs(y)} $down\\n3\"\n }\n println(result.length)\n println(result.mkString(\"\\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.take(n).map(line => line.split(' ').map(_.toInt)).map(i => (i.head, i.last)).toList\n val result = line\n .sortBy(i => (Math.min(Math.abs(i._1), Math.abs(i._2)), Math.max(Math.abs(i._1), Math.abs(i._2))))\n .map {\n case (x, y) if x == 0 =>\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(y)} $down\\n3\"\n case (x, y) if y == 0 =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n s\"1 ${Math.abs(x)} $right\\n2\\n1 ${Math.abs(x)} $left\\n3\"\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n s\"1 ${Math.abs(x)} $right\\n1 ${Math.abs(y)} $up\\n2\\n1 ${Math.abs(x)} $left\\n1 ${Math.abs(y)} $down\\n3\"\n }\n println(result.length * 4 - line.count(i => i._1 == 0 || i._2 == 9))\n println(result.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val set = in.take(n).map(line => line.split(' ').map(_.toInt)).map(i => (i.head, i.last)).toSet\n val sorted = set.toList.sortBy(i => Math.min(Math.abs(i._1), Math.abs(i._2)))\n val result = sorted.flatMap {\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n val there = (if (x != 0) List(s\"1 ${Math.abs(x)} $right\") else Nil) ::: (if (y != 0) List(s\"1 ${Math.abs(y)} $up\") else Nil)\n val back = (if (x != 0) List(s\"1 ${Math.abs(x)} $left\") else Nil) ::: (if (y != 0) List(s\"1 ${Math.abs(y)} $down\") else Nil)\n there ::: List(\"2\") ::: back ::: List(\"3\")\n }\n println(result.length)\n println(result.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val result = in.take(n).map(line => line.split(' ').map(_.toInt))\n .map(i => (i.head, i.last)).toList\n .sortBy(i => (Math.min(Math.abs(i._1), Math.abs(i._2)), Math.max(Math.abs(i._1), Math.abs(i._2))))\n .flatMap {\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n List(if (x != 0) Some(s\"1 ${Math.abs(x)} $right \\n \") else None,\n if (y != 0) Some(s\"1 ${Math.abs(y)} $up\") else None,\n Some(\"2\"),\n if (x != 0) Some(s\"1 ${Math.abs(x)} $left\") else None,\n if (y != 0) Some(s\"1 ${Math.abs(y)} $down\") else None,\n Some(\"3\"))\n }\n println(result.length)\n println(result.mkString(\"\\n\"))\n}\n"}, {"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val set = in.take(n).map(line => line.split(' ').map(_.toInt)).map(i => (i.head, i.last)).toSet\n val sorted = set.toList.sortBy(i => (Math.min(Math.abs(i._1), Math.abs(i._2)), Math.max(Math.abs(i._1), Math.abs(i._2))))\n val result = sorted.flatMap {\n case (x, y) =>\n val right = if (x > 0) 'R' else 'L'\n val left = if (x > 0) 'L' else 'R'\n val up = if (y > 0) 'U' else 'D'\n val down = if (y > 0) 'D' else 'U'\n List(if (x != 0) Some(s\"1 ${Math.abs(x)} $right \\n \") else None,\n if (y != 0) List(s\"1 ${Math.abs(y)} $up\") else None,\n Some(\"2\"),\n if (x != 0) List(s\"1 ${Math.abs(x)} $left\") else Nil,\n if (y != 0) List(s\"1 ${Math.abs(y)} $down\") else Nil,\n Some(\"3\"))\n }\n println(result.length)\n println(result.mkString(\"\\n\"))\n}\n"}], "src_uid": "a7c1b9845ab0569e0175853db9ed5c32"} {"nl": {"description": "Little boy Petya loves stairs very much. But he is bored from simple going up and down them \u2014 he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once.One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009109, 0\u2009\u2264\u2009m\u2009\u2264\u20093000) \u2014 the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d1,\u2009d2,\u2009...,\u2009dm (1\u2009\u2264\u2009di\u2009\u2264\u2009n) \u2014 the numbers of the dirty stairs (in an arbitrary order).", "output_spec": "Print \"YES\" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print \"NO\".", "sample_inputs": ["10 5\n2 4 8 3 6", "10 5\n2 4 5 7 9"], "sample_outputs": ["NO", "YES"], "notes": null}, "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 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}"}, {"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 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}"}], "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"} {"nl": {"description": "Wilbur the pig is tinkering with arrays again. He has the array a1,\u2009a2,\u2009...,\u2009an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai,\u2009ai\u2009+\u20091,\u2009... ,\u2009an or subtract 1 from all elements ai,\u2009ai\u2009+\u20091,\u2009...,\u2009an. His goal is to end up with the array b1,\u2009b2,\u2009...,\u2009bn. Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the length of the array ai. Initially ai\u2009=\u20090 for every position i, so this array is not given in the input. The second line of the input contains n integers b1,\u2009b2,\u2009...,\u2009bn (\u2009-\u2009109\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "Print the minimum number of steps that Wilbur needs to make in order to achieve ai\u2009=\u2009bi for all i.", "sample_inputs": ["5\n1 2 3 4 5", "4\n1 2 2 1"], "sample_outputs": ["5", "3"], "notes": "NoteIn the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1."}, "positive_code": [{"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"}, {"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": "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"}], "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"} {"nl": {"description": "You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \\le x \\le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \\le y \\le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) \u2014 the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \\le a, b, n, S \\le 10^9$$$) \u2014 the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.", "output_spec": "For the $$$i$$$-th test case print the answer on it \u2014 YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"], "sample_outputs": ["YES\nNO\nNO\nYES"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations arbitrary number of times (possibly, zero): Choose a pair of indices $$$(i, j)$$$ such that $$$|i-j|=1$$$ (indices $$$i$$$ and $$$j$$$ are adjacent) and set $$$a_i := a_i + |a_i - a_j|$$$; Choose a pair of indices $$$(i, j)$$$ such that $$$|i-j|=1$$$ (indices $$$i$$$ and $$$j$$$ are adjacent) and set $$$a_i := a_i - |a_i - a_j|$$$. The value $$$|x|$$$ means the absolute value of $$$x$$$. For example, $$$|4| = 4$$$, $$$|-3| = 3$$$.Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.It is guaranteed that you always can obtain the array of equal elements using such operations.Note that after each operation each element of the current array should not exceed $$$10^{18}$$$ by absolute value.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2 \\cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "In the first line print one integer $$$k$$$ \u2014 the minimum number of operations required to obtain the array of equal elements. In the next $$$k$$$ lines print operations itself. The $$$p$$$-th operation should be printed as a triple of integers $$$(t_p, i_p, j_p)$$$, where $$$t_p$$$ is either $$$1$$$ or $$$2$$$ ($$$1$$$ means that you perform the operation of the first type, and $$$2$$$ means that you perform the operation of the second type), and $$$i_p$$$ and $$$j_p$$$ are indices of adjacent elements of the array such that $$$1 \\le i_p, j_p \\le n$$$, $$$|i_p - j_p| = 1$$$. See the examples for better understanding. Note that after each operation each element of the current array should not exceed $$$10^{18}$$$ by absolute value. If there are many possible answers, you can print any.", "sample_inputs": ["5\n2 4 6 6 6", "3\n2 8 10", "4\n1 1 1 1"], "sample_outputs": ["2\n1 2 3 \n1 1 2", "2\n2 2 1 \n2 3 2", "0"], "notes": null}, "positive_code": [{"source_code": "\nobject D1144Equal extends App {\n import scala.collection.mutable\n import scala.io.StdIn.{readInt, readLine}\n\n val n = readInt\n val arr = readLine.split(' ').map(_.toInt).toArray\n val freq = arr.groupBy(identity).mapValues(_.length).maxBy(_._2)._1\n val pivot = arr.zipWithIndex.find(_._1 == freq).get._2\n\n val res: mutable.ArrayBuffer[(Int, Int, Int)] = mutable.ArrayBuffer.empty\n\n for(i <- (0 until pivot).reverse) {\n if(arr(i) < freq) res.append((1, i, i + 1))\n else if (arr(i) > freq) res.append((2, i, i + 1))\n }\n\n for(i <- pivot + 1 until n) {\n if(arr(i) < freq) res.append((1, i, i - 1))\n else if (arr(i) > freq) res.append((2, i, i - 1))\n }\n\n\n println(res.length)\n println(res.map( x => s\"${x._1} ${x._2 + 1} ${x._3 + 1}\").mkString(\"\\n\"))\n\n}\n"}], "negative_code": [{"source_code": "\nobject D1144Equal extends App {\n import scala.io.StdIn.{readInt, readLine}\n\n val n = readInt\n val arr = readLine.split(' ').map(_.toInt).toList\n val freq = arr.groupBy(identity).mapValues(_.length).maxBy(_._2)._1\n val arrIdx = arr.zipWithIndex\n val pivot = arrIdx.find(_._1 == freq).get._2 + 1\n val tmp = arrIdx.take(pivot).reverse ++ arrIdx.drop(pivot)\n\n var res: List[(Int, Int, Int)] = List.empty\n var i_prev = tmp.head._2\n val master = tmp.head._1\n\n for((a, i) <- tmp.tail) {\n if (a < master) {\n res :+= (1, i_prev, i)\n } else if (a > master) {\n res :+= (2, i_prev, i)\n }\n i_prev = i\n }\n\n println(res.length)\n res.foreach( x => println(s\"${x._1} ${x._2 + 1} ${x._3 + 1}\"))\n\n}\n"}], "src_uid": "732d28ed9092883dccadbd1999308567"} {"nl": {"description": "Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example: the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\"; the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.", "input_spec": "The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.", "output_spec": "Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.", "sample_inputs": ["hellno", "abacaba", "asdfasdf"], "sample_outputs": ["hell no", "abacaba", "asd fasd f"], "notes": null}, "positive_code": [{"source_code": "object P861C {\n /** Input\n * The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.\n *\n * Output\n * Print the given word without any changes if there are no typos.\n *\n * Formally, a word is typed with a typo\n * if there is a block of not less that three consonants in a row,\n * and there are at least two different letters in this block.\n *\n * For example:\n * the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\";\n * the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\".\n *\n * When Beroffice editor finds a word with a typo,\n * it inserts as little as possible number of spaces in this word (dividing it into several words)\n * in such a way that each of the resulting words is typed without any typos.\n *\n */\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val word = sc.next()\n\n val vowels = Seq('a', 'e', 'i', 'o', 'u')\n var previouslySplitted = false\n\n if (word.length < 3) println(word)\n else {\n val words = word.take(2) ++ word.sliding(3).flatMap { cs =>\n if (!previouslySplitted && cs.count(!vowels.contains(_)) > 2 && cs.distinct.length > 1) {\n previouslySplitted = true\n Seq(' ', cs.last)\n }\n else {\n previouslySplitted = false\n Seq(cs.last)\n }\n }\n println(words.mkString)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object P861C {\n /** Input\n * The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.\n *\n * Output\n * Print the given word without any changes if there are no typos.\n *\n * Formally, a word is typed with a typo\n * if there is a block of not less that three consonants in a row,\n * and there are at least two different letters in this block.\n *\n * For example:\n * the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\";\n * the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\".\n *\n * When Beroffice editor finds a word with a typo,\n * it inserts as little as possible number of spaces in this word (dividing it into several words)\n * in such a way that each of the resulting words is typed without any typos.\n *\n */\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val word = sc.next()\n\n val vowels = Seq('a', 'e', 'i', 'o', 'u')\n\n if (word.length < 3) println(word)\n else {\n val words = word.take(2) ++ word.sliding(3).flatMap { cs =>\n if (cs.count(!vowels.contains(_)) > 2 && cs.distinct.length > 1) Seq(' ', cs.last)\n else Seq(cs.last)\n }\n println(words.mkString)\n }\n }\n}\n"}, {"source_code": "object P861C {\n /** Input\n * The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.\n *\n * Output\n * Print the given word without any changes if there are no typos.\n *\n * Formally, a word is typed with a typo\n * if there is a block of not less that three consonants in a row,\n * and there are at least two different letters in this block.\n *\n * For example:\n * the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\";\n * the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\".\n *\n * When Beroffice editor finds a word with a typo,\n * it inserts as little as possible number of spaces in this word (dividing it into several words)\n * in such a way that each of the resulting words is typed without any typos.\n *\n */\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val word = sc.next()\n\n val vowels = Seq('a', 'e', 'i', 'o', 'u')\n var previouslySplitted = false\n\n if (word.length < 3) println(word)\n else {\n val words = word.take(2) ++ word.sliding(3).flatMap { cs =>\n if (cs.count(!vowels.contains(_)) > 2 && cs.distinct.length > 1) {\n previouslySplitted = true\n Seq(' ', cs.last)\n }\n else {\n previouslySplitted = false\n Seq(cs.last)\n }\n }\n println(words.mkString)\n }\n }\n}\n"}, {"source_code": "object P861C {\n /** Input\n * The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.\n *\n * Output\n * Print the given word without any changes if there are no typos.\n *\n * Formally, a word is typed with a typo\n * if there is a block of not less that three consonants in a row,\n * and there are at least two different letters in this block.\n *\n * For example:\n * the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\";\n * the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\".\n *\n * When Beroffice editor finds a word with a typo,\n * it inserts as little as possible number of spaces in this word (dividing it into several words)\n * in such a way that each of the resulting words is typed without any typos.\n *\n */\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val word = sc.next()\n\n val vowels = Seq('a', 'e', 'i', 'o', 'u')\n\n if (word.length < 3) println(word)\n else {\n val words = word.take(2) ++ word.sliding(3).map { cs =>\n if (cs.count(!vowels.contains(_)) > 2 && cs.distinct.length > 1) Seq(' ' + cs.last).mkString\n else cs.last.toString\n }\n println(words)\n }\n }\n}\n"}, {"source_code": "object P861C {\n /** Input\n * The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.\n *\n * Output\n * Print the given word without any changes if there are no typos.\n *\n * Formally, a word is typed with a typo\n * if there is a block of not less that three consonants in a row,\n * and there are at least two different letters in this block.\n *\n * For example:\n * the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\";\n * the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\".\n *\n * When Beroffice editor finds a word with a typo,\n * it inserts as little as possible number of spaces in this word (dividing it into several words)\n * in such a way that each of the resulting words is typed without any typos.\n *\n */\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val word = sc.next()\n\n val vowels = Seq('a', 'e', 'i', 'o', 'u')\n\n if (word.length < 3) println(word)\n else {\n val words = word.take(2) ++ word.sliding(3).flatMap { cs =>\n if (cs.count(!vowels.contains(_)) > 2 && cs.distinct.length > 1) Seq(' ' + cs.last)\n else Seq(cs.last)\n }\n println(words.mkString)\n }\n }\n}\n"}], "src_uid": "436c00c832de8df739fc391f2ed6dac4"} {"nl": {"description": "Alice and Bob play the following game. Alice has a set $$$S$$$ of disjoint ranges of integers, initially containing only one range $$$[1, n]$$$. In one turn, Alice picks a range $$$[l, r]$$$ from the set $$$S$$$ and asks Bob to pick a number in the range. Bob chooses a number $$$d$$$ ($$$l \\le d \\le r$$$). Then Alice removes $$$[l, r]$$$ from $$$S$$$ and puts into the set $$$S$$$ the range $$$[l, d - 1]$$$ (if $$$l \\le d - 1$$$) and the range $$$[d + 1, r]$$$ (if $$$d + 1 \\le r$$$). The game ends when the set $$$S$$$ is empty. We can show that the number of turns in each game is exactly $$$n$$$.After playing the game, Alice remembers all the ranges $$$[l, r]$$$ she picked from the set $$$S$$$, but Bob does not remember any of the numbers that he picked. But Bob is smart, and he knows he can find out his numbers $$$d$$$ from Alice's ranges, and so he asks you for help with your programming skill.Given the list of ranges that Alice has picked ($$$[l, r]$$$), for each range, help Bob find the number $$$d$$$ that Bob has picked.We can show that there is always a unique way for Bob to choose his number for a list of valid ranges picked by Alice.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$). Each of the next $$$n$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le n$$$), denoting the range $$$[l, r]$$$ that Alice picked at some point. Note that the ranges are given in no particular order. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$, and the ranges for each test case are from a valid game.", "output_spec": "For each test case print $$$n$$$ lines. Each line should contain three integers $$$l$$$, $$$r$$$, and $$$d$$$, denoting that for Alice's range $$$[l, r]$$$ Bob picked the number $$$d$$$. You can print the lines in any order. We can show that the answer is unique. It is not required to print a new line after each test case. The new lines in the output of the example are for readability only. ", "sample_inputs": ["4\n1\n1 1\n3\n1 3\n2 3\n2 2\n6\n1 1\n3 5\n4 4\n3 6\n4 5\n1 6\n5\n1 5\n1 2\n4 5\n2 2\n4 4"], "sample_outputs": ["1 1 1\n\n1 3 1\n2 2 2\n2 3 3\n\n1 1 1\n3 5 3\n4 4 4\n3 6 6\n4 5 5\n1 6 2\n\n1 5 3\n1 2 1\n4 5 5\n2 2 2\n4 4 4"], "notes": "NoteIn the first test case, there is only 1 range $$$[1, 1]$$$. There was only one range $$$[1, 1]$$$ for Alice to pick, and there was only one number $$$1$$$ for Bob to pick.In the second test case, $$$n = 3$$$. Initially, the set contains only one range $$$[1, 3]$$$. Alice picked the range $$$[1, 3]$$$. Bob picked the number $$$1$$$. Then Alice put the range $$$[2, 3]$$$ back to the set, which after this turn is the only range in the set. Alice picked the range $$$[2, 3]$$$. Bob picked the number $$$3$$$. Then Alice put the range $$$[2, 2]$$$ back to the set. Alice picked the range $$$[2, 2]$$$. Bob picked the number $$$2$$$. The game ended. In the fourth test case, the game was played with $$$n = 5$$$. Initially, the set contains only one range $$$[1, 5]$$$. The game's turn is described in the following table. Game turnAlice's picked rangeBob's picked numberThe range set afterBefore the game start$$$ \\{ [1, 5] \\} $$$1$$$[1, 5]$$$$$$3$$$$$$ \\{ [1, 2], [4, 5] \\}$$$2$$$[1, 2]$$$$$$1$$$$$$ \\{ [2, 2], [4, 5] \\} $$$3$$$[4, 5]$$$$$$5$$$$$$ \\{ [2, 2], [4, 4] \\} $$$4$$$[2, 2]$$$$$$2$$$$$$ \\{ [4, 4] \\} $$$5$$$[4, 4]$$$$$$4$$$$$$ \\{ \\} $$$ (empty set) "}, "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}"}, {"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"}], "negative_code": [], "src_uid": "eca433877ef3fbda198c5f2c95a359e7"} {"nl": {"description": "Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.", "input_spec": "The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \\le c_i, sum_i \\le 10^4$$$) \u2014 the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.", "output_spec": "For each room print one integer \u2014 the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.", "sample_inputs": ["4\n1 10000\n10000 1\n2 6\n4 6"], "sample_outputs": ["100000000\n1\n18\n10"], "notes": "NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$."}, "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": "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "This is an interactive problem. In the output section below you will see the information about flushing the output.On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vi\u010dkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of n dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to n. After a little thought, the girl ordered exactly k different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers x and y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n). After that Noora chooses some dish a for the number x such that, at first, a is among the dishes Noora ordered (x can be equal to a), and, secondly, the value is the minimum possible. By the same rules the girl chooses dish b for y. After that Noora says \u00abTAK\u00bb to Leha, if , and \u00abNIE\u00bb otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.Help Leha to solve this problem!", "input_spec": "There are two numbers n and k (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.", "output_spec": "If you want to provide an answer, output a string of the form 2 x y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n,\u2009x\u2009\u2260\u2009y), if you think the dishes x and y was among dishes ordered by Noora. After that, flush the output and terminate your program.", "sample_inputs": ["3 2\nNIE\nTAK\nNIE\nTAK\nTAK\nTAK"], "sample_outputs": ["1 1 2\n1 2 1\n1 1 3\n1 3 1\n1 2 3\n1 3 2\n2 2 3"], "notes": "NoteThere are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (x\u2009=\u20091), then she'll choose the second dish (a\u2009=\u20092) as the dish with the minimum value . For the second (x\u2009=\u20092) and the third (x\u2009=\u20093) dishes themselves will be optimal, because in that case . Let Leha asks Noora about the next couple of dishes: x\u2009=\u20091, y\u2009=\u20092, then he'll recieve \u00abNIE\u00bb answer, because |1\u2009-\u20092|\u2009>\u2009|2\u2009-\u20092| x\u2009=\u20092, y\u2009=\u20091, then he'll recieve \u00abTAK\u00bb answer, because |2\u2009-\u20092|\u2009\u2264\u2009|1\u2009-\u20092| x\u2009=\u20091, y\u2009=\u20093, then he'll recieve \u00abNIE\u00bb answer, because |1\u2009-\u20092|\u2009>\u2009|3\u2009-\u20093| x\u2009=\u20093, y\u2009=\u20091, then he'll recieve \u00abTAK\u00bb answer, because |3\u2009-\u20093|\u2009\u2264\u2009|1\u2009-\u20092| x\u2009=\u20092, y\u2009=\u20093, then he'll recieve \u00abTAK\u00bb answer, because |2\u2009-\u20092|\u2009\u2264\u2009|3\u2009-\u20093| x\u2009=\u20093, y\u2009=\u20092, then he'll recieve \u00abTAK\u00bb answer, because |3\u2009-\u20093|\u2009\u2264\u2009|2\u2009-\u20092| According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3."}, "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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 def solve(left: Int, right: Int): Int = {\n if (left == right) left\n else {\n val mid = (left + right + 1) / 2\n val lMid = (left + mid) / 2\n val rMid = (mid + right + 1) / 2\n\n //println(left, right, mid, lMid, rMid)\n\n println(s\"1 $lMid $rMid\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n if (mid == right) solve(left, mid - 1)\n else solve(left, mid)\n case \"NIE\" =>\n if (mid == left) solve(mid + 1, right)\n else solve(mid, right)\n }\n }\n }\n\n val res1 = solve(1, n)\n //println(res1)\n val res2a = if (res1 > 1) solve(1, res1 - 1) else -1\n val res2b = if (res1 < n) solve(res1 + 1, n) else -1\n\n val res2 = if (res2a == -1) res2b\n else if (res2b == -1) res2a\n else {\n println(s\"1 $res2a $res2b\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n res2a\n case \"NIE\" =>\n res2b\n }\n }\n\n println(s\"2 $res1 $res2\")\n Console.flush\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) = readInts(2)\n\n def solve(left: Int, right: Int): Int = {\n if (left == right) left\n else {\n val mid = (left + right + 1) / 2\n val lMid = (left + mid) / 2\n val rMid = (mid + right + 1) / 2\n\n// println(left, right, mid, lMid, rMid)\n\n println(s\"1 $lMid $rMid\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n if (mid == right) solve(left, mid - 1)\n else solve(left, mid)\n case \"NIE\" =>\n if (mid == left) solve(mid + 1, right)\n else solve(mid, right)\n }\n }\n }\n\n val res1 = solve(1, n)\n //println(res1)\n val res2a = solve(1, res1 - 1)\n val res2b = solve(res1 + 1, n)\n\n println(s\"1 $res2a $res2b\")\n Console.flush\n\n val res2 = readLine match {\n case \"TAK\" =>\n res2a\n case \"NIE\" =>\n res2b\n }\n\n println(s\"2 $res1 $res2\")\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 def solve(left: Int, right: Int): Int = {\n //println(left, right)\n if (left == right) left\n else {\n val mid = (left + right) / 2\n val lMid = (left + mid) / 2\n val rMid = (mid + right + 1) / 2\n\n println(s\"1 $lMid $rMid\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n solve(left, mid)\n case \"NIE\" =>\n solve(mid, right)\n }\n }\n }\n\n val res1 = solve(1, n)\n val res2a = solve(1, res1 - 1)\n val res2b = solve(res1 + 1, n)\n\n println(s\"1 $res2a $res2b\")\n Console.flush\n\n val res2 = readLine match {\n case \"TAK\" =>\n res2a\n case \"NIE\" =>\n res2b\n }\n\n println(s\"2 $res1 $res2\")\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 def solve(left: Int, right: Int): Int = {\n if (left == right) left\n else {\n val mid = (left + right + 1) / 2\n val lMid = (left + mid) / 2\n val rMid = (mid + right + 1) / 2\n\n println(left, right, mid, lMid, rMid)\n\n //println(s\"1 $lMid $rMid\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n if (mid == right) solve(left, mid - 1)\n else solve(left, mid)\n case \"NIE\" =>\n solve(mid, right)\n }\n }\n }\n\n val res1 = solve(1, n)\n //println(res1)\n val res2a = solve(1, res1 - 1)\n val res2b = solve(res1 + 1, n)\n\n println(s\"1 $res2a $res2b\")\n Console.flush\n\n val res2 = readLine match {\n case \"TAK\" =>\n res2a\n case \"NIE\" =>\n res2b\n }\n\n println(s\"2 $res1 $res2\")\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 def solve(left: Int, right: Int): Int = {\n if (left == right) left\n else {\n val mid = (left + right + 1) / 2\n val lMid = (left + mid) / 2\n val rMid = (mid + right + 1) / 2\n\n// println(left, right, mid, lMid, rMid)\n\n println(s\"1 $lMid $rMid\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n if (mid == right) solve(left, mid - 1)\n else solve(left, mid)\n case \"NIE\" =>\n solve(mid, right)\n }\n }\n }\n\n val res1 = solve(1, n)\n //println(res1)\n val res2a = solve(1, res1 - 1)\n val res2b = solve(res1 + 1, n)\n\n println(s\"1 $res2a $res2b\")\n Console.flush\n\n val res2 = readLine match {\n case \"TAK\" =>\n res2a\n case \"NIE\" =>\n res2b\n }\n\n println(s\"2 $res1 $res2\")\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 def solve(left: Int, right: Int): Int = {\n //println(left, right)\n if (left == right) left\n else {\n val mid = (left + right + 1) / 2\n val lMid = (left + mid + 1) / 2\n val rMid = (mid + right) / 2\n\n println(s\"1 $lMid $rMid\")\n Console.flush\n\n readLine match {\n case \"TAK\" =>\n solve(left, mid)\n case \"NIE\" =>\n solve(mid, right)\n }\n }\n }\n\n val res1 = solve(1, n)\n val res2a = solve(1, res1 - 1)\n val res2b = solve(res1 + 1, n)\n\n println(s\"1 $res2a $res2b\")\n Console.flush\n\n val res2 = readLine match {\n case \"TAK\" =>\n res2a\n case \"NIE\" =>\n res2b\n }\n\n println(s\"2 $res1 $res2\")\n Console.flush\n}\n"}], "src_uid": "f4240b7bbc46e2c4a62a4e5c563ec8f6"} {"nl": {"description": "Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.", "input_spec": "In first line there is one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 number of cafes indices written by Vlad. In second line, n numbers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u20092\u00b7105) are written\u00a0\u2014 indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.", "output_spec": "Print one integer\u00a0\u2014 index of the cafe that Vlad hasn't visited for as long as possible.", "sample_inputs": ["5\n1 3 2 1 2", "6\n2 1 2 2 4 1"], "sample_outputs": ["3", "2"], "notes": "NoteIn first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $$$(0,0)$$$ to $$$(x,0)$$$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $$$n$$$ favorite numbers: $$$a_1, a_2, \\ldots, a_n$$$. What is the minimum number of hops Rabbit needs to get from $$$(0,0)$$$ to $$$(x,0)$$$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points $$$(x_i, y_i)$$$ and $$$(x_j, y_j)$$$ is $$$\\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$$$.For example, if Rabbit has favorite numbers $$$1$$$ and $$$3$$$ he could hop from $$$(0,0)$$$ to $$$(4,0)$$$ in two hops as shown below. Note that there also exists other valid ways to hop to $$$(4,0)$$$ in $$$2$$$ hops (e.g. $$$(0,0)$$$ $$$\\rightarrow$$$ $$$(2,-\\sqrt{5})$$$ $$$\\rightarrow$$$ $$$(4,0)$$$). Here is a graphic for the first example. Both hops have distance $$$3$$$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $$$a_i$$$ and hops with distance equal to $$$a_i$$$ in any direction he wants. The same number can be used multiple times.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain test cases \u2014 two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le x \\le 10^9$$$) \u00a0\u2014 the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u00a0\u2014 Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the minimum number of hops needed.", "sample_inputs": ["4\n\n2 4\n\n1 3\n\n3 12\n\n3 4 5\n\n1 5\n\n5\n\n2 10\n\n15 4"], "sample_outputs": ["2\n3\n1\n2"], "notes": "NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to $$$(2,\\sqrt{5})$$$, then to $$$(4,0)$$$ for a total of two hops. Each hop has a distance of $$$3$$$, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop $$$3$$$ times is: $$$(0,0)$$$ $$$\\rightarrow$$$ $$$(4,0)$$$ $$$\\rightarrow$$$ $$$(8,0)$$$ $$$\\rightarrow$$$ $$$(12,0)$$$.In the third test case of the sample, Rabbit can hop from $$$(0,0)$$$ to $$$(5,0)$$$.In the fourth test case of the sample, Rabbit can hop: $$$(0,0)$$$ $$$\\rightarrow$$$ $$$(5,10\\sqrt{2})$$$ $$$\\rightarrow$$$ $$$(10,0)$$$."}, "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 t = in.nextInt()\n ( 1 to t).foreach{ _ =>\n val n = in.nextInt()\n val x = in.nextInt()\n val a = (1 to n).map(_ => in.nextInt())\n val m = a.max\n if(a.contains(x)){\n out.println(1)\n }else{\n if(m>x){\n out.println(2)\n }else{\n val res = (x+m-1)/m\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}"}], "negative_code": [], "src_uid": "b6a7e8abc747bdcee74653817085002c"} {"nl": {"description": "Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x\u2009-\u2009y| kilometers. We call a \"route\" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). Next line contains n distinct integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107).", "output_spec": "Output two integers \u2014 the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.", "sample_inputs": ["3\n2 3 5"], "sample_outputs": ["22 3"], "notes": "NoteConsider 6 possible routes: [2, 3, 5]: total distance traveled: |2 \u2013 0| + |3 \u2013 2| + |5 \u2013 3| = 5; [2, 5, 3]: |2 \u2013 0| + |5 \u2013 2| + |3 \u2013 5| = 7; [3, 2, 5]: |3 \u2013 0| + |2 \u2013 3| + |5 \u2013 2| = 7; [3, 5, 2]: |3 \u2013 0| + |5 \u2013 3| + |2 \u2013 5| = 8; [5, 2, 3]: |5 \u2013 0| + |2 \u2013 5| + |3 \u2013 2| = 9; [5, 3, 2]: |5 \u2013 0| + |3 \u2013 5| + |2 \u2013 3| = 8. The average travel distance is = = ."}, "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 printf(\"%d %d\\n\", a/d, n/d)\n}\n"}, {"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"} {"nl": {"description": "There is an infinite set generated as follows: $$$1$$$ is in this set. If $$$x$$$ is in this set, $$$x \\cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are: $$$1$$$, $$$3$$$ ($$$1$$$ is in this set, so $$$1\\cdot a=3$$$ is in this set), $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set), $$$9$$$ ($$$3$$$ is in this set, so $$$3\\cdot a=9$$$ is in this set), $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\leq t\\leq 10^5$$$) \u2014 the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\\leq n,a,b\\leq 10^9$$$) separated by a single space.", "output_spec": "For each test case, print \"Yes\" if $$$n$$$ is in this set, and \"No\" otherwise. You can print each letter in any case.", "sample_inputs": ["5\n24 3 5\n10 3 6\n2345 1 4\n19260817 394 485\n19260817 233 264"], "sample_outputs": ["Yes\nNo\nYes\nNo\nYes"], "notes": "NoteIn the first test case, $$$24$$$ is generated as follows: $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set; $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set; $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them."}, "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(_.toLong)\r\n\r\n val ans = {\r\n @annotation.tailrec\r\n def go(x: Long): Boolean = x <= n && ((n - x) % b == 0 || a != 1 && go(x * a))\r\n\r\n go(1)\r\n }\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": "e0a3c678f6d1d89420c8162b0ddfcef7"} {"nl": {"description": "Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x\u2009=\u2009i.The problematic bone is initially at the position x\u2009=\u20091. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x\u2009=\u2009ui and x\u2009=\u2009vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x\u2009=\u20094 and the one at x\u2009=\u20096, they will not be at the position x\u2009=\u20095 at any moment during the operation. Zane\u2019s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.", "input_spec": "The first line contains three integers n, m, and k (2\u2009\u2264\u2009n\u2009\u2264\u2009106, 1\u2009\u2264\u2009m\u2009\u2264\u2009n, 1\u2009\u2264\u2009k\u2009\u2264\u20093\u00b7105)\u00a0\u2014 the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1,\u2009h2,\u2009...,\u2009hm (1\u2009\u2264\u2009hi\u2009\u2264\u2009n)\u00a0\u2014 the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi)\u00a0\u2014 the positions of the cups to be swapped.", "output_spec": "Print one integer\u00a0\u2014 the final position along the x-axis of the bone.", "sample_inputs": ["7 3 4\n3 4 6\n1 2\n2 5\n5 7\n7 1", "5 1 2\n2\n1 2\n2 4"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample, after the operations, the bone becomes at x\u2009=\u20092, x\u2009=\u20095, x\u2009=\u20097, and x\u2009=\u20091, respectively.In the second sample, after the first operation, the bone becomes at x\u2009=\u20092, and falls into the hole onto the ground."}, "positive_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 = 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"}, {"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"} {"nl": {"description": "You are given an array of $$$n$$$ integers $$$a_1,a_2,\\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\\dots,b_n$$$ such that: The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\\{a_1,a_2,\\dots,a_n\\}$$$ and $$$\\{b_1,b_2,\\dots,b_n\\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$. For all $$$k=1,2,\\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\\dots,n$$$, it must hold $$$$$$b_1+b_2+\\cdots+b_k\\not=0\\,.$$$$$$ If an array $$$b_1,b_2,\\dots, b_n$$$ with the required properties does not exist, you have to print NO.", "input_spec": "Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\le t \\le 1000$$$) \u2014 the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\\le n\\le 50$$$) \u00a0\u2014 the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\\dots, a_n$$$ ($$$-50\\le a_i\\le 50$$$) \u00a0\u2014 the elements of $$$a$$$.", "output_spec": "For each testcase, if there is not an array $$$b_1,b_2,\\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\\dots,b_n$$$. If there is more than one array $$$b_1,b_2,\\dots,b_n$$$ satisfying the required properties, you can print any of them.", "sample_inputs": ["4\n4\n1 -2 3 -4\n3\n0 0 0\n5\n1 -1 1 -1 1\n6\n40 -31 -9 0 13 -40"], "sample_outputs": ["YES\n1 -2 3 -4\nNO\nYES\n1 1 -1 1 -1\nYES\n-40 13 40 0 -9 -31"], "notes": "NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds: The first element of $$$b$$$ is $$$1$$$. The sum of the first two elements of $$$b$$$ is $$$-1$$$. The sum of the first three elements of $$$b$$$ is $$$2$$$. The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds: The first element of $$$b$$$ is $$$1$$$. The sum of the first two elements of $$$b$$$ is $$$2$$$. The sum of the first three elements of $$$b$$$ is $$$1$$$. The sum of the first four elements of $$$b$$$ is $$$2$$$. The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds: The first element of $$$b$$$ is $$$-40$$$. The sum of the first two elements of $$$b$$$ is $$$-27$$$. The sum of the first three elements of $$$b$$$ is $$$13$$$. The sum of the first four elements of $$$b$$$ is $$$13$$$. The sum of the first five elements of $$$b$$$ is $$$4$$$. The sum of the first six elements of $$$b$$$ is $$$-27$$$. "}, "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"}, {"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"}], "negative_code": [], "src_uid": "e57345f5757654749b411727ebb99c80"} {"nl": {"description": "Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some \"extra\" time if for its running time, a seconds, an inequality 2a\u2009\u2264\u2009v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met: v is a positive integer; all correct solutions pass the system testing; at least one correct solution passes the system testing with some \"extra\" time; all wrong solutions do not pass the system testing; value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). The second line contains n space-separated positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009100) \u2014 the running time of each of m wrong solutions in seconds. ", "output_spec": "If there is a valid TL value, print it. Otherwise, print -1.", "sample_inputs": ["3 6\n4 5 2\n8 9 6 10 7 11", "3 1\n3 4 5\n6"], "sample_outputs": ["5", "-1"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.The area looks like a strip of cells 1\u2009\u00d7\u2009n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 length of the strip. Next line contains a string of length n which consists of characters \"<\" and \">\" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1\u2009\u2264\u2009di\u2009\u2264\u2009109)\u00a0\u2014 the length of the jump from the i-th cell.", "output_spec": "Print \"INFINITE\" (without quotes) if grasshopper will continue his jumps forever. Otherwise print \"FINITE\" (without quotes).", "sample_inputs": ["2\n><\n1 2", "3\n>><\n2 1 1"], "sample_outputs": ["FINITE", "INFINITE"], "notes": "NoteIn the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite."}, "positive_code": [{"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}"}, {"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 @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"}, {"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"}], "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"} {"nl": {"description": "Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things: Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one); Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves: You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$. You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$. You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$. You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$. You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) \u2014 the lower bound on the sum of the array.", "output_spec": "For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $$$n$$$.", "sample_inputs": ["5\n1\n5\n42\n1337\n1000000000"], "sample_outputs": ["0\n3\n11\n72\n63244"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi\u2009+\u20091... sj, i\u2009\u2264\u2009j).Then the simple prettiness of s is defined by the formula:The prettiness of s equals Find the prettiness of the given song title.We assume that the vowels are I,\u2009E,\u2009A,\u2009O,\u2009U,\u2009Y.", "input_spec": "The input contains a single string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20095\u00b7105) \u2014 the title of the song.", "output_spec": "Print the prettiness of the song with the absolute or relative error of at most 10\u2009-\u20096.", "sample_inputs": ["IEAIAIO", "BYOB", "YISVOWEL"], "sample_outputs": ["28.0000000", "5.8333333", "17.0500000"], "notes": "NoteIn the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28."}, "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject E {\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 chars = next.toCharArray\n val n = chars.length\n val vowels = Set('A', 'Y', 'E', 'U', 'I', 'O')\n var ans = 0.0d\n val sum1 = new Array[Double](n + 1)\n for (i <- 1 until n + 1) {\n sum1(i) = sum1(i - 1) + (1.0d / i)\n }\n val sum2 = new Array[Double](n + 1)\n sum2(n) = 1.0d / n\n for (i <- n - 1 to 0 by - 1) {\n sum2(i) = sum2(i + 1) + (1.0d * n - i + 1) / i\n }\n (1 to n).foreach(i => {\n if (vowels.contains(chars(i - 1))) {\n val min = Math.min(i, n - i + 1)\n val max = Math.max(i, n - i + 1)\n ans += min - 1\n ans += min * (sum1(max - 1) - sum1(min - 1))\n ans += sum2(max)\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"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject E {\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 chars = next.toCharArray\n val n = chars.length\n val vowels = Set('A', 'Y', 'E', 'U', 'I', 'O')\n var ans = 0.0f\n val sum1 = new Array[Float](n + 1)\n for (i <- 1 until n + 1) {\n sum1(i) = sum1(i - 1) + (1.0f / i)\n }\n val sum2 = new Array[Float](n + 1)\n sum2(n) = 1.0f / n\n for (i <- n - 1 to 0 by - 1) {\n sum2(i) = sum2(i + 1) + (1.0f * n - i + 1) / i\n }\n (1 to n).foreach(i => {\n if (vowels.contains(chars(i - 1))) {\n val min = Math.min(i, n - i + 1)\n val max = Math.max(i, n - i + 1)\n ans += min - 1\n ans += min * (sum1(max - 1) - sum1(min - 1))\n ans += sum2(max)\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.StringTokenizer\n\nobject E {\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 chars = next.toCharArray\n val n = chars.length\n val vowels = Set('A', 'Y', 'E', 'U', 'I', 'O')\n var ans = 0.0f\n val sum1 = new Array[Float](n + 1)\n for (i <- 1 until n + 1) {\n sum1(i) = sum1(i - 1) + (1.0f / i)\n }\n val sum2 = new Array[Float](n + 1)\n for (i <- 1 until n + 1) {\n sum2(i) = sum2(i - 1) + (1.0f * n - i + 1) / i\n }\n (1 to n).foreach(i => {\n if (vowels.contains(chars(i - 1))) {\n val min = Math.min(i, n - i + 1)\n val max = Math.max(i, n - i + 1)\n ans += min - 1\n ans += min * (sum1(max) - sum1(min - 1))\n ans += sum2(n) - sum2(max)\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"}], "src_uid": "2b37188c17b7cbc3e533e9ad341441b2"} {"nl": {"description": "Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), that is the number of cafe visitors. Each of the following n lines has two space-separated integers hi and mi (0\u2009\u2264\u2009hi\u2009\u2264\u200923;\u00a00\u2009\u2264\u2009mi\u2009\u2264\u200959), representing the time when the i-th person comes into the cafe. Note that the time is given in the chronological order. All time is given within one 24-hour period.", "output_spec": "Print a single integer \u2014 the minimum number of cashes, needed to serve all clients next day.", "sample_inputs": ["4\n8 0\n8 10\n8 10\n8 45", "3\n0 12\n10 11\n22 22"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash."}, "positive_code": [{"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 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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1\u2009\u2264\u2009a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws each box vertically down on the first wi stairs of the staircase, that is, the box covers stairs with numbers 1,\u20092,\u2009...,\u2009wi. Each thrown box flies vertically down until at least one of the two following events happen: the bottom of the box touches the top of a stair; the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width wi cannot touch the stair number wi\u2009+\u20091.You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109;\u00a0ai\u2009\u2264\u2009ai\u2009+\u20091). The next line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of boxes. Each of the following m lines contains a pair of integers wi,\u2009hi (1\u2009\u2264\u2009wi\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009hi\u2009\u2264\u2009109) \u2014 the size of the i-th thrown box. The numbers in the lines are separated by spaces.", "output_spec": "Print m integers \u2014 for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3", "3\n1 2 3\n2\n1 1\n3 1", "1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10"], "sample_outputs": ["1\n3\n4\n6", "1\n3", "1\n3\n13\n23\n33"], "notes": "NoteThe first sample are shown on the picture. "}, "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 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"}, {"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"} {"nl": {"description": "Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.", "input_spec": "The first line contains string s of length n. The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.", "output_spec": "Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line \"impossible\" (without the quotes). If there are multiple possible answers, print any of them.", "sample_inputs": ["0001\n1011", "000\n111"], "sample_outputs": ["0011", "impossible"], "notes": "NoteIn the first sample different answers are possible, namely \u2014 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101."}, "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, _) => 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"}, {"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"} {"nl": {"description": "Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second. ", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the quantity of the numbers in the both given permutations. Next line contains n space-separated integers \u2014 the first permutation. Each number between 1 to n will appear in the permutation exactly once. Next line describe the second permutation in the same format.", "output_spec": "Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.", "sample_inputs": ["3\n3 2 1\n1 2 3", "5\n1 2 3 4 5\n1 5 2 3 4", "5\n1 5 2 3 4\n1 2 3 4 5"], "sample_outputs": ["2", "1", "3"], "notes": "NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this: 1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5 So he needs three moves."}, "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"}, {"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"}], "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"} {"nl": {"description": "A permutation p of length n is a sequence of distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n). A permutation is an identity permutation, if for any i the following equation holds pi\u2009=\u2009i. A swap (i,\u2009j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q)\u2009=\u2009m, using the minimum number of swaps. Help him do that.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the length of permutation p. The second line contains n distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 Valera's initial permutation. The last line contains integer m (0\u2009\u2264\u2009m\u2009<\u2009n).", "output_spec": "In the first line, print integer k \u2014 the minimum number of swaps. In the second line, print 2k integers x1,\u2009x2,\u2009...,\u2009x2k \u2014 the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1,\u2009x2), (x3,\u2009x4), ..., (x2k\u2009-\u20091,\u2009x2k). If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.", "sample_inputs": ["5\n1 2 3 4 5\n2", "5\n2 1 4 5 3\n2"], "sample_outputs": ["2\n1 2 1 3", "1\n1 2"], "notes": "NoteSequence x1,\u2009x2,\u2009...,\u2009xs is lexicographically smaller than sequence y1,\u2009y2,\u2009...,\u2009ys, if there is such integer r (1\u2009\u2264\u2009r\u2009\u2264\u2009s), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009...,\u2009xr\u2009-\u20091\u2009=\u2009yr\u2009-\u20091 and xr\u2009<\u2009yr. "}, "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by hama_du on 2014/06/14.\n */\nobject ProblemD extends App {\n val INF = 1000000000\n\n def breakLoops(count: Int, initialLoop: ArrayBuffer[ArrayBuffer[Int]]) = {\n var loops = initialLoop\n val answers = new Array[Int](count * 2)\n (1 to count).foreach(i => {\n var bestV = INF\n var smallestLi = -1\n for ((loop, li) <- loops.zipWithIndex) {\n if (loop.size >= 2) {\n for (v <- loop) {\n if (bestV > v) {\n bestV = v\n smallestLi = li\n }\n }\n }\n }\n\n val bestLoop = loops(smallestLi)\n val sortedLoop = bestLoop.zipWithIndex.sorted\n answers((i-1)*2) = sortedLoop(0)._1+1\n answers((i-1)*2+1) = sortedLoop(1)._1+1\n\n val left = Math.min(sortedLoop(0)._2, sortedLoop(1)._2)\n val right = Math.max(sortedLoop(0)._2, sortedLoop(1)._2)\n loops += bestLoop.slice(0, left+1) ++ bestLoop.slice(right+1,bestLoop.size)\n loops += bestLoop.slice(left+1, right+1)\n loops(smallestLi) = ArrayBuffer[Int]()\n loops = loops.filter(p => p.size >= 2)\n })\n answers\n }\n\n def connectLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n val l = loops.size\n val answers = new Array[Int](count * 2)\n (1 to count).foreach(i => {\n answers((i-1)*2) = 1\n answers((i-1)*2+1) = loops(i)(0)+1\n })\n answers\n }\n\n def countSwaps(loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n loops.map(loop => loop.size-1).sum\n }\n\n def makeLoops(array: Array[Int]): ArrayBuffer[ArrayBuffer[Int]] = {\n val n = array.size\n val done = new Array[Boolean](n)\n val loops = new ArrayBuffer[ArrayBuffer[Int]]()\n (0 until n).foreach(i => {\n if (!done(i)) {\n val loopIndices = new ArrayBuffer[Int]()\n var li = i\n while (!done(li)) {\n done(li) = true\n loopIndices += li\n li = array(li)\n }\n loops += loopIndices\n }\n })\n loops\n }\n\n val in = new Scanner(System.in)\n val n = in.nextInt\n val array = (0 until n).map(_ => in.nextInt-1).toArray\n val m = in.nextInt\n val loops = makeLoops(array)\n val swapValue = countSwaps(loops)\n\n val countOperation = Math.abs(m-swapValue)\n\n println(countOperation)\n if (m < swapValue) {\n val answer = breakLoops(countOperation, loops)\n println(answer.mkString(\" \"))\n } else if (m > swapValue) {\n val answer = connectLoops(countOperation, loops)\n println(answer.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by hama_du on 2014/06/14.\n */\nobject ProblemD extends App {\n val INF = 1000000000\n\n def breakLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n val answers = new Array[Int](count * 2)\n (1 to count).foreach(i => {\n var best = ((INF, INF), -1, -1)\n for ((loop, li) <- loops.zipWithIndex) {\n for ((value, vi) <- loop.zipWithIndex) {\n val min = Math.min(value, loop((vi+1)%loop.size))\n val max = Math.max(value, loop((vi+1)%loop.size))\n if (best._1._1 > min || (best._1._1 == min && best._1._2 > max)) {\n best = ((min, max), li, vi)\n }\n }\n }\n answers((i-1)*2) = best._1._1+1\n answers((i-1)*2+1) = best._1._2+1\n val deleteIndex = (best._3+1) % loops(best._2).size\n loops(best._2).remove(deleteIndex)\n })\n answers\n }\n\n def connectLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n val l = loops.size\n val answers = new Array[Int](count * 2)\n (1 to count).foreach(i => {\n answers((i-1)*2) = 1\n answers((i-1)*2+1) = loops(i)(0)+1\n })\n answers\n }\n\n def countSwaps(loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n loops.map(loop => loop.size-1).sum\n }\n\n def makeLoops(array: Array[Int]): ArrayBuffer[ArrayBuffer[Int]] = {\n val n = array.size\n val done = new Array[Boolean](n)\n val loops = new ArrayBuffer[ArrayBuffer[Int]]()\n (0 until n).foreach(i => {\n if (!done(i)) {\n val loopIndices = new ArrayBuffer[Int]()\n var li = i\n while (!done(li)) {\n done(li) = true\n loopIndices += li\n li = array(li)\n }\n loops += loopIndices\n }\n })\n loops\n }\n\n val in = new Scanner(System.in)\n val n = in.nextInt\n val array = (0 until n).map(_ => in.nextInt-1).toArray\n val m = in.nextInt\n val loops = makeLoops(array)\n val swapValue = countSwaps(loops)\n\n\n val countOperation = Math.abs(m-swapValue)\n\n println(countOperation)\n if (m < swapValue) {\n val answer = breakLoops(countOperation, loops)\n println(answer.mkString(\" \"))\n } else if (m > swapValue) {\n val answer = connectLoops(countOperation, loops)\n println(answer.mkString(\" \"))\n }\n}\n"}, {"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\n\n/**\n * Created by hama_du on 2014/06/14.\n */\nobject ProblemD extends App {\n val INF = 1000000000\n\n def breakLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n val answers = new Array[Int](count * 2)\n (1 to count).foreach(i => {\n var best = ((INF, INF), -1, -1)\n for ((loop, li) <- loops.zipWithIndex) {\n if (loop.size >= 2) {\n for ((value, vi) <- loop.zipWithIndex) {\n val min = Math.min(value, loop((vi + 1) % loop.size))\n val max = Math.max(value, loop((vi + 1) % loop.size))\n if (best._1._1 > min || (best._1._1 == min && best._1._2 > max)) {\n best = ((min, max), li, vi)\n }\n }\n }\n }\n answers((i-1)*2) = best._1._1+1\n answers((i-1)*2+1) = best._1._2+1\n val deleteIndex = (best._3+1) % loops(best._2).size\n loops(best._2).remove(deleteIndex)\n })\n answers\n }\n\n def connectLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n val l = loops.size\n val answers = new Array[Int](count * 2)\n (1 to count).foreach(i => {\n answers((i-1)*2) = 1\n answers((i-1)*2+1) = loops(i)(0)+1\n })\n answers\n }\n\n def countSwaps(loops: ArrayBuffer[ArrayBuffer[Int]]) = {\n loops.map(loop => loop.size-1).sum\n }\n\n def makeLoops(array: Array[Int]): ArrayBuffer[ArrayBuffer[Int]] = {\n val n = array.size\n val done = new Array[Boolean](n)\n val loops = new ArrayBuffer[ArrayBuffer[Int]]()\n (0 until n).foreach(i => {\n if (!done(i)) {\n val loopIndices = new ArrayBuffer[Int]()\n var li = i\n while (!done(li)) {\n done(li) = true\n loopIndices += li\n li = array(li)\n }\n loops += loopIndices\n }\n })\n loops\n }\n\n val in = new Scanner(System.in)\n val n = in.nextInt\n val array = (0 until n).map(_ => in.nextInt-1).toArray\n val m = in.nextInt\n val loops = makeLoops(array)\n val swapValue = countSwaps(loops)\n\n\n val countOperation = Math.abs(m-swapValue)\n\n println(countOperation)\n if (m < swapValue) {\n val answer = breakLoops(countOperation, loops)\n println(answer.mkString(\" \"))\n } else if (m > swapValue) {\n val answer = connectLoops(countOperation, loops)\n println(answer.mkString(\" \"))\n }\n}\n"}], "src_uid": "e7517e32caa1b044ebf1d39276560b47"} {"nl": {"description": "Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.", "input_spec": "The first line contains two integers n and k (1\u2009\u2009\u2264\u2009\u2009n,\u2009k\u2009\u2009\u2264\u2009\u2009500)\u00a0\u2014 the number of coins and the price of the chocolate, respectively. Next line will contain n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009500)\u00a0\u2014 the values of Pari's coins. It's guaranteed that one can make value k using these coins.", "output_spec": "First line of the output must contain a single integer q\u2014 the number of suitable values x. Then print q integers in ascending order\u00a0\u2014 the values that Arya can make for some subset of coins of Pari that pays for the chocolate.", "sample_inputs": ["6 18\n5 6 1 10 12 2", "3 50\n25 25 50"], "sample_outputs": ["16\n0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18", "3\n0 25 50"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leqslant n \\leqslant 10^5$$$)\u00a0\u2014 the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either \"zero\" which corresponds to the digit $$$0$$$ or \"one\" which corresponds to the digit $$$1$$$.", "output_spec": "Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.", "sample_inputs": ["4\nezor", "10\nnznooeeoer"], "sample_outputs": ["0", "1 1 0"], "notes": "NoteIn the first example, the correct initial ordering is \"zero\".In the second example, the correct initial ordering is \"oneonezero\"."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of abbreviations to process. Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.", "output_spec": "For each abbreviation given in the input, find the year of the corresponding Olympiad.", "sample_inputs": ["5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0", "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999"], "sample_outputs": ["2015\n12015\n1991\n1989\n1990", "1989\n1999\n2999\n9999"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n\n // 1989 - 1998 1 digit\n\n def findYear(s: String) = {\n val len = s.length\n var pow = 10\n var offset = 0\n for (_ <- 1 until len) {\n offset += pow\n pow *= 10\n }\n\n val year = s.toInt\n val L = 1989 + offset\n val m = L / pow\n val result = m * pow + year\n if (result < L) result + pow else result\n }\n\n val n = readInt()\n (1 to n).foreach { _ =>\n val s = readLine().drop(4)\n println(findYear(s))\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n\n // 1989 - 1998 1 digit\n\n def findYear(s: String) = {\n val len = s.length\n var pow = 10\n var offset = 0\n for (_ <- 1 until len) {\n offset += pow\n pow *= 10\n }\n\n val year = s.toInt\n val L = 1989 + offset\n if (year == 0) {\n 1990\n } else {\n val m = L / pow\n val result = m * pow + year\n if (result < L) result + pow else result\n }\n }\n\n val n = readInt()\n (1 to n).foreach { _ =>\n val s = readLine().drop(4)\n println(findYear(s))\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject C extends App {\n /*\n 1989 - 1998 -> %10 // 1 10\n 1999 - 2098 -> %100 // 2 100\n 2099 - 3098 -> %1000 // 3 1000\n 3099 - 13098 -> %10000 // 4 10000\n ...\n -> // 5 100000\n -> // 6 1000000\n -> // 7 10000000\n -> // 8 100000000\n -> // 9 1000000000\n\n 13098 -> 3098\n\n 9 -> 1989\n 1 digit -> 199x\n 99 -> 1999\n 2 digits -> 19xy\n 099 -> 2099\n 3 digits, 1st != 0 -> 2xyz\n 3 digits, 1st == 0 -> 3xyz\n 4 digits, 1st != 0,1,2,3 -> x\n 4 digits, 1st == 0,1,2,3 -> 1abcd\n 5 digits, 1st != 0,1 -> x\n 5 digits, 1st == 0,1 -> 1abcde\n 6 digits, 1st != 0,1 -> x\n 6 digits, 1st == 0,1 -> 1abcdef\n */\n\n def findYear(s: String) = {\n if (s == \"9\") \"1989\"\n else if (s.length == 1) \"199\" + s\n else if (s == \"99\") \"1999\"\n else if (s.length == 2) \"20\" + s\n else if (s == \"099\") \"2099\"\n else if (s.length == 3 && s(0) != '0') \"2\" + s\n else if (s.length == 3) \"3\" + s\n else if (s.length == 4 && (s != \"3099\" && (s(0) - '0' <= 2 || (s(0) == '3' && s(1) == '0')))) \"1\" + s\n else if (s.length == 4) s\n else if (s.length == 5 && s != \"13099\" && (s(0) == '0' || s(0) == '1' && s(1) <= '2' || s.take(3) == \"130\")) \"1\" + s\n else if (s.length == 5) s\n else if (s.length == 6 && s != \"113099\" && (s(0) == '0' || s.take(2) == \"10\" || s.take(3) == \"111\" || s.take(3) == \"110\" || s.take(3) == \"112\" || s.take(4) == \"1130\")) \"1\" + s\n else if (s.length == 6) s\n else s\n }\n\n// println(findAbb(\"1\"))\n\n val n = readInt()\n (1 to n).foreach { _ =>\n val s = readLine().drop(4)\n println(findYear(s))\n }\n\n// val map = collection.mutable.Map[String, Int]()\n// val abbList = collection.mutable.ListBuffer[String]()\n// val left = 1989\n// val right = 5913099\n//\n// for (year <- left to right) {\n// var digit = 1\n// var abb = \"\" + (year % Math.pow(10, digit).toInt)\n// while (map.contains(abb)) {\n// digit += 1\n// abb = \"\" + (year % Math.pow(10, digit).toInt)\n// abb = (\"0\" * (digit - abb.length)) + abb\n// }\n// map.put(abb, year)\n// abbList += abb\n// }\n//\n// for (abb <- abbList) {\n// val year = map(abb)\n// val actual = findYear(abb)\n//\n// if (actual != \"\" + map(abb)) {\n// println(actual + \" | \" + map(abb) + \" -> \" + abb)\n// }\n// }\n}\n"}], "src_uid": "31be4d38a8b5ea8738a65bfee24a5a21"} {"nl": {"description": "Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of V (1\u2009\u2264\u2009V\u2009\u2264\u2009100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures.Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants P (10\u2009\u2264\u2009P\u2009\u2264\u20091000) of the village, they respond with a random non-negative integer k, drawn from one of two types of probability distributions: Poisson (d'avril) distribution: the probability of getting an answer k is for k\u2009=\u20090,\u20091,\u20092,\u20093,\u2009..., Uniform distribution: the probability of getting an answer k is for k\u2009=\u20090,\u20091,\u20092,\u2009...,\u20092P. Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution.Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?", "input_spec": "The first line of input will contain the number of villages V (1\u2009\u2264\u2009V\u2009\u2264\u2009100). The following V lines each describe one village. The description of each village consists of 250 space-separated integers k, drawn from one of the above distributions.", "output_spec": "Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answer came from a uniform distribution.", "sample_inputs": ["2\n92 100 99 109 93 105 103 106 101 99 ... (input is truncated)\n28 180 147 53 84 80 180 85 8 16 ... (input is truncated)"], "sample_outputs": ["poisson\nuniform"], "notes": "NoteThe full example input is visually represented below, along with the probability distribution function it was drawn from (the y-axis is labeled by its values multiplied by 250)."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\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 val Z = 250\n\n read()\n val n = int()\n for (i <- 1 to n) {\n read()\n val arr = Array.fill(Z)(int())\n\n val avg = arr.sum.toDouble / Z\n val disp = arr.map(x => (x - avg) * (x - avg)).sum / (Z - 1)\n\n val limit = Math.sqrt(avg * avg * avg / 3)\n //println(s\"$avg, $disp, $limit\")\n if (disp > limit) println(\"uniform\") else println(\"poisson\")\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nobject E 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 val Z = 250\n\n read()\n val n = int()\n for (i <- 1 to n) {\n read()\n val arr = Array.fill(Z)(int())\n\n val avg = arr.sum.toDouble / Z\n val disp = arr.map(x => (x - avg) * (x - avg)).sum / (Z - 1)\n\n val limit = Math.sqrt(avg * avg * avg / 3)\n //println(s\"$avg, $disp, $limit\")\n val ans = if (disp > limit) {\n //uniform\n avg\n } else {\n //poisson\n avg\n }\n println(ans.round)\n }\n\n}\n"}], "src_uid": "e1dad71bee6d60b4d6dc33ea8cf09ba1"} {"nl": {"description": "A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.", "input_spec": "The first line contains a pair of integer numbers n and v (1\u2009\u2264\u2009n\u2009\u2264\u2009105; 1\u2009\u2264\u2009v\u2009\u2264\u2009109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti,\u2009pi (1\u2009\u2264\u2009ti\u2009\u2264\u20092; 1\u2009\u2264\u2009pi\u2009\u2264\u2009104), where ti is the vehicle type (1 \u2013 a kayak, 2 \u2013 a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.", "output_spec": "In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.", "sample_inputs": ["3 2\n1 2\n2 7\n1 3"], "sample_outputs": ["7\n2"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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 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"}], "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"} {"nl": {"description": "There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C\u00b7k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.", "input_spec": "The first line contains five integers n, A, B, C and T (1\u2009\u2264\u2009n,\u2009A,\u2009B,\u2009C,\u2009T\u2009\u2264\u20091000). The second string contains n integers ti (1\u2009\u2264\u2009ti\u2009\u2264\u2009T).", "output_spec": "Output one integer \u00a0\u2014 the answer to the problem.", "sample_inputs": ["4 5 5 3 5\n1 5 5 4", "5 3 1 1 3\n2 2 2 1 1", "5 5 3 4 5\n1 2 3 4 5"], "sample_outputs": ["20", "15", "35"], "notes": "NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n\u00b7A\u2009=\u200920 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5\u2009-\u20094\u00b73)\u2009+\u2009(5\u2009-\u20093\u00b73)\u2009+\u2009(5\u2009-\u20092\u00b73)\u2009+\u2009(5\u2009-\u20091\u00b73)\u2009+\u20095\u2009=\u2009\u2009-\u20095 points. This is 35 in total."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "281b95c3686c94ae1c1e4e2a18b7fcc4"} {"nl": {"description": "Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result \"greater\", \"smaller\" or \"equal\". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons \"less\", \"equal\", \"greater\" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$)\u00a0\u2014 the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \\le a_{i,j} \\le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction.", "output_spec": "Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street.", "sample_inputs": ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"], "sample_outputs": ["2 2 2 \n2 2 2", "2 3 \n3 2"], "notes": "NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column "}, "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 Hmax = Array.ofDim[Int](N)\n val Vmax= Array.ofDim[Int](M)\n val H, V = Array.ofDim[Int](N, M)\n\n REP(N) { i =>\n val as = Array.ofDim[Int](M)\n REP(M) { j =>\n as(j) = A(i)(j)\n }\n val zip = new Zipper(as)\n\n REP(M) { j =>\n H(i)(j) = zip.get(A(i)(j))\n }\n\n Hmax(i) = zip.last\n }\n\n REP(M) { j =>\n val as = Array.ofDim[Int](N)\n REP(N) { i =>\n as(i) = A(i)(j)\n }\n val zip = new Zipper(as)\n\n REP(N) { i =>\n V(i)(j) = zip.get(A(i)(j))\n }\n\n Vmax(j) = zip.last\n }\n\n debug(Hmax)\n debug(Vmax)\n DEBUG {\n debug(\"H\")\n REP(N) { i =>\n debug(H(i))\n }\n debug(\"V\")\n REP(N) { i =>\n debug(V(i))\n }\n }\n\n val ans = Array.ofDim[Int](N, M)\n REP(N) { i =>\n REP(M) { j =>\n val v = max(H(i)(j), V(i)(j)) + max(Hmax(i) - H(i)(j), Vmax(j) - V(i)(j))\n ans(i)(j) = v\n }\n }\n\n REP(N) { i =>\n out.println(ans(i).mkString(\" \"))\n }\n }\n\n class Zipper(as: Array[Int]) {\n import java.util\n\n val A = as.distinct\n util.Arrays.sort(A)\n\n def get(x: Int): Int = {\n lowerBound(A, x) + 1\n }\n\n def last = A.length\n }\n\n // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] \u306e 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 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 val N, M = ni()\n val A = nm(N, M)\n val Hmax = Array.ofDim[Int](N)\n val Vmax= Array.ofDim[Int](M)\n val H, V = Array.ofDim[Int](N, M)\n\n REP(N) { i =>\n val as = Array.ofDim[Int](M)\n REP(M) { j =>\n as(j) = A(i)(j)\n }\n val zip = new Zipper(as)\n\n REP(M) { j =>\n H(i)(j) = zip.get(A(i)(j))\n }\n\n Hmax(i) = zip.last\n }\n\n REP(M) { j =>\n val as = Array.ofDim[Int](N)\n REP(N) { i =>\n as(i) = A(i)(j)\n }\n val zip = new Zipper(as)\n\n REP(N) { i =>\n V(i)(j) = zip.get(A(i)(j))\n }\n\n Vmax(j) = zip.last\n }\n\n debug(Hmax)\n debug(Vmax)\n DEBUG {\n debug(\"H\")\n REP(N) { i =>\n debug(H(i))\n }\n debug(\"V\")\n REP(N) { i =>\n debug(V(i))\n }\n }\n\n val ans = Array.ofDim[Int](N, M)\n REP(N) { i =>\n REP(M) { j =>\n val v = max(H(i)(j) + Vmax(j) - V(i)(j), V(i)(j) + Hmax(i) - H(i)(j))\n ans(i)(j) = v\n }\n }\n\n REP(N) { i =>\n out.println(ans(i).mkString(\" \"))\n }\n }\n\n class Zipper(as: Array[Int]) {\n import java.util\n\n val A = as.distinct\n util.Arrays.sort(A)\n\n def get(x: Int): Int = {\n lowerBound(A, x) + 1\n }\n\n def last = A.length\n }\n\n // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] \u306e 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 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"}], "src_uid": "206861107f0c06d3c8e358a85b9ddd7f"} {"nl": {"description": "You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \\to 1 \\to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \\to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^5$$$)\u00a0\u2014 the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\leq u, v \\leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \\dots, a_{n-1}$$$ ($$$1 \\leq a_i \\le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.", "sample_inputs": ["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"], "sample_outputs": ["17\n2 5 11\n-1"], "notes": "NoteFor the first test case, there are only two paths having one edge each: $$$1 \\to 2$$$ and $$$2 \\to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case."}, "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 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 g = new Array[Vector[pair]](n+1)\n val ans = new Array[Int](n+1)\n for (i <- 1 to n) {\n g(i) = Vector[pair]()\n }\n var x = 0\n var y = 0\n var ok = true\n for (i <- 1 until n) {\n x = readInt()\n y = readInt()\n g(x) +:= pair(y, i)\n g(y) +:= pair(x, i)\n }\n for (i <- 1 to n) {\n if (g(i).length > 2) {\n ok = false\n }\n }\n if (!ok) {\n writer.println(-1)\n } else {\n for (i <- 1 to n) {\n if (g(i).length == 1) {\n dfs(i, 0)\n }\n }\n for (i <- 1 until n) {\n writer.print(ans(i) + \" \")\n }\n writer.println()\n }\n def dfs(v: Int, p: Int): Int = {\n if (p == 0) {\n ans(g(v)(0).b) = 2\n dfs(g(v)(0).a, v)\n } else {\n if (g(v).length == 1){\n return 0\n }\n var x = g(v)(0)\n var y = g(v)(1)\n if (x.a == p) {\n if (ans(x.b) == 2) {\n ans(y.b) = 3\n dfs(y.a, v)\n } else {\n ans(y.b) = 2\n dfs(y.a, v)\n }\n } else {\n if (ans(y.b) == 2) {\n ans(x.b) = 3\n dfs(x.a, v)\n } else {\n ans(x.b) = 2\n dfs(x.a, v)\n }\n }\n }\n return 0\n }\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": "0639fbeb3a5be67a4c0beeffe8f5d43b"} {"nl": {"description": "Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if: $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$; $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$; $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$; $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^6$$$)\u00a0\u2014 the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.", "output_spec": "For each test case, output on a separate line: \"YES\" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["5\n1\n4041\n4042\n8081\n8079"], "sample_outputs": ["NO\nYES\nYES\nYES\nNO"], "notes": null}, "positive_code": [{"source_code": "import io.StdIn.readLine\n\nobject newyearsnumber {\n def main(args: Array[String]): Unit = {\n val T = readLine().toInt\n for(i <- 1 to T){\n val N = readLine().toInt\n if((N%2020) <= N/2021){\n println(\"YES\")\n }else{\n println(\"NO\")\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "3ec1b7027f487181dbdfb12f295f11ae"} {"nl": {"description": "You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$n-1 \\le m \\le min(\\frac{n(n-1)}{2}, 2 \\cdot 10^5)$$$, $$$1 \\le a, b, c \\le n$$$) \u2014 the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \\dots, p_m$$$ ($$$1 \\le p_i \\le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$u_i \\ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i.\u2009e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \\ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$, $$$\\sum m \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum possible price of Mike's trip if you distribute prices between edges optimally.", "sample_inputs": ["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"], "sample_outputs": ["7\n12"], "notes": "NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:"}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n for (_ <- 1 to nextInt) {\n val n, m, a0, b0, c0 = nextInt\n val a = a0 - 1\n val b = b0 - 1\n val c = c0 - 1\n val prices = nextLongs(m).sorted\n val priceSums = prices.scan(0L)(_ + _)\n\n val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n val adjs = adjBuilders.map(_.result())\n\n val distFromA, distFromB, distFromC = Array.fill(n)(Int.MaxValue)\n\n def bfs1(u0: Int, dist: Array[Int]): Unit = {\n val q = mutable.Queue(u0)\n dist(u0) = 0\n while (q.nonEmpty) {\n val u = q.dequeue()\n val d = dist(u) + 1\n for (v <- adjs(u)) {\n if (dist(v) == Int.MaxValue) {\n dist(v) = d\n q += v\n }\n }\n }\n }\n\n bfs1(a, distFromA)\n bfs1(c, distFromC)\n\n def bfs2(u0: Int, dist: Array[Int]): Long = {\n val q = mutable.Queue(u0)\n var min = Long.MaxValue\n dist(u0) = 0\n while (q.nonEmpty) {\n val u = q.dequeue()\n val d = distFromA(u) + distFromC(u) + dist(u)\n if (d < priceSums.length) {\n val cost = priceSums(d) + priceSums(dist(u))\n if (cost < min) min = cost\n }\n for (v <- adjs(u)) {\n if (dist(v) == Int.MaxValue) {\n dist(v) = dist(u) + 1\n q += v\n }\n }\n }\n min\n }\n\n val res = bfs2(b, distFromB)\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"}], "negative_code": [], "src_uid": "89be93cb82d9686ff099d156c309c146"} {"nl": {"description": "As their story unravels, a timeless tale is told once again...Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow.There are $$$n$$$ squares arranged in a row, and each of them can be painted either red or blue.Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square.Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color.For example, the imperfectness of \"BRRRBBR\" is $$$3$$$, with \"BB\" occurred once and \"RR\" occurred twice.Your goal is to minimize the imperfectness and print out the colors of the squares after painting. ", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains an integer $$$n$$$ ($$$1\\leq n\\leq 100$$$) \u2014 the length of the squares row. The second line of each test case contains a string $$$s$$$ with length $$$n$$$, containing characters 'B', 'R' and '?'. Here 'B' stands for a blue square, 'R' for a red square, and '?' for a blank square.", "output_spec": "For each test case, print a line with a string only containing 'B' and 'R', the colors of the squares after painting, which imperfectness is minimized. If there are multiple solutions, print any of them.", "sample_inputs": ["5\n7\n?R???BR\n7\n???R???\n1\n?\n1\nB\n10\n?R??RB??B?"], "sample_outputs": ["BRRBRBR\nBRBRBRB\nB\nB\nBRRBRBBRBR"], "notes": "NoteIn the first test case, if the squares are painted \"BRRBRBR\", the imperfectness is $$$1$$$ (since squares $$$2$$$ and $$$3$$$ have the same color), which is the minimum possible imperfectness."}, "positive_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 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"}, {"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 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}"}], "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"} {"nl": {"description": "Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\\cdot c=b$$$.For $$$n \\ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times.", "input_spec": "The first line of the input is a single integer $$$t\\ (1\\le t\\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\\ (2\\le n\\le 10^6, 1\\le k\\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. ", "output_spec": "Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac.", "sample_inputs": ["3\n5 1\n8 2\n3 4"], "sample_outputs": ["10\n12\n12"], "notes": "NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \\to 6 \\to 8 \\to 10 \\to 12$$$."}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "9fd9bc0a037b2948d60ac2bd5d57740f"} {"nl": {"description": "The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.", "input_spec": "The first line of the input contains two integers n and s (1\u2009\u2264\u2009n\u2009\u2264\u2009103; 1\u2009\u2264\u2009s\u2009<\u2009106) \u2014 the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers \u2014 the xi and yi coordinate values of the i-th location and the number ki of people in it (1\u2009\u2264\u2009ki\u2009<\u2009106). Each coordinate is an integer and doesn't exceed 104 in its absolute value. It is guaranteed that no two locations are at the same point and no location is at point (0;\u00a00).", "output_spec": "In the output, print \"-1\" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number \u2014 the minimum radius of the circle that the city needs to expand to in order to become a megacity. The answer is considered correct if the absolute or relative error don't exceed 10\u2009-\u20096.", "sample_inputs": ["4 999998\n1 1 1\n2 2 1\n3 3 1\n2 -2 1", "4 999998\n1 1 2\n2 2 1\n3 3 1\n2 -2 1", "2 1\n1 1 999997\n2 2 1"], "sample_outputs": ["2.8284271", "1.4142136", "-1"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n var Array(n, s) = in.next().split(' ').map(_.toInt)\n val data = (1 to n).map { _ =>\n val Array(x, y, k) = in.next().split(' ').map(_.toLong)\n (x * x + y * y, k)\n }.toList.sorted\n\n def solution(data: List[(Long, Long)], r: Long, left: Long): Long =\n if (left <= 0)\n r\n else if (data.isEmpty)\n -1l\n else\n solution(data.tail, data.head._1, left - data.head._2)\n\n val res = solution(data, 0, 1000000 - s)\n if (res < 0)\n println(-1)\n else\n println(Math.sqrt(res))\n\n}"}], "negative_code": [], "src_uid": "bcc758394d012519f0865479b3c6770c"} {"nl": {"description": "Polycarp got an array of integers $$$a[1 \\dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\\dots=a_n$$$)?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u00a0\u2014 the number of test cases in the test. The following are descriptions of the input test cases. The first line of the description of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u00a0\u2014 the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u00a0\u2014 elements of the array $$$a$$$.", "output_spec": "For each test case, print one integer \u00a0\u2014 the minimum number of operations to make all elements of the array $$$a$$$ equal.", "sample_inputs": ["3\n6\n3 4 2 4 1 2\n3\n1000 1002 998\n2\n12 11"], "sample_outputs": ["3\n4\n1"], "notes": "NoteFirst test case: $$$a=[3,4,2,4,1,2]$$$ take $$$a_3, a_5$$$ and perform an operation plus one on them, as a result we get $$$a=[3,4,3,4,2,2]$$$. $$$a=[3,4,3,4,2,2]$$$ we take $$$a_1, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,3,4,3,3]$$$. $$$a=[4,4,3,4,3,3]$$$ we take $$$a_3, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,4,4,4,4]$$$. There are other sequences of $$$3$$$ operations, after the application of which all elements become equal.Second test case: $$$a=[1000,1002,998]$$$ 2 times we take $$$a_1, a_3$$$ and perform an operation plus one on them, as a result we get $$$a=[1002,1002,1000]$$$. $$$a=[1002,1002,1000]$$$ also take $$$a_3$$$ 2 times and perform an operation plus one on it, as a result we get $$$a=[1002,1002,1002]$$$. Third test case: $$$a=[12,11]$$$ take $$$a_2$$$ and perform an operation plus one on it, as a result we get $$$a=[12,12]$$$. "}, "positive_code": [{"source_code": "import java.io._\r\nimport java.nio.file._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.+:\r\nimport scala.io.Codec\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n val sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)))\r\n val pw = new PrintWriter(System.out, false)\r\n\r\n val t = sc.nextInt()\r\n var i = 0\r\n for (i <- 0 to (t-1)) {\r\n Solver.solve(sc, pw, i)\r\n }\r\n pw.flush()\r\n }\r\n}\r\n\r\n/**\r\n * Actual solution\r\n */\r\nobject Solver {\r\n def solve(sc: Scanner, pw: PrintWriter, testcast: Int): Unit = {\r\n val n = sc.nextInt()\r\n val L = sc.nextLine.split(\" \").map(Integer.parseInt _).toList\r\n val N = L.min\r\n val M = L.max\r\n pw.println(M - N)\r\n }\r\n}\r\n\r\n/**\r\n * Scala implementation of a faster java.util.Scanner\r\n * See: http://codeforces.com/blog/entry/7018\r\n */\r\nclass Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {\r\n def this(reader: BufferedReader) = this(new LineNumberReader(reader))\r\n def this(reader: Reader) = this(new BufferedReader(reader))\r\n def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))\r\n def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))\r\n def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)\r\n def this(str: String) = this(new StringReader(str))\r\n\r\n private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)\r\n private[this] var current: Option[StringTokenizer] = None\r\n\r\n @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {\r\n current = if (tokenizers.hasNext) Some(tokenizers.next()) else None\r\n current\r\n }\r\n\r\n /**\r\n * Unlike Java's scanner which returns till end of current line, this actually returns the next line\r\n * @see line() if you want the Java behaviour\r\n */\r\n def nextLine(): String = {\r\n current = None // reset\r\n reader.readLine()\r\n }\r\n def lineNumber: Int = reader.getLineNumber\r\n def line(): String = tokenizer().get.nextToken(\"\\n\\r\")\r\n def nextString(): String = next()\r\n def nextChar(): Char = next().ensuring(_.length == 1).head\r\n def nextBoolean(): Boolean = next().toBoolean\r\n def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)\r\n def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)\r\n def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)\r\n def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)\r\n def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)\r\n def nextFloat(): Float = next().toFloat\r\n def nextDouble(): Double = next().toDouble\r\n def nextBigDecimal(): BigDecimal = BigDecimal(next())\r\n override def next() = tokenizer().get.nextToken()\r\n override def hasNext = tokenizer().nonEmpty\r\n override def close() = reader.close()\r\n}\r\n"}], "negative_code": [], "src_uid": "cf3cfcae029a6997ee62701eda959a60"} {"nl": {"description": "DZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.", "input_spec": "The first line contains two space-separated integers n and m . Each of the next m lines contains two space-separated integers xi and yi (1\u2009\u2264\u2009xi\u2009<\u2009yi\u2009\u2264\u2009n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order.", "output_spec": "Print a single integer \u2014 the maximum possible danger.", "sample_inputs": ["1 0", "2 1\n1 2", "3 2\n1 2\n2 3"], "sample_outputs": ["1", "2", "4"], "notes": "NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring)."}, "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 reaction = Array.fill[Set[Int]](n){Set.empty[Int]}\n (1 to m).foreach { _ =>\n val Array(x, y) = in.next().split(' ').map(_.toInt - 1)\n reaction(x) += y\n reaction(y) += x\n }\n var dangerous = 1l\n var bottleCanReact = reaction(0)\n var placed = Array.ofDim[Boolean](n)\n placed(0) = true\n (1 until n).foreach { _ =>\n (1 until n).find(i => !placed(i) && bottleCanReact.contains(i)) match {\n case Some(i) =>\n placed(i) = true\n bottleCanReact ++= reaction(i)\n dangerous <<= 1\n case None =>\n val i = (1 until n).find(i => !placed(i)).get\n placed(i) = true\n bottleCanReact ++= reaction(i)\n }\n }\n println(dangerous)\n\n}"}], "negative_code": [], "src_uid": "c36f4bb34543476abc31fe986032122d"} {"nl": {"description": "As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n\u2009+\u2009m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n\u2009+\u2009m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.", "input_spec": "The input consist of a single line with three space separated integers, n, m and k (0\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u200910).", "output_spec": "Output on a single line the desired probability with at least 4 digits after the decimal point.", "sample_inputs": ["5 3 1", "0 5 5", "0 1 0"], "sample_outputs": ["0.857143", "1", "0"], "notes": null}, "positive_code": [{"source_code": "object P026D {\n def main(args: Array[String]) = {\n val a = readLine.split(' ').map(x => x.toInt)\n println(math.max(0, 1- ((((a(1)-a(2)) to a(1)) zip ((a(0)+1) to (a(0)+a(2)+1)) toList).map(x => x._1*1.0/x._2) reduceLeft(_*_))))\n }\n}\n"}], "negative_code": [{"source_code": "object P026D {\n def main(args: Array[String]) = {\n val a = readLine.split(' ').map(x => x.toInt)\n println(1- ((((a(1)-a(2)) to a(1)) zip ((a(0)+1) to (a(0)+a(2)+1)) toList).map(x => x._1*1.0/x._2) reduceLeft(_*_)))\n }\n}\n"}], "src_uid": "5a2c9caec9c20a3caed1982ee8ed8f9c"} {"nl": {"description": "You are given a tree (an undirected connected graph without cycles) and an integer $$$s$$$.Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $$$s$$$. At the same time, he wants to make the diameter of the tree as small as possible.Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.Find the minimum possible diameter that Vanya can get.", "input_spec": "The first line contains two integer numbers $$$n$$$ and $$$s$$$ ($$$2 \\leq n \\leq 10^5$$$, $$$1 \\leq s \\leq 10^9$$$) \u2014 the number of vertices in the tree and the sum of edge weights. Each of the following $$$n\u22121$$$ lines contains two space-separated integer numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq n$$$, $$$a_i \\neq b_i$$$) \u2014 the indexes of vertices connected by an edge. The edges are undirected. It is guaranteed that the given edges form a tree.", "output_spec": "Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $$$s$$$. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\\frac {|a-b|} {max(1, b)} \\leq 10^{-6}$$$.", "sample_inputs": ["4 3\n1 2\n1 3\n1 4", "6 1\n2 1\n2 3\n2 5\n5 4\n5 6", "5 5\n1 2\n2 3\n3 4\n3 5"], "sample_outputs": ["2.000000000000000000", "0.500000000000000000", "3.333333333333333333"], "notes": "NoteIn the first example it is necessary to put weights like this: It is easy to see that the diameter of this tree is $$$2$$$. It can be proved that it is the minimum possible diameter.In the second example it is necessary to put weights like this: "}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "7bdd8f0cf42855bebda4ccc56d8fe788"} {"nl": {"description": "A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.", "input_spec": "The first input line contains the only integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) which represents the number of soldiers in the line. The second line contains integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1,\u2009a2,\u2009...,\u2009an are not necessarily different.", "output_spec": "Print the only integer \u2014 the minimum number of seconds the colonel will need to form a line-up the general will like.", "sample_inputs": ["4\n33 44 11 22", "7\n10 10 58 31 63 40 76"], "sample_outputs": ["2", "10"], "notes": "NoteIn the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).In the second sample the colonel may swap the soldiers in the following sequence: (10, 10, 58, 31, 63, 40, 76) (10, 58, 10, 31, 63, 40, 76) (10, 58, 10, 31, 63, 76, 40) (10, 58, 10, 31, 76, 63, 40) (10, 58, 31, 10, 76, 63, 40) (10, 58, 31, 76, 10, 63, 40) (10, 58, 31, 76, 63, 10, 40) (10, 58, 76, 31, 63, 10, 40) (10, 76, 58, 31, 63, 10, 40) (76, 10, 58, 31, 63, 10, 40) (76, 10, 58, 31, 63, 40, 10) "}, "positive_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\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": "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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called \"massive refactoring\", which can replace names of many variable in just one run. To use it, Alice needs to select two strings $$$s$$$ and $$$t$$$ and after that for each variable the following algorithm is performed: if the variable's name contains $$$s$$$ as a substring, then the first (and only first) occurrence of $$$s$$$ is replaced with $$$t$$$. If the name doesn't contain $$$s$$$, then this variable's name stays the same.The list of variables is known and for each variable both the initial name and the name Alice wants this variable change to are known. Moreover, for each variable the lengths of the initial name and the target name are equal (otherwise the alignment of the code could become broken). You need to perform renaming of all variables in exactly one run of the massive refactoring command or determine that it is impossible.", "input_spec": "The first line contains the only integer $$$n$$$ ($$$1 \\le n \\le 3000$$$)\u00a0\u2014 the number of variables in Alice's program. The following $$$n$$$ lines contain the initial names of variables $$$w_1, w_2, \\ldots, w_n$$$, one per line. After that, $$$n$$$ more lines go, the $$$i$$$-th of them contains the target name $$$w'_i$$$ for the $$$i$$$-th variable. It is guaranteed that $$$1 \\le |w_i| = |w'_i| \\le 3000$$$. It is guaranteed that there is at least one variable having its target name different from the initial name. Both initial and target names consist of lowercase English letters only. For each variable the length of its initial name is equal to the length of its target name.", "output_spec": "If it is impossible to rename all variables with one call of \"massive refactoring\", print \"NO\" (quotes for clarity). Otherwise, on the first line print \"YES\" (quotes for clarity) and on the following lines print $$$s$$$ and $$$t$$$ ($$$1 \\le |s|, |t| \\le 5000$$$), which should be used for replacement. Strings $$$s$$$ and $$$t$$$ should consist only of lowercase letters of English alphabet. If there are multiple ways to perform a \"massive refactoring\", you can use any of them.", "sample_inputs": ["1\ntopforces\ncodecoder", "3\nbab\ncac\ncdc\nbdb\ncdc\ncdc", "2\nyou\nshal\nnot\npass"], "sample_outputs": ["YES\ntopforces\ncodecoder", "YES\na\nd", "NO"], "notes": null}, "positive_code": [{"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\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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 // \u5de6\u53f3\u306e\u540c\u3058\u3082\u306e\u304c\u7d9a\u304f\u56de\u6570\n diffs.foreach { replace =>\n val l = replace.l\n val r = replace.r\n val i = replace.i\n // cntL, cntR\u306f\u3067\u304d\u308b\u3060\u3051\u5e83\u304f\u3068\u308b\u307b\u3046\u304cSame\u3068\u30d0\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u306b\u304f\u3044\u306e\u3067\u771f\u306b\u6709\u5229\u306b\u306a\u308b\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.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 // \u5de6\u53f3\u306e\u540c\u3058\u3082\u306e\u304c\u7d9a\u304f\u56de\u6570\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\u306f\u3067\u304d\u308b\u3060\u3051\u5e83\u304f\u3068\u308b\u307b\u3046\u304cSame\u3068\u30d0\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u306b\u304f\u3044\u306e\u3067\u6709\u5229\u306b\u306a\u308b\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 // \u5de6\u53f3\u306e\u540c\u3058\u3082\u306e\u304c\u7d9a\u304f\u56de\u6570\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\u306f\u3067\u304d\u308b\u3060\u3051\u5e83\u304f\u3068\u308b\u307b\u3046\u304cSame\u3068\u30d0\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u306b\u304f\u3044\u306e\u3067\u6709\u5229\u306b\u306a\u308b\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"} {"nl": {"description": "You are given a huge decimal number consisting of $$$n$$$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers $$$0 \\le y < x < n$$$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.", "input_spec": "The first line of the input contains three integers $$$n, x, y$$$ ($$$0 \\le y < x < n \\le 2 \\cdot 10^5$$$) \u2014 the length of the number and the integers $$$x$$$ and $$$y$$$, respectively. The second line of the input contains one decimal number consisting of $$$n$$$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.", "output_spec": "Print one integer \u2014 the minimum number of operations you should perform to obtain the number having remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.", "sample_inputs": ["11 5 2\n11010100101", "11 5 1\n11010100101"], "sample_outputs": ["1", "3"], "notes": "NoteIn the first example the number will be $$$11010100100$$$ after performing one operation. It has remainder $$$100$$$ modulo $$$100000$$$.In the second example the number will be $$$11010100010$$$ after performing three operations. It has remainder $$$10$$$ modulo $$$100000$$$."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "075988685fa3f9b20bd215037c504a4f"} {"nl": {"description": "One day Ms Swan bought an orange in a shop. The orange consisted of n\u00b7k segments, numbered with integers from 1 to n\u00b7k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009k) child wrote the number ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u00b7k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions: each child gets exactly n orange segments; the i-th child gets the segment with number ai for sure; no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u200930). The second line contains k space-separated integers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u00b7k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.", "output_spec": "Print exactly n\u00b7k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.", "sample_inputs": ["2 2\n4 1", "3 1\n2"], "sample_outputs": ["2 4 \n1 3", "3 2 1"], "notes": null}, "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": "\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"}, {"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"} {"nl": {"description": "Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?", "input_spec": "The first line of input contains an integer t (0\u2009<\u2009t\u2009<\u2009180) \u2014 the number of tests. Each of the following t lines contains a single integer a (0\u2009<\u2009a\u2009<\u2009180) \u2014 the angle the robot can make corners at measured in degrees.", "output_spec": "For each test, output on a single line \"YES\" (without quotes), if the robot can build a fence Emuskald wants, and \"NO\" (without quotes), if it is impossible.", "sample_inputs": ["3\n30\n60\n90"], "sample_outputs": ["NO\nYES\nYES"], "notes": "NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case \u2014 a square."}, "positive_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 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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i.\u00a0e. change $$$x \\to (-x)$$$). What is the maximum number of different values in the array you can achieve?", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$): the number of test cases. The next lines contain the description of the $$$t$$$ test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-100 \\leq a_i \\leq 100$$$).", "output_spec": "For each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.", "sample_inputs": ["3\n4\n1 1 2 2\n3\n1 2 3\n2\n0 0"], "sample_outputs": ["4\n3\n1"], "notes": "NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array $$$[-1, 1, 2, -2]$$$ with four different values.In the second example all three numbers are already different.In the third example negation does not change anything."}, "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 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}"}, {"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"} {"nl": {"description": "While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1,\u2009a2,\u2009...,\u2009am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1,\u2009f2,\u2009...,\u2009fn of length n and for each number ai got number bi\u2009=\u2009fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the lengths of sequences fi and bi respectively. The second line contains n integers, determining sequence f1,\u2009f2,\u2009...,\u2009fn (1\u2009\u2264\u2009fi\u2009\u2264\u2009n). The last line contains m integers, determining sequence b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009n).", "output_spec": "Print \"Possible\" if there is exactly one sequence ai, such that bi\u2009=\u2009fai for all i from 1 to m. Then print m integers a1,\u2009a2,\u2009...,\u2009am. If there are multiple suitable sequences ai, print \"Ambiguity\". If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print \"Impossible\".", "sample_inputs": ["3 3\n3 2 1\n1 2 3", "3 3\n1 1 1\n1 1 1", "3 3\n1 2 1\n3 3 3"], "sample_outputs": ["Possible\n3 2 1", "Ambiguity", "Impossible"], "notes": "NoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi\u2009\u2260\u20093 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake."}, "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\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}"}, {"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 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"}, {"source_code": "object _984B 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 map: Vector[String] = io.read(n)\n\n def bombCount(i: Int, j: Int) = {\n var c = 0\n for {\n dx <- -1 to 1\n row <- map.lift(i + dx)\n dy <- -1 to 1\n if !(dx == 0 && dy == 0)\n col <- row.lift(j + dy)\n if col == '*'\n } c += 1\n c\n }\n\n var ok = true\n for {\n i <- map.indices\n j <- map(i).indices\n if map(i)(j) != '*'\n c = if (map(i)(j).isDigit) map(i)(j) - '0' else 0\n } ok &= (c == bombCount(i, j))\n\n io.write(if (ok) \"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": "0d586ba7d304902caaeb7cd9e6917cd6"} {"nl": {"description": "There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his \"magic number\" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109\u2009+\u20097). Two ways are different, if the set of deleted positions in s differs.Look at the input part of the statement, s is given in a special form.", "input_spec": "In the first line you're given a string a (1\u2009\u2264\u2009|a|\u2009\u2264\u2009105), containing digits only. In the second line you're given an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009109). The plate s is formed by concatenating k copies of a together. That is n\u2009=\u2009|a|\u00b7k.", "output_spec": "Print a single integer \u2014 the required number of ways modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["1256\n1", "13990\n2", "555\n2"], "sample_outputs": ["4", "528", "63"], "notes": "NoteIn the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.In the third case, except deleting all digits, any choice will do. Therefore there are 26\u2009-\u20091\u2009=\u200963 possible ways to delete digits."}, "positive_code": [{"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 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}"}, {"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 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"} {"nl": {"description": "Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either \"M\" or from $$$0$$$ to $$$3$$$ \"X\" followed by \"S\" or \"L\". For example, sizes \"M\", \"XXS\", \"L\", \"XXXL\" are valid and \"XM\", \"Z\", \"XXXXL\" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ \u2014 the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ \u2014 the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.", "output_spec": "Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.", "sample_inputs": ["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"], "sample_outputs": ["2", "1", "0"], "notes": "NoteIn the first example Ksenia can replace \"M\" with \"S\" and \"S\" in one of the occurrences of \"XS\" with \"L\".In the second example Ksenia should replace \"L\" in \"XXXL\" with \"S\".In the third example lists are equal."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val n = StdIn.readInt()\n val map: Map[String, Int] = Map(\n \"XXXS\" -> 0,\n \"XXS\" -> 1,\n \"XS\" -> 2,\n \"S\" -> 3,\n \"M\" -> 4,\n \"L\" -> 5,\n \"XL\" -> 6,\n \"XXL\" -> 7,\n \"XXXL\" -> 8)\n\n val readArr = readStd(n, map, _: Array[Int], _: Int)\n val add = readArr(_: Array[Int], 1)\n val minus = readArr(_: Array[Int], -1)\n\n val arr = (add andThen minus) (Array.fill(9)(0))\n\n println(arr.filter({x: Int => x < 0}).map({x: Int => -x}).sum)\n }\n\n def readStd(n: Int, map: Map[String, Int], arr: Array[Int], add: Int): Array[Int] = {\n if (n != 0) {\n arr(map(StdIn.readLine)) += add\n readStd(n - 1, map, arr, add)\n } else {\n arr\n }\n }\n}\n"}], "negative_code": [], "src_uid": "c8321b60a6ad04093dee3eeb9ee27b6f"} {"nl": {"description": "Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.", "input_spec": "The first line contains two integers, n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n\u2009-\u20091 lines contains the edges of the tree in the format \"xi yi\" (without the quotes) (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree.", "output_spec": "A single integer \u2014 the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.", "sample_inputs": ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"], "sample_outputs": ["2", "2"], "notes": "NoteLet us remind you that a tree is a connected graph on n vertices and n\u2009-\u20091 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7."}, "positive_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 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"}, {"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": "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}"}], "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"} {"nl": {"description": "Eugeny has array a\u2009=\u2009a1,\u2009a2,\u2009...,\u2009an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: Query number i is given as a pair of integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali\u2009+\u2009ali\u2009+\u20091\u2009+\u2009...\u2009+\u2009ari\u2009=\u20090, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.", "input_spec": "The first line contains integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (ai\u2009=\u2009-1,\u20091). Next m lines contain Eugene's queries. The i-th line contains integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print m integers \u2014 the responses to Eugene's queries in the order they occur in the input.", "sample_inputs": ["2 3\n1 -1\n1 1\n1 2\n2 2", "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5"], "sample_outputs": ["0\n1\n0", "0\n1\n0\n1\n0"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.", "input_spec": "The first input line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0\u2009\u2264\u2009x\u2009\u2264\u20092000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0\u2009\u2264\u2009x\u2009\u2264\u20092000).", "output_spec": "Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.", "sample_inputs": ["7\nwin 10\nwin 5\nwin 3\nsell 5\nsell 3\nwin 10\nsell 10", "3\nwin 5\nsell 6\nsell 4"], "sample_outputs": ["1056", "0"], "notes": null}, "positive_code": [{"source_code": "import java.math.BigInteger\nimport java.util\nimport 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 noUsedFromTo(from: Int, to: Int, used: Array[Boolean]): Boolean = {\n var flag = true\n for (i <- from to to) {\n flag &= !used(i)\n }\n return flag\n }\n\n def solve: Int = {\n val n = nextInt\n val events = new Array[(Boolean, Int, Int)](n)\n val needToSell = new util.TreeSet[Int]()\n val used = new Array[Boolean](n)\n for (i <- 0 until n) {\n if (next == \"win\") {\n events(i) = (true, nextInt, i)\n } else {\n events(i) = (false, nextInt, i)\n needToSell.add(events(i)._2)\n }\n }\n var ans: BigInteger = BigInteger.ZERO\n val it = needToSell.descendingIterator\n while (it.hasNext) {\n val price = it.next\n val pos = events.find(x => !x._1 && x._2 == price).get._3\n var i = pos - 1\n while (i >= 0) {\n if (events(i)._1 && events(i)._2 == price && noUsedFromTo(i, pos, used)) {\n ans = ans.add(BigInteger.valueOf(2).pow(price))\n for (j <- i to pos) {\n used(j) = true\n }\n i = -1\n }\n i -= 1\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"}], "negative_code": [{"source_code": "import java.math.BigInteger\nimport java.util\nimport 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 events = new Array[(Boolean, Int, Int)](n)\n val needToSell = new util.TreeSet[Int]()\n val used = new Array[Boolean](n)\n for (i <- 0 until n) {\n if (next == \"win\") {\n events(i) = (true, nextInt, i)\n } else {\n events(i) = (false, nextInt, i)\n needToSell.add(events(i)._2)\n }\n }\n var ans: BigInteger = BigInteger.ZERO\n val it = needToSell.descendingIterator\n while (it.hasNext) {\n val price = it.next\n val pos = events.find(x => !x._1 && x._2 == price).get._3\n var i = pos - 1\n while (i >= 0) {\n if (events(i)._1 && events(i)._2 == price && !used(i)) {\n ans = ans.add(BigInteger.valueOf(2).pow(price))\n for (j <- i to pos) {\n used(j) = true\n }\n i = -1\n }\n i -= 1\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"}], "src_uid": "217a3a48b927213f4d5e0a19048e2a32"} {"nl": {"description": "ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b\u2009-\u2009a\u2009\u2264\u2009c, just the new word is appended to other words on the screen. If b\u2009-\u2009a\u2009>\u2009c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c\u2009=\u20095 and you typed words at seconds 1,\u20093,\u20098,\u200914,\u200919,\u200920 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.", "input_spec": "The first line contains two integers n and c (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009c\u2009\u2264\u2009109)\u00a0\u2014 the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009t1\u2009<\u2009t2\u2009<\u2009...\u2009<\u2009tn\u2009\u2264\u2009109), where ti denotes the second when ZS the Coder typed the i-th word.", "output_spec": "Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.", "sample_inputs": ["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"], "sample_outputs": ["3", "2"], "notes": "NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3\u2009-\u20091\u2009>\u20091. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10\u2009-\u20099\u2009\u2264\u20091."}, "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": "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}"}, {"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"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ both consisting of $$$n$$$ positive (greater than zero) integers. You are also given an integer $$$k$$$.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) and swap $$$a_i$$$ and $$$b_j$$$ (i.e. $$$a_i$$$ becomes $$$b_j$$$ and vice versa). Note that $$$i$$$ and $$$j$$$ can be equal or different (in particular, swap $$$a_2$$$ with $$$b_2$$$ or swap $$$a_3$$$ and $$$b_9$$$ both are acceptable moves).Your task is to find the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ such moves (swaps).You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 30; 0 \\le k \\le n$$$) \u2014 the number of elements in $$$a$$$ and $$$b$$$ and the maximum number of moves you can do. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 30$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 30$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.", "output_spec": "For each test case, print the answer \u2014 the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ swaps.", "sample_inputs": ["5\n2 1\n1 2\n3 4\n5 5\n5 5 6 6 5\n1 2 5 4 3\n5 3\n1 2 3 4 5\n10 9 10 10 9\n4 0\n2 2 4 3\n2 4 2 3\n4 4\n1 2 2 1\n4 4 5 4"], "sample_outputs": ["6\n27\n39\n11\n17"], "notes": "NoteIn the first test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_2 = 4$$$, so $$$a=[4, 2]$$$ and $$$b=[3, 1]$$$.In the second test case of the example, you don't need to swap anything.In the third test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_1 = 10$$$, $$$a_3 = 3$$$ and $$$b_3 = 10$$$ and $$$a_2 = 2$$$ and $$$b_4 = 10$$$, so $$$a=[10, 10, 10, 4, 5]$$$ and $$$b=[1, 9, 3, 2, 9]$$$.In the fourth test case of the example, you cannot swap anything.In the fifth test case of the example, you can swap arrays $$$a$$$ and $$$b$$$, so $$$a=[4, 4, 5, 4]$$$ and $$$b=[1, 2, 2, 1]$$$."}, "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": "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"}, {"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"} {"nl": {"description": "You are given two very long integers a,\u2009b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().", "input_spec": "The first line contains a non-negative integer a. The second line contains a non-negative integer b. The numbers a,\u2009b may contain leading zeroes. Each of them contains no more than 106 digits.", "output_spec": "Print the symbol \"<\" if a\u2009<\u2009b and the symbol \">\" if a\u2009>\u2009b. If the numbers are equal print the symbol \"=\".", "sample_inputs": ["9\n10", "11\n10", "00012345\n12345", "0123\n9", "0123\n111"], "sample_outputs": ["<", ">", "=", ">", ">"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.", "input_spec": "The first line of the input contains the number of countries n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). The second line contains n non-negative integers ai without leading zeroes\u00a0\u2014 the number of tanks of the i-th country. It is guaranteed that the second line contains at least n\u2009-\u20091 beautiful numbers and the total length of all these number's representations doesn't exceed 100\u2009000.", "output_spec": "Print a single number without leading zeroes\u00a0\u2014 the product of the number of tanks presented by each country.", "sample_inputs": ["3\n5 10 1", "4\n1 1 10 11", "5\n0 3 1 100 1"], "sample_outputs": ["50", "110", "0"], "notes": "NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful."}, "positive_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 //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"}, {"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": "// 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": "\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"} {"nl": {"description": "Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, \"macro_name\" is replaced with \"macro_value\" each time it is met in the program (only the whole tokens can be replaced; i.e. \"macro_name\" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A \"macro_value\" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros \u2014 the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression \"2 * sum\" is calculated. After macro substitution is performed we get \"2 * x + y\", instead of intuitively expected \"2 * (x + y)\".Let's call the situation \"suspicious\", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a \"safe\" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise \u2014 suspicious.Note that we consider the \"/\" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression \"a*(b/c)\" we can omit brackets to get the expression \"a*b/c\".", "input_spec": "The first line contains the only number n (0\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where name \u2014 the macro name, expression \u2014 the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109. All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word \"define\" or the names of constructions and variables. In particular, there can be any number of spaces before and after the \"#\" symbol. The length of any line from the input file does not exceed 100 characters.", "output_spec": "Output \"OK\", if the expression is correct according to the above given criterion, otherwise output \"Suspicious\".", "sample_inputs": ["1\n#define sum x + y\n1 * sum", "1\n#define sum (x + y)\nsum - sum", "4\n#define sum x + y\n#define mul a * b\n#define div a / b\n#define expr sum + mul * div * mul\nexpr", "3\n#define SumSafe (a+b)\n#define DivUnsafe a/b\n#define DenominatorUnsafe a*b\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)"], "sample_outputs": ["Suspicious", "OK", "OK", "Suspicious"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',\u2009E') of a graph G(V,\u2009E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. ", "input_spec": "The first line contains two space-separated integers n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi\u00a0(1\u2009\u2264\u2009xi\u2009\u2264\u2009106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,\u2009bi,\u2009ci\u00a0(1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009ci\u2009\u2264\u2009103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.", "output_spec": "Output a real number denoting the answer, with an absolute or relative error of at most 10\u2009-\u20099.", "sample_inputs": ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"], "sample_outputs": ["0.000000000000000", "3.000000000000000", "2.965517241379311"], "notes": "NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal."}, "positive_code": [{"source_code": "import java.util.Scanner\n\n/**\n * Created by hama_du on 2014/09/01.\n */\nobject ProblemA extends App {\n val in = new Scanner(System.in)\n val n = in.nextInt()\n val m = in.nextInt()\n val v = (0 until n).map(_ => in.nextInt).toArray\n val edges = (0 until m).map(_ => (in.nextInt()-1, in.nextInt()-1, in.nextInt())).toArray\n\n println(solve(v, edges))\n\n def solve(v: Array[Int], edges: Array[(Int,Int,Int)]): Double = {\n if (edges.length == 0) {\n 0\n } else {\n edges.map(edge => (v(edge._1) + v(edge._2) + 0.0d) / edge._3 ).max\n }\n }\n}\n"}], "negative_code": [], "src_uid": "ba4304e79d85d13c12233bcbcce6d0a6"} {"nl": {"description": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.", "input_spec": "The first line contains two space-separated integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 0\u2009\u2264\u2009x\u2009\u2264\u2009109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1\u2009\u2264\u2009di\u2009\u2264\u2009109). Record \"+ di\" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record \"- di\" means that a child who wants to take di packs stands in i-th place.", "output_spec": "Print two space-separated integers\u00a0\u2014 number of ice cream packs left after all operations, and number of kids that left the house in distress.", "sample_inputs": ["5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20", "5 17\n- 16\n- 2\n- 98\n+ 100\n- 98"], "sample_outputs": ["22 1", "3 2"], "notes": "NoteConsider the first sample. Initially Kay and Gerda have 7 packs of ice cream. Carrier brings 5 more, so now they have 12 packs. A kid asks for 10 packs and receives them. There are only 2 packs remaining. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. Carrier bring 40 packs, now Kay and Gerda have 42 packs. Kid asks for 20 packs and receives them. There are 22 packs remaining. "}, "positive_code": [{"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": "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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given $$$n$$$ points on the plane. The polygon formed from all the $$$n$$$ points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $$$1$$$ to $$$n$$$, in clockwise order.We define the distance between two points $$$p_1 = (x_1, y_1)$$$ and $$$p_2 = (x_2, y_2)$$$ as their Manhattan distance: $$$$$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$$$$Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $$$p_1, p_2, \\ldots, p_k$$$ $$$(k \\geq 3)$$$, then the perimeter of the polygon is $$$d(p_1, p_2) + d(p_2, p_3) + \\ldots + d(p_k, p_1)$$$.For some parameter $$$k$$$, let's consider all the polygons that can be formed from the given set of points, having any $$$k$$$ vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $$$f(k)$$$ to be the maximal perimeter.Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: In the middle polygon, the order of points ($$$p_1, p_3, p_2, p_4$$$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($$$p_1, p_2, p_3, p_4$$$), which is the left polygon.Your task is to compute $$$f(3), f(4), \\ldots, f(n)$$$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $$$3$$$ to $$$n$$$).", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 3\\cdot 10^5$$$)\u00a0\u2014 the number of points. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^8 \\leq x_i, y_i \\leq 10^8$$$)\u00a0\u2014 the coordinates of point $$$p_i$$$. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.", "output_spec": "For each $$$i$$$ ($$$3\\leq i\\leq n$$$), output $$$f(i)$$$.", "sample_inputs": ["4\n2 4\n4 3\n3 0\n1 3", "3\n0 0\n0 2\n2 0"], "sample_outputs": ["12 14", "8"], "notes": "NoteIn the first example, for $$$f(3)$$$, we consider four possible polygons: ($$$p_1, p_2, p_3$$$), with perimeter $$$12$$$. ($$$p_1, p_2, p_4$$$), with perimeter $$$8$$$. ($$$p_1, p_3, p_4$$$), with perimeter $$$12$$$. ($$$p_2, p_3, p_4$$$), with perimeter $$$12$$$. For $$$f(4)$$$, there is only one option, taking all the given points. Its perimeter $$$14$$$.In the second example, there is only one possible polygon. Its perimeter is $$$8$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \\times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.", "input_spec": "The first line contains three positive integers $$$n,m,k$$$ ($$$1 \\leq n, m, k \\leq 2\\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.", "output_spec": "A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.", "sample_inputs": ["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."], "sample_outputs": ["3", "1", "0"], "notes": "NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$ "}, "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}"}, {"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}"}], "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"} {"nl": {"description": "There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,\u2009j) (i\u2009<\u2009j) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950)\u00a0\u2014 the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.", "output_spec": "If the given grid can be achieved by any valid sequence of operations, output \"Yes\"; otherwise output \"No\" (both without quotes). You can print each character in any case (upper or lower).", "sample_inputs": ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"], "sample_outputs": ["Yes", "No", "No"], "notes": "NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport 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 grid = Array.fill(n){ readLine.toCharArray.map(_ == '#' )}\n val counts = Array.fill(n, m){ 0 }\n\n var ok = true\n var usedRow, usedCol = new mutable.BitSet\n\n for {\n r0 <- 0 until n\n c0 <- 0 until m\n if grid(r0)(c0) && counts(r0)(c0) == 0\n } {\n val rows, cols = ArrayBuffer.empty[Int]\n for (c <- 0 until m) {\n if (grid(r0)(c)) {\n cols += c\n if (usedCol(c)) ok = false\n usedCol += c\n }\n }\n for (r <- 0 until n) {\n if (grid(r)(c0)) {\n rows += r\n if (usedRow(r)) ok = false\n usedRow += r\n }\n }\n for {\n r <- rows\n c <- cols\n } {\n if (!grid(r)(c)) ok = false\n counts(r)(c) += 1\n //grid(r)(c) = false\n }\n }\n\n //counts.foreach(c => println(c.mkString))\n\n if (counts.exists(_.exists(_ > 1))) ok = false\n\n println(if (ok) \"Yes\" else \"No\")\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport 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 grid = Array.fill(n){ readLine.toCharArray.map(_ == '#' )}\n val counts = Array.fill(n, m){ 0 }\n\n var ok = true\n var usedRow, usedCol = new mutable.BitSet\n\n for {\n r0 <- 0 until n\n c0 <- 0 until m\n if grid(r0)(c0) && counts(r0)(c0) == 0\n } {\n val rows, cols = ArrayBuffer.empty[Int]\n for (c <- 0 until m) {\n if (grid(r0)(c)) {\n cols += c\n //if (usedCol(c)) ok = false\n usedCol += c\n }\n }\n for (r <- 0 until n) {\n if (grid(r)(c0)) {\n rows += r\n //if (usedRow(r)) ok = false\n usedRow += r\n }\n }\n for {\n r <- rows\n c <- cols\n } {\n if (!grid(r)(c)) ok = false\n counts(r)(c) += 1\n //grid(r)(c) = false\n }\n }\n\n //counts.foreach(c => println(c.mkString))\n\n if (counts.exists(_.exists(_ > 1))) ok = false\n\n println(if (ok) \"Yes\" else \"No\")\n}\n"}, {"source_code": "import scala.collection.mutable\nimport 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 grid = Array.fill(n){ readLine.toCharArray.map(_ == '#' )}\n val counts = Array.fill(n, m){ 0 }\n\n var ok = true\n var usedRow, usedCol = new mutable.BitSet\n\n for {\n r0 <- 0 until n\n c0 <- 0 until m\n if grid(r0)(c0) && counts(r0)(c0) == 0\n } {\n val rows = ArrayBuffer(r0)\n val cols = ArrayBuffer(c0)\n for (c <- c0 + 1 until m) {\n if (grid(r0)(c)) {\n cols += c\n //if (usedCol(c)) ok = false\n usedCol += c\n }\n }\n for (r <- r0 + 1 until n) {\n if (grid(r)(c0)) {\n rows += r\n //if (usedRow(r)) ok = false\n usedRow += r\n }\n }\n for {\n r <- rows\n c <- cols\n } {\n if (!grid(r)(c)) ok = false\n counts(r)(c) += 1\n //grid(r)(c) = false\n }\n }\n\n //counts.foreach(c => println(c.mkString))\n\n if (counts.exists(_.exists(_ > 1))) ok = false\n\n println(if (ok) \"Yes\" else \"No\")\n}\n"}], "src_uid": "ac718922461f3187d8b7587c360b05fc"} {"nl": {"description": "You're given an undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Nodes are numbered from $$$1$$$ to $$$n$$$.The graph is considered harmonious if and only if the following property holds: For every triple of integers $$$(l, m, r)$$$ such that $$$1 \\le l < m < r \\le n$$$, if there exists a path going from node $$$l$$$ to node $$$r$$$, then there exists a path going from node $$$l$$$ to node $$$m$$$. In other words, in a harmonious graph, if from a node $$$l$$$ we can reach a node $$$r$$$ through edges ($$$l < r$$$), then we should able to reach nodes $$$(l+1), (l+2), \\ldots, (r-1)$$$ too.What is the minimum number of edges we need to add to make the graph harmonious? ", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \\le n \\le 200\\ 000$$$ and $$$1 \\le m \\le 200\\ 000$$$). The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\neq v_i$$$), that mean that there's an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).", "output_spec": "Print the minimum number of edges we have to add to the graph to make it harmonious.", "sample_inputs": ["14 8\n1 2\n2 7\n3 4\n6 3\n5 7\n3 8\n6 8\n11 12", "200000 3\n7 9\n9 8\n4 5"], "sample_outputs": ["1", "0"], "notes": "NoteIn the first example, the given graph is not harmonious (for instance, $$$1 < 6 < 7$$$, node $$$1$$$ can reach node $$$7$$$ through the path $$$1 \\rightarrow 2 \\rightarrow 7$$$, but node $$$1$$$ can't reach node $$$6$$$). However adding the edge $$$(2, 4)$$$ is sufficient to make it harmonious.In the second example, the given graph is already harmonious."}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {}\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 val n, m = nextInt\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n\n for (_ <- 1 to m) {\n val _u, _v = nextInt\n val u = Math.min(_u, _v) - 1\n val v = Math.max(_u, _v) - 1\n adjBuilders(u) += v\n }\n val adjs = adjBuilders.map(_.result())\n val con = new UnionFind(n)\n var res = 0L\n\n var u = 0\n while (u < n) {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n con.union(u, v)\n i += 1\n }\n u += 1\n }\n\n val max = Array.tabulate(n)(identity)\n\n var i = 0\n while (i < n) {\n val f = con.find(i)\n if (i > max(f)) max(f) = i\n i += 1\n }\n\n var l = 0\n while (l < n) {\n val l0 = l\n var r = max(con.find(l0))\n while (l < r) {\n l += 1\n if (!con.same(l0, l)) {\n val max2 = max(con.find(l))\n if (max2 > r) r = max2\n con.union(l0, l)\n res += 1\n }\n }\n l += 1\n }\n\n out.println(res)\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": "04fd1a55027cce56a491b984ce3a1d6d"} {"nl": {"description": "There are $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) \u2014 the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\\cdot10^5$$$.", "output_spec": "For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).", "sample_inputs": ["4\n6\n40 6 40 3 20 1\n1\n1024\n4\n2 4 8 16\n3\n3 1 7"], "sample_outputs": ["4\n10\n4\n0"], "notes": "NoteIn the first test case of the example, the optimal sequence of moves can be as follows: before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$; choose $$$c=6$$$; now $$$a=[40, 3, 40, 3, 20, 1]$$$; choose $$$c=40$$$; now $$$a=[20, 3, 20, 3, 20, 1]$$$; choose $$$c=20$$$; now $$$a=[10, 3, 10, 3, 10, 1]$$$; choose $$$c=10$$$; now $$$a=[5, 3, 5, 3, 5, 1]$$$ \u2014 all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd."}, "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 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 }"}, {"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"} {"nl": {"description": "Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?", "input_spec": "The first line contains string a, the second line contains string b, and the third line contains string c (1\u2009\u2264\u2009|a|,\u2009|b|,\u2009|c|\u2009\u2264\u2009105, where |s| denotes the length of string s). All three strings consist only of lowercase English letters. It is possible that b and c coincide.", "output_spec": "Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.", "sample_inputs": ["aaa\na\nb", "pozdravstaklenidodiri\nniste\ndobri", "abbbaaccca\nab\naca"], "sample_outputs": ["aaa", "nisteaadddiiklooprrvz", "ababacabcc"], "notes": "NoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1\u2009\u2013\u20092 (ab), 3\u2009\u2013\u20094 (ab), 5\u2009\u2013\u20097 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc."}, "positive_code": [{"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"}, {"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 = readLine()\n val b = readLine()\n val c = readLine()\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"}, {"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 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 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 _1234A 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 input = io.read[Seq[Seq[Int]]]\n val ans = input.map(prices => (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"}, {"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"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \\ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array.", "output_spec": "Print \"YES\" if it is possible to make all elements zero, otherwise print \"NO\".", "sample_inputs": ["4\n1 1 2 2", "6\n1 2 3 4 5 6"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations: Decrease $$$a_1$$$ and $$$a_2$$$, Decrease $$$a_3$$$ and $$$a_4$$$, Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero."}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1201 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toLong).sorted\n\n if (A.sum % 2 == 1 || A.init.sum < A.last) println(\"NO\")\n else println(\"YES\")\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B_1201 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt).sorted\n\n if (A.sum % 2 == 1 || A.init.sum < A.last) println(\"NO\")\n else println(\"YES\")\n\n}\n"}], "src_uid": "52f4f2a48063c9d0e412a5f78c873e6f"} {"nl": {"description": "Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s\u2009=\u2009s1s2... sn, then the following inequality holds, si\u2009\u2260\u2009si\u2009+\u20091(1\u2009\u2264\u2009i\u2009<\u2009n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x\u2009=\u2009x1x2... xp is lexicographically less than string y\u2009=\u2009y1y2... yq, if either p\u2009<\u2009q and x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xp\u2009=\u2009yp, or there is such number r (r\u2009<\u2009p,\u2009r\u2009<\u2009q), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xr\u2009=\u2009yr and xr\u2009+\u20091\u2009<\u2009yr\u2009+\u20091. The characters of the strings are compared by their ASCII codes.", "input_spec": "A single line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009106,\u20091\u2009\u2264\u2009k\u2009\u2264\u200926) \u2014 the string's length and the number of distinct letters.", "output_spec": "In a single line print the required string. If there isn't such string, print \"-1\" (without the quotes).", "sample_inputs": ["7 4", "4 7"], "sample_outputs": ["ababacd", "-1"], "notes": null}, "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": "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 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}"}, {"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"}, {"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 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}"}], "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"} {"nl": {"description": "Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$)\u2014 the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\\cdot10^5$$$.", "output_spec": "For each test case, print a single value \u2014 the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["4\n3\n3 1 2\n3\n-7 -6 -6\n3\n2 2 2\n4\n17 3 5 -3"], "sample_outputs": ["4.500000000\n-12.500000000\n4.000000000\n18.666666667"], "notes": "NoteIn the first test case, the array is $$$[3, 1, 2]$$$. These are all the possible ways to split this array: $$$a = [3]$$$, $$$b = [1,2]$$$, so the value of $$$f(a) + f(b) = 3 + 1.5 = 4.5$$$. $$$a = [3,1]$$$, $$$b = [2]$$$, so the value of $$$f(a) + f(b) = 2 + 2 = 4$$$. $$$a = [3,2]$$$, $$$b = [1]$$$, so the value of $$$f(a) + f(b) = 2.5 + 1 = 3.5$$$. Therefore, the maximum possible value $$$4.5$$$.In the second test case, the array is $$$[-7, -6, -6]$$$. These are all the possible ways to split this array: $$$a = [-7]$$$, $$$b = [-6,-6]$$$, so the value of $$$f(a) + f(b) = (-7) + (-6) = -13$$$. $$$a = [-7,-6]$$$, $$$b = [-6]$$$, so the value of $$$f(a) + f(b) = (-6.5) + (-6) = -12.5$$$. Therefore, the maximum possible value $$$-12.5$$$."}, "positive_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(_.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"}, {"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"} {"nl": {"description": "Suppose you are living with two cats: A and B. There are $$$n$$$ napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically: Cat A changes its napping place in order: $$$n, n - 1, n - 2, \\dots, 3, 2, 1, n, n - 1, \\dots$$$ In other words, at the first hour it's on the spot $$$n$$$ and then goes in decreasing order cyclically; Cat B changes its napping place in order: $$$1, 2, 3, \\dots, n - 1, n, 1, 2, \\dots$$$ In other words, at the first hour it's on the spot $$$1$$$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $$$x$$$ then the A takes this place and B moves to the next place in its order (if $$$x < n$$$ then to $$$x + 1$$$, but if $$$x = n$$$ then to $$$1$$$). Cat B follows his order, so it won't return to the skipped spot $$$x$$$ after A frees it, but will move to the spot $$$x + 2$$$ and so on.Calculate, where cat B will be at hour $$$k$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^9$$$; $$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the number of spots and hour $$$k$$$.", "output_spec": "For each test case, print one integer\u00a0\u2014 the index of the spot where cat B will sleep at hour $$$k$$$.", "sample_inputs": ["7\n2 1\n2 2\n3 1\n3 2\n3 3\n5 5\n69 1337"], "sample_outputs": ["1\n2\n1\n3\n2\n2\n65"], "notes": "NoteIn the first and second test cases $$$n = 2$$$, so: at the $$$1$$$-st hour, A is on spot $$$2$$$ and B is on $$$1$$$; at the $$$2$$$-nd hour, A moves to spot $$$1$$$ and B\u00a0\u2014 to $$$2$$$. If $$$n = 3$$$ then: at the $$$1$$$-st hour, A is on spot $$$3$$$ and B is on $$$1$$$; at the $$$2$$$-nd hour, A moves to spot $$$2$$$; B'd like to move from $$$1$$$ to $$$2$$$, but this spot is occupied, so it moves to $$$3$$$; at the $$$3$$$-rd hour, A moves to spot $$$1$$$; B also would like to move from $$$3$$$ to $$$1$$$, but this spot is occupied, so it moves to $$$2$$$. In the sixth test case: A's spots at each hour are $$$[5, 4, 3, 2, 1]$$$; B's spots at each hour are $$$[1, 2, 4, 5, 2]$$$. "}, "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": "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"}, {"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": "//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"}], "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"} {"nl": {"description": "You are given a string $$$s[1 \\dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \\ge 0$$$.The string $$$s[1 \\dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied: The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\\dots=s_{\\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\\frac{n}{2} + 1}s_{\\frac{n}{2} + 2} \\dots s_n$$$) is a $$$(c+1)$$$-good string; The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\\frac{n}{2} + 1}=s_{\\frac{n}{2} + 2}=\\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \\dots s_{\\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: \"aabc\" is 'a'-good, \"ffgheeee\" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$\"cdbbaaaa\". It is an 'a'-good string, because: the second half of the string (\"aaaa\") consists of only the character 'a'; the first half of the string (\"cdbb\") is 'b'-good string, because: the second half of the string (\"bb\") consists of only the character 'b'; the first half of the string (\"cd\") is 'c'-good string, because: the first half of the string (\"c\") consists of only the character 'c'; the second half of the string (\"d\") is 'd'-good string. ", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 131~072$$$) \u2014 the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \\ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.", "sample_inputs": ["6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac"], "sample_outputs": ["0\n7\n4\n5\n1\n1"], "notes": null}, "positive_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n implicit class StringOps(str: String) {\n def countSlice(from: Int, until: Int, p: Char => Boolean): Int = {\n @scala.annotation.tailrec\n def go(i: Int, c: Int = 0): Int =\n if (i == until) c\n else go(i + 1, c + (if (p(str(i))) 1 else 0))\n\n go(from)\n }\n }\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n def count(c: Char, from: Int, size: Int): Int =\n size match {\n case 1 =>\n if (c == sn(from)) 0 else 1\n case _ =>\n val l = sn.countSlice(from, from + size / 2, _ != c) + count((c + 1).toChar, from + size / 2, size / 2)\n val r = sn.countSlice(from + size / 2, from + size, _ != c) + count((c + 1).toChar, from, size / 2)\n l min r\n }\n\n val ans = count('a', 0, n)\n\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val t = readInt()\n\n (0 until t).foreach { _ =>\n val n = readInt()\n val sn = readLine()\n\n def good(c: Char, from: Int, size: Int): Int =\n size match {\n case 1 => if (c == sn(from)) 0 else 1\n case _ =>\n val (l, r) = sn.slice(from, from + size).zipWithIndex.foldLeft(((0, 0), (0, 0))) {\n case ((l, r), (s, i)) if s == c => if (i < size / 2) ((l._1 + 1, l._2), r) else (l, (r._1 + 1, r._2))\n case ((l, r), (s, i)) if s == c + 1 => if (i < size / 2) ((l._1, l._2 + 1), r) else (l, (r._1, r._2 + 1))\n case ((l, r), _) => (l, r)\n }\n\n if (l._1 + r._2 >= r._1 + l._2)\n size / 2 - l._1 + good((c + 1).toChar, from + size / 2, size / 2)\n else\n size / 2 - r._1 + good((c + 1).toChar, from, size / 2)\n }\n\n val ans = good('a', 0, n)\n\n println(ans)\n }\n}\n"}], "src_uid": "324b7957b46dfe4948074c781159b7e7"} {"nl": {"description": "According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.", "output_spec": "Print a single number which is the number of people Vasya should check to guarantee the law enforcement.", "sample_inputs": ["5\n18\nVODKA\nCOKE\n19\n17"], "sample_outputs": ["2"], "notes": "NoteIn the sample test the second and fifth clients should be checked."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "The new generation external memory contains an array of integers $$$a[1 \\ldots n] = [a_1, a_2, \\ldots, a_n]$$$.This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions: You may select arbitrary indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) as the boundaries of the segment. Then you replace the segment $$$a[l \\ldots r]$$$ with it's cyclic shift to the left by an arbitrary offset $$$d$$$. The concept of a cyclic shift can be also explained by following relations: the sequence $$$[1, 4, 1, 3]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$1$$$ and the sequence $$$[4, 1, 3, 1]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$2$$$. For example, if $$$a = [1, \\color{blue}{3, 2, 8}, 5]$$$, then choosing $$$l = 2$$$, $$$r = 4$$$ and $$$d = 2$$$ yields a segment $$$a[2 \\ldots 4] = [3, 2, 8]$$$. This segment is then shifted by the offset $$$d = 2$$$ to the left, and you get a segment $$$[8, 3, 2]$$$ which then takes the place of of the original elements of the segment. In the end you get $$$a = [1, \\color{blue}{8, 3, 2}, 5]$$$.Sort the given array $$$a$$$ using no more than $$$n$$$ cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires $$$n$$$ or less cyclic shifts will be accepted.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain the descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$2 \\leq n \\leq 50$$$)\u00a0\u2014 the length of the array. The second line consists of space-separated elements of the array $$$a_i$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$). Elements of array $$$a$$$ may repeat and don't have to be unique.", "output_spec": "Print $$$t$$$ answers to all input test cases. The first line of the answer of each test case should contain an integer $$$k$$$ ($$$0 \\le k \\le n$$$)\u00a0\u2014 the number of actions to sort the array. The next $$$k$$$ lines should contain descriptions of the actions formatted as \"$$$l$$$\u00a0$$$r$$$\u00a0$$$d$$$\" (without quotes) where $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) are the boundaries of the segment being shifted, while $$$d$$$ ($$$1 \\le d \\le r - l$$$) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset $$$d$$$ to the to the left. Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed $$$n$$$ will be accepted. If the given array $$$a$$$ is already sorted, one of the possible answers is $$$k = 0$$$ and an empty sequence of cyclic shifts. If there are several possible answers, you may print any of them.", "sample_inputs": ["4\n2\n2 1\n3\n1 2 1\n4\n2 4 1 3\n5\n2 5 1 4 3"], "sample_outputs": ["1\n1 2 1\n1\n1 3 2\n3\n2 4 1\n2 3 1\n1 3 2\n4\n2 4 2\n1 5 3\n1 2 1\n1 3 1"], "notes": "NoteExplanation of the fourth data set in the example: The segment $$$a[2 \\ldots 4]$$$ is selected and is shifted to the left by $$$2$$$: $$$[2, \\color{blue}{5, 1, 4}, 3] \\longrightarrow [2, \\color{blue}{4, 5, 1}, 3]$$$ The segment $$$a[1 \\ldots 5]$$$ is then selected and is shifted to the left by $$$3$$$: $$$[\\color{blue}{2, 4, 5, 1, 3}] \\longrightarrow [\\color{blue}{1, 3, 2, 4, 5}]$$$ After that the segment $$$a[1 \\ldots 2]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\\color{blue}{1, 3}, 2, 4, 5] \\longrightarrow [\\color{blue}{3, 1}, 2, 4, 5]$$$ And in the end the segment $$$a[1 \\ldots 3]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\\color{blue}{3, 1, 2}, 4, 5] \\longrightarrow [\\color{blue}{1, 2, 3}, 4, 5]$$$ "}, "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"}, {"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"}], "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"} {"nl": {"description": "Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: a1\u2009=\u2009p, where p is some integer; ai\u2009=\u2009ai\u2009-\u20091\u2009+\u2009(\u2009-\u20091)i\u2009+\u20091\u00b7q (i\u2009>\u20091), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.Sequence s1,\u2009\u2009s2,\u2009\u2009...,\u2009\u2009sk is a subsequence of sequence b1,\u2009\u2009b2,\u2009\u2009...,\u2009\u2009bn, if there is such increasing sequence of indexes i1,\u2009i2,\u2009...,\u2009ik (1\u2009\u2009\u2264\u2009\u2009i1\u2009\u2009<\u2009\u2009i2\u2009\u2009<\u2009... \u2009\u2009<\u2009\u2009ik\u2009\u2009\u2264\u2009\u2009n), that bij\u2009\u2009=\u2009\u2009sj. In other words, sequence s can be obtained from b by crossing out some elements.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20094000). The next line contains n integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "Print a single integer \u2014 the length of the required longest subsequence.", "sample_inputs": ["2\n3 5", "4\n10 20 10 30"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10,\u200920,\u200910."}, "positive_code": [{"source_code": "import collection.mutable.Map\n\nobject test5 extends App {\n val n=readInt\n val b=readLine.split(\" \").map(_.toInt)\n val x=new Array[Int](n)\n val map=Map[Int,Int]()\n b.zipWithIndex.foreach {case (v,i)=>{\n if(!map.contains(v)) map(v)=map.size\n x(i)=map(v)\n }\n }\n \n val dp=Array.ofDim[Int](n,n)\n for(i<-0 until n) java.util.Arrays.fill(dp(i),1)\n \n var max=1\n for(i<-1 until n; j<-0 until i){\n dp(i)(x(j))=dp(j)(x(i))+1\n max=math.max(max, dp(i)(x(j)))\n }\n \n println(max)\n}\n"}], "negative_code": [{"source_code": "import collection.mutable.Map\n\nobject test5 extends App {\n val n=readInt\n val b=readLine.split(\" \").map(_.toInt)\n var max=1\n val dp=new Array[Map[Int,Int]](n)\n for(i<-0 until n) dp(i)=Map[Int,Int]()\n \n for(i<-1 until n; j<-i-1 to 0 by -1){\n var q=b(i)-b(j)\n if(!dp(i).contains(q) && dp(j).contains(q) && dp(j)(q)%2==0){\n dp(i)(q)=dp(j)(q)+1\n max=math.max(max,dp(i)(q))\n }\n \n if(!dp(i).contains(q)){\n if(dp(j).contains(-q) && dp(j)(-q)%2==1)\n dp(i)(-q)=dp(j)(-q)+1\n else\n dp(i)(-q)=2\n max=math.max(max,dp(i)(-q))\n }\n }\n \n println(max)\n}\n\n\n\n\n"}, {"source_code": "import collection.mutable.Map\n\nobject test5 extends App {\n val n=readInt\n val b=readLine.split(\" \").map(_.toInt)\n var max=1\n val dp=new Array[Map[Int,Int]](n)\n for(i<-0 until n) dp(i)=Map[Int,Int]()\n \n for(i<-1 until n; j<-i-1 to 0 by -1){\n var q=b(i)-b(j)\n if(!dp(i).contains(q) && dp(j).contains(q) && dp(j)(q)%2==0){\n dp(i)(q)=dp(j)(q)+1\n max=math.max(max,dp(i)(q))\n }\n \n if(!dp(i).contains(-q)){\n if(dp(j).contains(-q) && dp(j)(-q)%2==1)\n dp(i)(-q)=dp(j)(-q)+1\n else\n dp(i)(-q)=2\n max=math.max(max,dp(i)(-q))\n }\n }\n \n println(max)\n}\n\n\n\n\n"}, {"source_code": "import collection.mutable.Map\n\nobject test5 extends App {\n val n=readInt\n val b=readLine.split(\" \").map(_.toInt)\n var max=0\n val dp=new Array[Map[Int,Int]](n)\n for(i<-0 until n) dp(i)=Map[Int,Int]()\n \n for(i<-1 until n; j<-i-1 to 0 by -1){\n var q=b(i)-b(j)\n if(dp(j).contains(q) && dp(j)(q)%2==0){\n dp(i)(q)=math.max(dp(i).getOrElse(q, 0),dp(j)(q)+1)\n max=math.max(max,dp(i)(q))\n }\n if(dp(j).contains(-q) && dp(j)(-q)%2==1)\n dp(i)(-q)=math.max(dp(i).getOrElse(-q,0),dp(j)(-q)+1)\n else\n dp(i)(-q)=math.max(dp(i).getOrElse(-q,0),2)\n\n max=math.max(max,dp(i)(-q))\n }\n \n println(max)\n}\n\n\n\n\n"}, {"source_code": "\n\nobject test5 extends App {\n val n=readInt\n val b=readLine.split(\" \").map(_.toInt)\n var max=0\n var q=0\n var count=1\n \n val getQ=(i:Int)=>{\n val ret=b(i)-b(i-1)\n if(i%2==0) ret else -ret\n }\n \n for(i<-1 until n){\n if(getQ(i)==q){\n count+=1\n }\n else{\n q=getQ(i)\n max=math.max(max,count)\n count=2\n }\n }\n max=math.max(max,count)\n println(max)\n}\n\n\n\n\n"}, {"source_code": "import collection.mutable.Map\n\nobject test5 extends App {\n val n=readInt\n val b=readLine.split(\" \").map(_.toInt)\n var max=1\n val dp=new Array[Map[Int,Int]](n)\n for(i<-0 until n) dp(i)=Map[Int,Int]()\n \n for(i<-1 until n; j<-i-1 to 0 by -1){\n var q=b(i)-b(j)\n if(!dp(i).contains(q)){\n if(dp(j).contains(q) && dp(j)(q)%2==0){\n dp(i)(q)=dp(j)(q)+1\n max=math.max(max,dp(i)(q))\n }\n }\n \n if(!dp(i).contains(-q)){\n if(dp(j).contains(-q) && dp(j)(-q)%2==1)\n dp(i)(-q)=dp(j)(-q)+1\n else\n dp(i)(-q)=2\n max=math.max(max,dp(i)(-q))\n }\n }\n \n println(max)\n}\n\n\n\n\n"}], "src_uid": "86ded9e6336a14b43dda780ebd099b4f"} {"nl": {"description": "...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops. ", "input_spec": "The first line contains two integers \u2014 the number of vertices n and the number of edges m of the graph (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 0\u2009\u2264\u2009m\u2009\u2264\u2009). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n,\u2009x\u2009\u2260\u2009y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.", "output_spec": "Print \"NO\", if the graph is not Cthulhu and \"FHTAGN!\" if it is.", "sample_inputs": ["6 6\n6 3\n6 4\n5 1\n2 5\n1 4\n5 4", "6 5\n5 6\n4 6\n3 1\n5 1\n1 2"], "sample_outputs": ["FHTAGN!", "NO"], "notes": "NoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v\u2009-\u20091 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and n\u2009-\u20091 edges (n\u2009>\u20090).A rooted tree is a tree where one vertex is selected to be the root."}, "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 var graph = Set.empty[Set[Int]]\n var list = List.empty[(Int, Int)]\n (1 to m).foreach{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n list ::= (Math.max(a, b), Math.min(a, b))\n val first = graph.find(_.contains(a))\n val second = graph.find(_.contains(b))\n if (first.isEmpty && second.isEmpty)\n graph += Set(a, b)\n else if (first.isEmpty && second.isDefined) {\n graph -= second.get\n graph += (second.get + a)\n } else if (first.isDefined && second.isEmpty) {\n graph -= first.get\n graph += (first.get + b)\n } else if (first != second) {\n graph -= first.get\n graph -= second.get\n graph += (first.get ++ second.get)\n }\n }\n if (n == m && graph.size == 1 && graph.head.size == n) {\n println(\"FHTAGN!\")\n } else {\n println(\"NO\")\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 var graph = Set.empty[Set[Int]]\n var list = List.empty[(Int, Int)]\n (1 to m).foreach{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n list ::= (Math.max(a, b), Math.min(a, b))\n val first = graph.find(_.contains(a))\n val second = graph.find(_.contains(b))\n if (first.isEmpty && second.isEmpty)\n graph += Set(a, b)\n else if (first.isEmpty && second.isDefined) {\n graph -= second.get\n graph += (second.get + a)\n } else if (first.isDefined && second.isEmpty) {\n graph -= first.get\n graph += (first.get + b)\n } else if (first != second) {\n graph -= first.get\n graph -= second.get\n graph += (first.get ++ second.get)\n }\n }\n if (n == m && graph.size == 1 && graph.size == n) {\n println(\"FHTAGN!\")\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 var graph = Set.empty[Set[Int]]\n (1 to m).foreach{ _ =>\n val Array(a, b) = in.next().split(\" \").map(_.toInt - 1)\n val first = graph.find(_.contains(a))\n val second = graph.find(_.contains(b))\n if (first.isEmpty && second.isEmpty)\n graph += Set(a, b)\n else if (first.isEmpty && second.isDefined) {\n graph -= second.get\n graph += (second.get + a)\n } else if (first.isDefined && second.isEmpty) {\n graph -= first.get\n graph += (first.get + b)\n } else if (first != second) {\n graph -= first.get\n graph -= second.get\n graph += (first.get ++ second.get)\n }\n }\n if (n == m && graph.size == 1) {\n println(\"FHTAGN!\")\n } else {\n println(\"NO\")\n }\n\n}"}], "src_uid": "4ecbfc792da55f458342c6eff2d5da5a"} {"nl": {"description": "There are n cities in Berland, each of them has a unique id\u00a0\u2014 an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads\u00a0\u2014 there are no roads.That is why there was a decision to build n\u2009-\u20091 roads so that there will be exactly one simple path between each pair of cities.In the construction plan t integers a1,\u2009a2,\u2009...,\u2009at were stated, where t equals to the distance from the capital to the most distant city, concerning new roads. ai equals the number of cities which should be at the distance i from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another. Also, it was decided that among all the cities except the capital there should be exactly k cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it. Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.", "input_spec": "The first line contains three positive numbers n, t and k (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009t,\u2009k\u2009<\u2009n)\u00a0\u2014 the distance to the most distant city from the capital and the number of cities which should be dead-ends (the capital in this number is not taken into consideration). The second line contains a sequence of t integers a1,\u2009a2,\u2009...,\u2009at (1\u2009\u2264\u2009ai\u2009<\u2009n), the i-th number is the number of cities which should be at the distance i from the capital. It is guaranteed that the sum of all the values ai equals n\u2009-\u20091.", "output_spec": "If it is impossible to built roads which satisfy all conditions, print -1. Otherwise, in the first line print one integer n\u00a0\u2014 the number of cities in Berland. In the each of the next n\u2009-\u20091 line print two integers\u00a0\u2014 the ids of cities that are connected by a road. Each road should be printed exactly once. You can print the roads and the cities connected by a road in any order. If there are multiple answers, print any of them. Remember that the capital has id 1.", "sample_inputs": ["7 3 3\n2 3 1", "14 5 6\n4 4 2 2 1", "3 1 1\n2"], "sample_outputs": ["7\n1 3\n2 1\n2 6\n2 4\n7 4\n3 5", "14\n3 1\n1 4\n11 6\n1 2\n10 13\n6 10\n10 12\n14 12\n8 4\n5 1\n3 7\n2 6\n5 9", "-1"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \\times 2$$$\u00a0\u2014 Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5000$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the width of the grid. The second line of each test case contains a string $$$s$$$ consisting of $$$n$$$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid. Additional constraint on the input: each input corresponds to at least one valid tiling.", "output_spec": "For each test case, output one string\u00a0\u2014 the other row of the grid, using the same format as the input string. If there are multiple answers, print any.", "sample_inputs": ["4\n1\nU\n2\nLR\n5\nLRDLR\n6\nUUUUUU"], "sample_outputs": ["D\nLR\nLRULR\nDDDDDD"], "notes": "NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like: In the second test case, Alice shows Bob the bottom row, the whole grid may look like: In the third test case, Alice shows Bob the bottom row, the whole grid may look like: In the fourth test case, Alice shows Bob the top row, the whole grid may look like: "}, "positive_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 writer.flush()\r\n println()\r\n }\r\n }\r\n}\r\n"}, {"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"} {"nl": {"description": "One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a,\u2009b) (a\u2009\u2260\u2009b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and \u0441 are immediate neighbors, and b and c are immediate neighbors. As you can easily deduce, in the end Vasya drew 2\u00b7n arcs.For example, if the numbers are written in the circle in the order 1,\u20092,\u20093,\u20094,\u20095 (in the clockwise direction), then the arcs will join pairs of integers (1,\u20092), (2,\u20093), (3,\u20094), (4,\u20095), (5,\u20091), (1,\u20093), (2,\u20094), (3,\u20095), (4,\u20091) and (5,\u20092).Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with 2\u00b7n written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs.", "input_spec": "The first line of the input contains a single integer n (5\u2009\u2264\u2009n\u2009\u2264\u2009105) that shows, how many numbers were written on the board. Next 2\u00b7n lines contain pairs of integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi) \u2014 the numbers that were connected by the arcs. It is guaranteed that no pair of integers, connected by a arc, occurs in the input more than once. The pairs of numbers and the numbers in the pairs are given in the arbitrary order.", "output_spec": "If Vasya made a mistake somewhere and there isn't any way to place numbers from 1 to n on the circle according to the statement, then print a single number \"-1\" (without the quotes). Otherwise, print any suitable sequence of n distinct integers from 1 to n. If there are multiple solutions, you are allowed to print any of them. Specifically, it doesn't matter which number you write first to describe the sequence of the order. It also doesn't matter whether you write out the numbers in the clockwise or counter-clockwise direction.", "sample_inputs": ["5\n1 2\n2 3\n3 4\n4 5\n5 1\n1 3\n2 4\n3 5\n4 1\n5 2", "6\n5 6\n4 3\n5 3\n2 4\n6 1\n3 1\n6 2\n2 5\n1 4\n3 6\n1 2\n4 5"], "sample_outputs": ["1 2 3 4 5", "1 2 4 5 3 6"], "notes": null}, "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 //\u5168p\u3092check\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"}, {"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 //\u5168p\u3092check\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"}], "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 //\u5168p\u3092check\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"} {"nl": {"description": "There are three cells on an infinite 2-dimensional grid, labeled $$$A$$$, $$$B$$$, and $$$F$$$. Find the length of the shortest path from $$$A$$$ to $$$B$$$ if: in one move you can go to any of the four adjacent cells sharing a side; visiting the cell $$$F$$$ is forbidden (it is an obstacle). ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first one contains two integers $$$x_A, y_A$$$ ($$$1 \\le x_A, y_A \\le 1000$$$)\u00a0\u2014 coordinates of the start cell $$$A$$$. The second one contains two integers $$$x_B, y_B$$$ ($$$1 \\le x_B, y_B \\le 1000$$$)\u00a0\u2014 coordinates of the finish cell $$$B$$$. The third one contains two integers $$$x_F, y_F$$$ ($$$1 \\le x_F, y_F \\le 1000$$$)\u00a0\u2014 coordinates of the forbidden cell $$$F$$$. All cells are distinct. Coordinate $$$x$$$ corresponds to the column number and coordinate $$$y$$$ corresponds to the row number (see the pictures below).", "output_spec": "Output $$$t$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th test case: the length of the shortest path from the cell $$$A$$$ to the cell $$$B$$$ if the cell $$$F$$$ is not allowed to be visited.", "sample_inputs": ["7\n\n1 1\n3 3\n2 2\n\n2 5\n2 1\n2 3\n\n1000 42\n1000 1\n1000 1000\n\n1 10\n3 10\n2 10\n\n3 8\n7 8\n3 7\n\n2 1\n4 1\n1 1\n\n1 344\n1 10\n1 1"], "sample_outputs": ["4\n6\n41\n4\n4\n2\n334"], "notes": "Note An example of a possible shortest path for the first test case. An example of a possible shortest path for the second test case. "}, "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 readLine()\r\n val Array(xa, ya) = readLine().split(\" \").map(_.toInt)\r\n val Array(xb, yb) = readLine().split(\" \").map(_.toInt)\r\n val Array(xf, yf) = readLine().split(\" \").map(_.toInt)\r\n\r\n val (x1, x2) = (xa min xb, xa max xb)\r\n val (y1, y2) = (ya min yb, ya max yb)\r\n\r\n val ans =\r\n x2 - x1 +\r\n y2 - y1 +\r\n (if (x1 == x2 && x1 == xf && y1 < yf && yf < y2 || y1 == y2 && y1 == yf && x1 < xf && xf < x2) 2 else 0)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "6422d76f71702e77808b1cc041962bb8"} {"nl": {"description": "There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.", "input_spec": "The first line of the input data contains two integer numbers separated by a space n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) and k (0\u2009\u2264\u2009k\u2009\u2264\u2009106) \u2014 the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009106) is the height of the i-th book in millimeters.", "output_spec": "In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b \u2014 the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space \u2014 indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.", "sample_inputs": ["3 3\n14 12 10", "2 0\n10 10", "4 5\n8 19 10 13"], "sample_outputs": ["2 2\n1 2\n2 3", "2 1\n1 2", "2 1\n3 4"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \\le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \\le i < j < k \\le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \\le n \\le 5 \\cdot 10^4$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$; $$$a_{i - 1} \\le a_i$$$)\u00a0\u2014 the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the answer to it in one line. If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1.", "sample_inputs": ["3\n7\n4 6 11 11 15 18 20\n4\n10 10 10 11\n3\n1 1 1000000000"], "sample_outputs": ["2 3 6\n-1\n1 2 3"], "notes": "NoteIn the first test case it is impossible with sides $$$6$$$, $$$11$$$ and $$$18$$$. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle."}, "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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Casimir has a string $$$s$$$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions: he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent); or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by $$$2$$$. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with $$$s$$$\u00a0$$$=$$$\u00a0\"ABCABC\" he can obtain a string $$$s$$$\u00a0$$$=$$$\u00a0\"ACBC\" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string $$$s$$$ determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Each test case is described by one string $$$s$$$, for which you need to determine if it can be fully erased by some sequence of turns. The string $$$s$$$ consists of capital letters 'A', 'B', 'C' and has a length from $$$1$$$ to $$$50$$$ letters, inclusive.", "output_spec": "Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if there is a way to fully erase the corresponding string and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).", "sample_inputs": ["6\nABACAB\nABBA\nAC\nABC\nCABCBB\nBCBCBCBCBCBCBCBC"], "sample_outputs": ["NO\nYES\nNO\nNO\nYES\nYES"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "ca6b162f945d4216055bf92d7263dbd5"} {"nl": {"description": "Are you going to Scarborough Fair?Parsley, sage, rosemary and thyme.Remember me to one who lives there.He once was the true love of mine.Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.Although the girl wants to help, Willem insists on doing it by himself.Grick gave Willem a string of length n.Willem needs to do m operations, each operation has four parameters l,\u2009r,\u2009c1,\u2009c2, which means that all symbols c1 in range [l,\u2009r] (from l-th to r-th, including l and r) are changed into c2. String is 1-indexed.Grick wants to know the final string after all the m operations.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). The second line contains a string s of length n, consisting of lowercase English letters. Each of the next m lines contains four parameters l,\u2009r,\u2009c1,\u2009c2 (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n, c1,\u2009c2 are lowercase English letters), separated by space.", "output_spec": "Output string s after performing m operations described above.", "sample_inputs": ["3 1\nioi\n1 1 i n", "5 3\nwxhak\n3 3 h x\n1 5 x a\n1 3 w g"], "sample_outputs": ["noi", "gaaak"], "notes": "NoteFor the second example:After the first operation, the string is wxxak.After the second operation, the string is waaak.After the third operation, the string is gaaak."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters \"-\".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format \"dd-mm-yyyy\". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy \"0012-10-2012-10-2012\" mentions date 12-10-2012 twice (first time as \"0012-10-2012-10-2012\", second time as \"0012-10-2012-10-2012\").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format \"dd-mm-yyyy\", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date \"1-1-2013\" isn't recorded in the format \"dd-mm-yyyy\", and date \"01-01-2013\" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.", "input_spec": "The first line contains the Prophesy: a non-empty string that only consists of digits and characters \"-\". The length of the Prophesy doesn't exceed 105 characters.", "output_spec": "In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.", "sample_inputs": ["777-444---21-12-2013-12-2013-12-2013---444-777"], "sample_outputs": ["13-12-2013"], "notes": null}, "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 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}"}, {"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 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}"}], "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"} {"nl": {"description": "Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.", "input_spec": "The first line contains three integers n, m and x (2\u2009\u2264\u2009n\u2009\u2264\u200950, 1\u2009\u2264\u2009m\u2009\u2264\u2009500, 1\u2009\u2264\u2009x\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of nodes, the number of directed edges and the number of bears, respectively. Each of the following m lines contains three integers ai, bi and ci (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi, 1\u2009\u2264\u2009ci\u2009\u2264\u20091\u2009000\u2009000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i\u2009\u2260\u2009j it's guaranteed that ai\u2009\u2260\u2009aj or bi\u2009\u2260\u2009bj. It is also guaranteed that there is at least one path from node 1 to node n.", "output_spec": "Print one real value on a single line\u00a0\u2014 the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .", "sample_inputs": ["4 4 3\n1 2 2\n2 4 1\n1 3 1\n3 4 2", "5 11 23\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 3 4\n2 4 5\n3 5 6\n1 4 2\n2 5 3\n1 5 2\n3 2 30"], "sample_outputs": ["1.5000000000", "10.2222222222"], "notes": "NoteIn the first sample, Niwel has three bears. Two bears can choose the path , while one bear can choose the path . Even though the bear that goes on the path can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day."}, "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 def maxFlow(cap: Array[Array[Long]], s: Int, t: Int): Long = {\n\n val n = cap.size\n val untilN = 0 until n\n var flow = 0L\n\n val adj = Array.fill(n, n)(0)\n val deg = Array.fill(n)(0)\n\n for (u <- untilN) {\n for (v <- untilN) if (cap(u)(v) != 0 && u != v) {\n adj(u)(deg(u)) = v\n deg(u) += 1\n //adj(v)(deg(v)) = u\n //deg(v) += 1\n }\n }\n\n var done = false\n val q = Array.fill(n)(-1) // BFS stuff\n\n while (!done) {\n\n // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable\n val prev = Array.fill(n)(-1)\n\n // find an augmenting path\n var qf = 0\n var qb = 1\n q(0) = s\n prev(s) = -2\n while (qb > qf && prev(t) == -1) {\n val u = q(qf)\n qf += 1\n for (i <- 0 until deg(u)) {\n val v = adj(u)(i)\n if (prev(v) == -1 && cap(u)(v) != 0) {\n q(qb) = v\n qb += 1\n prev(v) = u\n }\n }\n }\n\n if (prev(t) == -1) done = true\n else // try finding more paths:\n for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {\n var bot = cap(z)(t)\n var v = z\n var u = prev(v)\n while (u >= 0) {\n bot = math.min(bot, cap(u)(v))\n v = u\n u = prev(v)\n }\n\n if (bot != 0) {\n\n cap(z)(t) -= bot\n cap(t)(z) += bot\n\n v = z\n u = prev(v)\n while (u >= 0) {\n cap(u)(v) -= bot\n cap(v)(u) += bot\n v = u\n u = prev(v)\n }\n\n flow += bot\n }\n }\n }\n\n flow\n }\n\n val Array(n, m, x) = readInts(3)\n val ws = Array.fill(n, n){ 0L }\n\n for (_ <- 0 until m) {\n val Array(a, b, c) = readInts(3)\n ws(a - 1)(b - 1) = c\n }\n\n def can(c: Double): Boolean = {\n val caps = ws.map {\n _.map {\n w => if (w == 0) 0 else {\n if (x * c > w) (w / c).floor.toLong else x\n }\n }\n }\n maxFlow(caps, 0, n - 1) >= x\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n if (depth > 60) (lo + hi) / 2\n else {\n val mid = (lo + hi) / 2\n if (can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n println(x * binSearchD(0.1d / x, 10000000d, 0))\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\n def maxFlow(cap: Array[Array[Long]], s: Int, t: Int): Long = {\n\n val n = cap.size\n val untilN = 0 until n\n var flow = 0L\n\n val adj = Array.fill(n, n)(0)\n val deg = Array.fill(n)(0)\n\n for (u <- untilN) {\n for (v <- untilN) if (cap(u)(v) != 0 && u != v) {\n adj(u)(deg(u)) = v\n deg(u) += 1\n //adj(v)(deg(v)) = u\n //deg(v) += 1\n }\n }\n\n var done = false\n val q = Array.fill(n)(-1) // BFS stuff\n\n while (!done) {\n\n // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable\n val prev = Array.fill(n)(-1)\n\n // find an augmenting path\n var qf = 0\n var qb = 1\n q(0) = s\n prev(s) = -2\n while (qb > qf && prev(t) == -1) {\n val u = q(qf)\n qf += 1\n for (i <- 0 until deg(u)) {\n val v = adj(u)(i)\n if (prev(v) == -1 && cap(u)(v) != 0) {\n q(qb) = v\n qb += 1\n prev(v) = u\n }\n }\n }\n\n if (prev(t) == -1) done = true\n else // try finding more paths:\n for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {\n var bot = cap(z)(t)\n var v = z\n var u = prev(v)\n while (u >= 0) {\n bot = math.min(bot, cap(u)(v))\n v = u\n u = prev(v)\n }\n\n if (bot != 0) {\n\n cap(z)(t) -= bot\n cap(t)(z) += bot\n\n v = z\n u = prev(v)\n while (u >= 0) {\n cap(u)(v) -= bot\n cap(v)(u) += bot\n v = u\n u = prev(v)\n }\n\n flow += bot\n }\n }\n }\n\n flow\n }\n\n val Array(n, m, x) = readInts(3)\n val ws = Array.fill(n, n){ 0L }\n\n for (_ <- 0 until m) {\n val Array(a, b, c) = readInts(3)\n ws(a - 1)(b - 1) = c\n }\n\n def can(c: Double): Boolean = {\n val caps = ws.map {\n _.map {\n w => if (w == 0) 0 else {\n var y = x.toLong\n try {\n y = if (x * c > w) (w / c).floor.toLong else x\n } catch {\n case _: Exception =>\n }\n y\n }\n }\n }\n maxFlow(caps, 0, n - 1) >= x\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n //println(depth, lo, hi)\n if (depth > 50 || math.abs(hi - lo) < 1E-7d || hi / lo < 1d + 1E-7d) (lo + hi) / 2\n else {\n val mid = (lo + hi) / 2\n if (can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n println(x * binSearchD(1d / x, 1000000d, 0))\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 def maxFlow(cap: Array[Array[Long]], s: Int, t: Int): Long = {\n\n val n = cap.size\n val untilN = 0 until n\n var flow = 0L\n\n val adj = Array.fill(n, n)(0)\n val deg = Array.fill(n)(0)\n\n for (u <- untilN) {\n for (v <- untilN) if (cap(u)(v) != 0) {\n adj(u)(deg(u)) = v\n deg(u) += 1\n adj(v)(deg(v)) = u\n deg(v) += 1\n }\n }\n\n var done = false\n val q = Array.fill(n)(-1) // BFS stuff\n\n while (!done) {\n\n // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable\n val prev = Array.fill(n)(-1)\n\n // find an augmenting path\n var qf = 0\n var qb = 1\n q(0) = s\n prev(s) = -2\n while (qb > qf && prev(t) == -1) {\n val u = q(qf)\n qf += 1\n for (i <- 0 until deg(u)) {\n val v = adj(u)(i)\n if (prev(v) == -1 && cap(u)(v) != 0) {\n q(qb) = v\n qb += 1\n prev(v) = u\n }\n }\n }\n\n if (prev(t) == -1) done = true\n else // try finding more paths:\n for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {\n var bot = cap(z)(t)\n var v = z\n var u = prev(v)\n while (u >= 0) {\n bot = math.min(bot, cap(u)(v))\n v = u\n u = prev(v)\n }\n\n if (bot != 0) {\n\n cap(z)(t) -= bot\n cap(t)(z) += bot\n\n v = z\n u = prev(v)\n while (u >= 0) {\n cap(u)(v) -= bot\n cap(v)(u) += bot\n v = u\n u = prev(v)\n }\n\n flow += bot\n }\n }\n }\n\n flow\n }\n\n val Array(n, m, x) = readInts(3)\n val ws = Array.fill(n, n){ 0 }\n\n for (_ <- 0 until m) {\n val Array(a, b, c) = readInts(3)\n ws(a - 1)(b - 1) = c\n }\n\n def can(c: Double): Boolean = {\n val caps = ws.map {\n _.map {\n w => (w / c).floor.toLong\n }\n }\n maxFlow(caps, 0, n - 1) >= x\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n if (depth > 20 || math.abs(hi - lo) < 1E-7d || hi / lo < 1d + 1E-7d) (lo + hi) / 2\n else {\n val mid = (lo + hi) / 2\n if (can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n println(x * binSearchD(0.8d / x, 10000000d, 0))\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 def maxFlow(cap: Array[Array[Int]], s: Int, t: Int): Int = {\n\n val n = cap.size\n val untilN = 0 until n\n var flow = 0\n\n val adj = Array.fill(n, n)(0)\n val deg = Array.fill(n)(0)\n\n for (u <- untilN) {\n for (v <- untilN) if (cap(u)(v) != 0) {\n adj(u)(deg(u)) = v\n deg(u) += 1\n adj(v)(deg(v)) = u\n deg(v) += 1\n }\n }\n\n var done = false\n val q = Array.fill(n)(-1) // BFS stuff\n\n while (!done) {\n\n // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable\n val prev = Array.fill(n)(-1)\n\n // find an augmenting path\n var qf = 0\n var qb = 1\n q(0) = s\n prev(s) = -2\n while (qb > qf && prev(t) == -1) {\n val u = q(qf)\n qf += 1\n for (i <- 0 until deg(u)) {\n val v = adj(u)(i)\n if (prev(v) == -1 && cap(u)(v) != 0) {\n q(qb) = v\n qb += 1\n prev(v) = u\n }\n }\n }\n\n if (prev(t) == -1) done = true\n else // try finding more paths:\n for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {\n var bot = cap(z)(t)\n var v = z\n var u = prev(v)\n while (u >= 0) {\n bot = math.min(bot, cap(u)(v))\n v = u\n u = prev(v)\n }\n\n if (bot != 0) {\n\n cap(z)(t) -= bot\n cap(t)(z) += bot\n\n v = z\n u = prev(v)\n while (u >= 0) {\n cap(u)(v) -= bot\n cap(v)(u) += bot\n v = u\n u = prev(v)\n }\n\n flow += bot\n }\n }\n }\n\n flow\n }\n\n val Array(n, m, x) = readInts(3)\n val ws = Array.fill(n, n){ 0 }\n\n for (_ <- 0 until m) {\n val Array(a, b, c) = readInts(3)\n ws(a - 1)(b - 1) = c\n }\n\n def can(c: Double): Boolean = {\n val caps = ws.map {\n _.map {\n w => (w / c).floor.toInt\n }\n }\n maxFlow(caps, 0, n - 1) >= x\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double): Double = {\n if (math.abs(hi - lo) < 1E-6) hi\n else {\n val mid = (lo + hi) / 2\n if (can(mid)) binSearchD(mid, hi)\n else binSearchD(lo, mid)\n }\n }\n\n println(x * binSearchD(0.8d / x, 10000000d))\n}\n"}], "src_uid": "f404720fd6624174c33d93af6349e561"} {"nl": {"description": "Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive \"OR\", that is denoted as \"xor\" in Pascal and \"^\" in C/C++/Java.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.", "output_spec": "Print a single integer \u2014 the required maximal xor of a segment of consecutive elements.", "sample_inputs": ["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"], "sample_outputs": ["3", "7", "14"], "notes": "NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three)."}, "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 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"}, {"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"} {"nl": {"description": "In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second \u2014 number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 \u2014 AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.", "input_spec": "The first line of the input contains integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .", "output_spec": "Write n lines, each line should contain a cell coordinates in the other numeration system.", "sample_inputs": ["2\nR23C55\nBC23"], "sample_outputs": ["BC23\nR23C55"], "notes": null}, "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": "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": "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.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 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"}, {"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"}, {"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 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.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"}], "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"} {"nl": {"description": "Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square. Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.", "input_spec": "The first line of the input contains number n\u00a0\u2014 the number of mines on the map (2\u2009\u2264\u2009n\u2009\u2264\u20091000). Each of the next n lines contains a pair of integers xi and yi\u00a0\u2014 the coordinates of the corresponding mine (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109). All points are pairwise distinct.", "output_spec": "Print the minimum area of the city that can cover all the mines with valuable resources.", "sample_inputs": ["2\n0 0\n2 2", "2\n0 0\n0 3"], "sample_outputs": ["4", "9"], "notes": null}, "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(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}"}, {"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"} {"nl": {"description": "You are given an undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. Your task is to find the number of connected components which are cycles.Here are some definitions of graph theory.An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $$$a$$$ is connected with a vertex $$$b$$$, a vertex $$$b$$$ is also connected with a vertex $$$a$$$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.Two vertices $$$u$$$ and $$$v$$$ belong to the same connected component if and only if there is at least one path along edges connecting $$$u$$$ and $$$v$$$.A connected component is a cycle if and only if its vertices can be reordered in such a way that: the first vertex is connected with the second vertex by an edge, the second vertex is connected with the third vertex by an edge, ... the last vertex is connected with the first vertex by an edge, all the described edges of a cycle are distinct. A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. There are $$$6$$$ connected components, $$$2$$$ of them are cycles: $$$[7, 10, 16]$$$ and $$$[5, 11, 9, 15]$$$. ", "input_spec": "The first line contains two integer numbers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le m \\le 2 \\cdot 10^5$$$) \u2014 number of vertices and edges. The following $$$m$$$ lines contains edges: edge $$$i$$$ is given as a pair of vertices $$$v_i$$$, $$$u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$u_i \\ne v_i$$$). There is no multiple edges in the given graph, i.e. for each pair ($$$v_i, u_i$$$) there no other pairs ($$$v_i, u_i$$$) and ($$$u_i, v_i$$$) in the list of edges.", "output_spec": "Print one integer \u2014 the number of connected components which are also cycles.", "sample_inputs": ["5 4\n1 2\n3 4\n5 4\n3 5", "17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example only component $$$[3, 4, 5]$$$ is also a cycle.The illustration above corresponds to the second example."}, "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, M = ni()\n val deg = Array.ofDim[Int](N)\n val uf = new UnionFind(N)\n rep(M) { _ =>\n val u, v = ni() -1\n deg(u) += 1\n deg(v) += 1\n uf.unite(u, v)\n }\n\n val cnt = Array.fill[mutable.Set[Int]](N)(mutable.Set())\n rep(N) { i =>\n cnt(uf.find(i)) += i\n }\n\n val ans = cnt count { set =>\n set.size >= 3 && (set forall (v => deg(v) == 2))\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n class UnionFind(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\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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": [], "src_uid": "cf7520d88e10ba171de443f36fdd2b73"} {"nl": {"description": "Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li,\u2009ri], besides, ri\u2009<\u2009li\u2009+\u20091 for 1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091.To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i\u2009+\u20091)-th islads, if there are such coordinates of x and y, that li\u2009\u2264\u2009x\u2009\u2264\u2009ri, li\u2009+\u20091\u2009\u2264\u2009y\u2009\u2264\u2009ri\u2009+\u20091 and y\u2009-\u2009x\u2009=\u2009a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.", "input_spec": "The first line contains integers n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) and m (1\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of islands and bridges. Next n lines each contain two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u20091018) \u2014 the coordinates of the island endpoints. The last line contains m integer numbers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u20091018) \u2014 the lengths of the bridges that Andrewid got.", "output_spec": "If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line \"No\" (without the quotes), otherwise print in the first line \"Yes\" (without the quotes), and in the second line print n\u2009-\u20091 numbers b1,\u2009b2,\u2009...,\u2009bn\u2009-\u20091, which mean that between islands i and i\u2009+\u20091 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print \"Yes\" and \"No\" in correct case.", "sample_inputs": ["4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8", "2 2\n11 14\n17 18\n2 9", "2 1\n1 1\n1000000000000000000 1000000000000000000\n999999999999999999"], "sample_outputs": ["Yes\n2 3 1", "No", "Yes\n1"], "notes": "NoteIn the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist."}, "positive_code": [{"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n val x=this.length-that.length\n if(x==0L){\n this.idx-that.idx\n }else{\n x.signum\n }\n\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-0 until n-1){\n val l=nextLong\n val r=nextLong\n gap(i)=new Gap(l-lastR,r-lastL,i)\n lastL=l\n lastR=r\n }\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n b+=new Bridge(nextLong,i+1)\n }\n\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val iter=b.iteratorFrom(new Bridge(gap(i).min,-1))\n if(iter.hasNext){\n val bg=iter.next\n if(bg.length>gap(i).max){\n dead=true;\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n }\n else{\n dead=true;\n break\n }\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n // out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n if(n==100 && (m==200))\n out.println(gap(i))\n }\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100&& (m==200)){\n// out.println(gap(i)+\" \"+bg.length)\n// b.foreach(e=>out.println(e.length))\n }\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n out.println(gap(i))\n }\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100&& (m==200)){\n out.println(gap(i)+\" \"+bg.length)\n }\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n // out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n // out.println(gap(i))\n }\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100&& (m==200)){\n out.println(gap(i)+\" \"+bg.length)\n }\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n // out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n // out.println(gap(i))\n }\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100&& (m==200)){\n out.println(gap(i)+\" \"+bg.length)\n b.foreach(e=>out.println(e.length))\n }\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n val x=this.max-that.max\n if(x>0){\n 1\n }else if(x<0){\n -1\n }else{\n (this.min-that.min).signum\n }\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n// out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n/* for(i<-0 until gap.size){\n out.println(gap(i))\n }*/\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n // out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n if(n==100&& (m==200)){\n out.println(gap.filter(_.max<=183).size+\" \"+b.filter(_.length<=183).size)\n out.println(gap.size+\" \"+b.size)\n }\n\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n// out.println(gap(i))\n }\n\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n // out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n if(n==100&& (m==200)){\n out.println(gap.filter(_.max<=183).size+\" \"+b.filter(_.length<=183).size)\n }\n\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n// out.println(gap(i))\n }\n\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n override def toString()={\n \"(\"+this.min+\",\"+this.max+\",\"+this.idx+\")\"\n }\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n // out.println(gap(i-1)+\" \"+l+\",\"+r+\",\"+lastL+\",\"+lastR)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n for(i<-0 until gap.size){\n// out.println(gap(i))\n }\n if(n==100&& (m==200)){\n out.println(gap.filter(_.max<=183).size+\" \"+b.filter(_.length<=183).size)\n }\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100&& (m==200)){\n// out.println(gap(i)+\" \"+bg.length)\n// b.foreach(e=>out.println(e.length))\n }\n break\n\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n\n }\n case None => {dead=true;\n break\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100){\n out.println(bg.length+\" \"+i)\n }\n\n break\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n }\n case None => {dead=true;\n if(n==100){\n out.println(i)\n }\n break\n\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n if(n==100&&(m==200)){\n out.println(bg.length+\" \"+i)\n }\n\n break\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n }\n case None => {dead=true;\n if(n==100&&(m==200)){\n out.println(i)\n }\n break\n\n }\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}, {"source_code": "object B2{\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 import scala.collection.mutable.TreeSet\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 class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{\n val min=imin\n val max=imax\n val idx=iidx\n def compare(that:Gap)={\n (this.max-that.max).signum\n }\n\n }\n class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{\n val length=ilength\n val idx=iidx\n def compare(that:Bridge)={\n (this.length-that.length).signum\n }\n }\n val gap=Array.ofDim[Gap](n-1)\n var lastL=nextLong\n var lastR=nextLong\n for(i<-1 until n){\n val l=nextLong\n val r=nextLong\n gap(i-1)=new Gap(l-lastR,r-lastL,i-1)\n lastL=l\n lastR=r\n }\n //val b=Array.ofDim[Bridge](m)\n val b=new TreeSet[Bridge]()\n for(i<-0 until m){\n //b(i)=new Bridge(nextLong,i+1)\n b+=new Bridge(nextLong,i+1)\n }\n import scala.util.Sorting.quickSort\n\n quickSort(gap)\n var dead=false\n val ans=Array.fill(n-1)(-1)\n\n breakable {\n for(i<-0 until n-1){\n val minl=gap(i).min\n b.find(_.length>=minl) match{\n case Some(bg)=> {\n if(bg.length>gap(i).max){\n dead=true;\n break\n }else{\n ans(gap(i).idx)=bg.idx\n b-=bg\n }\n }\n case None => {dead=true; break}\n }\n\n\n }\n }\n if(dead){\n out.println(\"No\")\n }else{\n out.println(\"Yes\")\n ans.foreach(e=>out.print(e+\" \"))\n out.println\n }\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "f7a34711e8a4faa9822d42ef54a0bfc1"} {"nl": {"description": "You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered top to bottom, the columns are numbered left to right.Each cell of the matrix can be either free or locked.Let's call a path in the matrix a staircase if it: starts and ends in the free cell; visits only free cells; has one of the two following structures: the second cell is $$$1$$$ to the right from the first one, the third cell is $$$1$$$ to the bottom from the second one, the fourth cell is $$$1$$$ to the right from the third one, and so on; the second cell is $$$1$$$ to the bottom from the first one, the third cell is $$$1$$$ to the right from the second one, the fourth cell is $$$1$$$ to the bottom from the third one, and so on. In particular, a path, consisting of a single cell, is considered to be a staircase.Here are some examples of staircases: Initially all the cells of the matrix are free.You have to process $$$q$$$ queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \\le n, m \\le 1000$$$; $$$1 \\le q \\le 10^4$$$)\u00a0\u2014 the sizes of the matrix and the number of queries. Each of the next $$$q$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x \\le n$$$; $$$1 \\le y \\le m$$$)\u00a0\u2014 the description of each query.", "output_spec": "Print $$$q$$$ integers\u00a0\u2014 the $$$i$$$-th value should be equal to the number of different staircases after $$$i$$$ queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.", "sample_inputs": ["2 2 8\n1 1\n1 1\n1 1\n2 2\n1 1\n1 2\n2 1\n1 1", "3 4 10\n1 4\n1 2\n2 3\n1 2\n2 3\n3 2\n1 3\n3 4\n1 3\n3 1", "1000 1000 2\n239 634\n239 634"], "sample_outputs": ["5\n10\n5\n2\n5\n3\n1\n0", "49\n35\n24\n29\n49\n39\n31\n23\n29\n27", "1332632508\n1333333000"], "notes": null}, "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 val rem = 1000000007\n\n val t = 1\n for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n val q = readInt()\n var cnt = 0L\n for (i <- 1 to n) {\n for (j <- 1 to m) {\n cnt += min(n - i, m - j) * 2L\n cnt += min(n - i, m - j + 1)\n cnt += min(n - i + 1, m - j)\n cnt += 1\n }\n }\n val arr = Array.ofDim[Boolean](n+1 ,m+1)\n var x = 0\n var y = 0\n var u1 = 0L\n var u2 = 0L\n var d1 = 0L\n var d2 = 0L\n var nx = 0\n var ny = 0\n for (k <- 1 to q) {\n x = readInt()\n y = readInt()\n u1 = 0L\n u2 = 0L\n d1 = 0L\n d2 = 0L\n nx = x\n ny = y-1\n while (nx >= 1 && ny >= 1 && !arr(nx)(ny)) {\n u1 += 1\n if (u1 % 2== 0)\n ny -= 1\n else\n nx -= 1\n }\n nx = x-1\n ny = y\n while (nx >= 1 && ny >= 1 && !arr(nx)(ny)) {\n u2 += 1\n if (u2 % 2== 1)\n ny -= 1\n else\n nx -= 1\n }\n nx = x+1\n ny = y\n while (nx <= n && ny <= m && !arr(nx)(ny)) {\n d1 += 1\n if (d1 % 2== 0)\n nx += 1\n else\n ny += 1\n }\n nx = x\n ny = y+1\n while (nx <= n && ny <= m && !arr(nx)(ny)) {\n d2 += 1\n if (d2 % 2== 1)\n nx += 1\n else\n ny += 1\n }\n //println(u1, u2, d1, d2)\n if (arr(x)(y))\n cnt += u1*d1 + u2*d2 + u1 + u2 + d1 + d2 + 1\n else\n cnt -= u1*d1 + u2*d2 + u1 + u2 + d1 + d2 + 1\n arr(x)(y) = !arr(x)(y)\n writer.println(cnt)\n }\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "c72b1a45f5cf80a31c239cf1409c0104"} {"nl": {"description": "Consider the set of all nonnegative integers: $$${0, 1, 2, \\dots}$$$. Given two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^4$$$). We paint all the numbers in increasing number first we paint $$$0$$$, then we paint $$$1$$$, then $$$2$$$ and so on.Each number is painted white or black. We paint a number $$$i$$$ according to the following rules: if $$$i = 0$$$, it is colored white; if $$$i \\ge a$$$ and $$$i - a$$$ is colored white, $$$i$$$ is also colored white; if $$$i \\ge b$$$ and $$$i - b$$$ is colored white, $$$i$$$ is also colored white; if $$$i$$$ is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors.For example, if $$$a=3$$$, $$$b=5$$$, then the colors of the numbers (in the order from $$$0$$$) are: white ($$$0$$$), black ($$$1$$$), black ($$$2$$$), white ($$$3$$$), black ($$$4$$$), white ($$$5$$$), white ($$$6$$$), black ($$$7$$$), white ($$$8$$$), white ($$$9$$$), ...Note that: It is possible that there are infinitely many nonnegative integers colored black. For example, if $$$a = 10$$$ and $$$b = 10$$$, then only $$$0, 10, 20, 30$$$ and any other nonnegative integers that end in $$$0$$$ when written in base 10 are white. The other integers are colored black. It is also possible that there are only finitely many nonnegative integers colored black. For example, when $$$a = 1$$$ and $$$b = 10$$$, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored black is infinite.If there are infinitely many nonnegative integers colored black, simply print a line containing \"Infinite\" (without the quotes). Otherwise, print \"Finite\" (without the quotes).", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then $$$t$$$ lines follow, each line contains two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^4$$$).", "output_spec": "For each test case, print one line containing either \"Infinite\" or \"Finite\" (without the quotes). Output is case-insensitive (i.e. \"infinite\", \"inFiNite\" or \"finiTE\" are all valid answers).", "sample_inputs": ["4\n10 10\n1 10\n6 9\n7 3"], "sample_outputs": ["Infinite\nFinite\nInfinite\nFinite"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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"} {"nl": {"description": "PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $$$6$$$ slices, medium ones consist of $$$8$$$ slices, and large pizzas consist of $$$10$$$ slices each. Baking them takes $$$15$$$, $$$20$$$ and $$$25$$$ minutes, respectively.Petya's birthday is today, and $$$n$$$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least $$$n$$$ slices in total. For example: if $$$12$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$12$$$ slices in total. He can order two small pizzas, containing exactly $$$12$$$ slices, and the time to bake them is $$$30$$$ minutes; if $$$15$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$15$$$ slices in total. He can order a small pizza and a large pizza, containing $$$16$$$ slices, and the time to bake them is $$$40$$$ minutes; if $$$300$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$300$$$ slices in total. He can order $$$15$$$ small pizzas, $$$10$$$ medium pizzas and $$$13$$$ large pizzas, in total they contain $$$15 \\cdot 6 + 10 \\cdot 8 + 13 \\cdot 10 = 300$$$ slices, and the total time to bake them is $$$15 \\cdot 15 + 10 \\cdot 20 + 13 \\cdot 25 = 750$$$ minutes; if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $$$15$$$ minutes. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. Each testcase consists of a single line that contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^{16}$$$)\u00a0\u2014 the number of Petya's friends.", "output_spec": "For each testcase, print one integer\u00a0\u2014 the minimum number of minutes that is needed to bake pizzas containing at least $$$n$$$ slices in total.", "sample_inputs": ["6\n12\n15\n300\n1\n9999999999999999\n3"], "sample_outputs": ["30\n40\n750\n15\n25000000000000000\n15"], "notes": null}, "positive_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 && 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ \u2014 the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ \u2014 the lower bound of their preferred temperature range, and $$$h_i$$$ \u2014 the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.", "input_spec": "Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \\le q \\le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100$$$, $$$-10^9 \\le m \\le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \\le t_i \\le 10^9$$$, $$$-10^9 \\le l_i \\le h_i \\le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.", "output_spec": "For each test case, print \"YES\" if it is possible to satisfy all customers. Otherwise, print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val q = readInt\n (0 until q).foreach((q) => f1)\n }\n\n def f1: Unit = {\n val Array(n, m) = readLine.split(\" \").map(_.toLong)\n var l: Long = m\n var r: Long = m\n var i: Long = 0\n var t: Long = 0\n var b = true\n while (i < n) {\n val Array(ct, lt, ht) = readLine.split(\" \").map(_.toLong)\n l -= (ct - t)\n r += (ct - t)\n t = ct\n l = Math.max(l, lt)\n r = Math.min(r, ht)\n if (l > r) b = false\n i = i + 1\n }\n if (b) println(\"YES\") else println(\"NO\")\n }\n}\n"}], "negative_code": [], "src_uid": "a75b8b9b99b800762645ef7c3bc29905"} {"nl": {"description": "This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai\u00a0\u2014 how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.", "input_spec": "The first line of the input contains two positive integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20091000)\u00a0\u2014 the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u20091000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.", "output_spec": "Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.", "sample_inputs": ["3 1\n2 1 4\n11 3 16", "4 3\n4 3 5 6\n11 12 14 20"], "sample_outputs": ["4", "3"], "notes": "NoteIn the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer."}, "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: 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: 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": "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"}, {"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"}], "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"} {"nl": {"description": "Oleg the bank client lives in Bankopolia. There are n cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from 1 to n. There are a total of m roads in Bankopolia, the i-th road connects cities ui and vi. It is guaranteed that from each city it is possible to travel to any other city using some of the roads.Oleg wants to give a label to each city. Suppose the label of city i is equal to xi. Then, it must hold that for all pairs of cities (u,\u2009v) the condition |xu\u2009-\u2009xv|\u2009\u2264\u20091 holds if and only if there is a road connecting u and v.Oleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.", "input_spec": "The first line of input contains two space-separated integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105, 1\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105)\u00a0\u2014 the number of cities and the number of roads. Next, m lines follow. The i-th line contains two space-separated integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi)\u00a0\u2014 the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities and it is possible to travel from any city to any other city using some roads.", "output_spec": "If the required labeling is not possible, output a single line containing the string \"NO\" (without quotes). Otherwise, output the string \"YES\" (without quotes) on the first line. On the next line, output n space-separated integers, x1,\u2009x2,\u2009...,\u2009xn. The condition 1\u2009\u2264\u2009xi\u2009\u2264\u2009109 must hold for all i, and for all pairs of cities (u,\u2009v) the condition |xu\u2009-\u2009xv|\u2009\u2264\u20091 must hold if and only if there is a road connecting u and v.", "sample_inputs": ["4 4\n1 2\n1 3\n1 4\n3 4", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n5 4", "4 3\n1 2\n1 3\n1 4"], "sample_outputs": ["YES\n2 3 1 1", "YES\n1 1 1 1 1", "NO"], "notes": "NoteFor the first sample, x1\u2009=\u20092, x2\u2009=\u20093, x3\u2009=\u2009x4\u2009=\u20091 is a valid labeling. Indeed, (3,\u20094), (1,\u20092), (1,\u20093), (1,\u20094) are the only pairs of cities with difference of labels not greater than 1, and these are precisely the roads of Bankopolia.For the second sample, all pairs of cities have difference of labels not greater than 1 and all pairs of cities have a road connecting them.For the last sample, it is impossible to construct a labeling satisfying the given constraints."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given integer $$$n$$$. You have to arrange numbers from $$$1$$$ to $$$2n$$$, using each of them exactly once, on the circle, so that the following condition would be satisfied:For every $$$n$$$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $$$2n$$$ numbers differ not more than by $$$1$$$.For example, choose $$$n = 3$$$. On the left you can see an example of a valid arrangement: $$$1 + 4 + 5 = 10$$$, $$$4 + 5 + 2 = 11$$$, $$$5 + 2 + 3 = 10$$$, $$$2 + 3 + 6 = 11$$$, $$$3 + 6 + 1 = 10$$$, $$$6 + 1 + 4 = 11$$$, any two numbers differ by at most $$$1$$$. On the right you can see an invalid arrangement: for example, $$$5 + 1 + 6 = 12$$$, and $$$3 + 2 + 4 = 9$$$, $$$9$$$ and $$$12$$$ differ more than by $$$1$$$. ", "input_spec": "The first and the only line contain one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$).", "output_spec": "If there is no solution, output \"NO\" in the first line. If there is a solution, output \"YES\" in the first line. In the second line output $$$2n$$$ numbers\u00a0\u2014 numbers from $$$1$$$ to $$$2n$$$ in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.", "sample_inputs": ["3", "4"], "sample_outputs": ["YES\n1 4 5 2 3 6", "NO"], "notes": "NoteExample from the statement is shown for the first example. It can be proved that there is no solution in the second example."}, "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(n) = readInts(1)\n\n val res = Array.ofDim[Int](2 * n)\n\n var l = 1\n var r = 2 * n\n for (i <- 0 until n) {\n if (i % 2 == 0) {\n res(i) = l\n l += 1\n res(i + n) = l\n l += 1\n } else {\n res(i) = r\n r -= 1\n res(i + n) = r\n r -= 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n % 2 == 1) {\n println(\"YES\")\n println(res.mkString(\" \"))\n } else println(\"NO\")\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "5e23f02afc7446ecf8688ad2a8fa284d"} {"nl": {"description": "You are given four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$. You should build a sequence $$$a_0, a_1, a_2, \\dots, a_n$$$ where $$$a_0 = 0$$$ and for each $$$i \\ge 1$$$ you can choose: either $$$a_i = a_{i - 1} + x$$$ or $$$a_i = a_{i - 1} - y$$$. Your goal is to build such a sequence $$$a$$$ that $$$a_i \\le B$$$ for all $$$i$$$ and $$$\\sum\\limits_{i=0}^{n}{a_i}$$$ is maximum possible.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$1 \\le B, x, y \\le 10^9$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print one integer\u00a0\u2014 the maximum possible $$$\\sum\\limits_{i=0}^{n}{a_i}$$$.", "sample_inputs": ["3\n5 100 1 30\n7 1000000000 1000000000 1000000000\n4 1 7 3"], "sample_outputs": ["15\n4000000000\n-10"], "notes": "NoteIn the first test case, the optimal sequence $$$a$$$ is $$$[0, 1, 2, 3, 4, 5]$$$.In the second test case, the optimal sequence $$$a$$$ is $$$[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$$$.In the third test case, the optimal sequence $$$a$$$ is $$$[0, -3, -6, 1, -2]$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n\r\n def solve(n: Int, b: Int, x: Int, y: Int) = {\r\n\r\n def recur(i: Int, prev: Long): Long = {\r\n if (i == 0) 0\r\n else {\r\n val curr = if (prev + x > b) prev - y else prev + x\r\n curr + recur(i - 1, curr)\r\n }\r\n }\r\n\r\n recur(n, 0)\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 text = readLine().split(\"\\\\s+\").map(_.toInt)\r\n ) println(solve(text(0), text(1), text(2), text(3)))\r\n\r\n }\r\n\r\n\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "2c921093abf2c5963f5f0e96cd430456"} {"nl": {"description": "You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps: select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$); if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following: select $$$i = 1$$$: we'll get 111010 $$$\\rightarrow$$$ 11010 $$$\\rightarrow$$$ 010; select $$$i = 2$$$: we'll get 111010 $$$\\rightarrow$$$ 11010 $$$\\rightarrow$$$ 010; select $$$i = 3$$$: we'll get 111010 $$$\\rightarrow$$$ 11010 $$$\\rightarrow$$$ 010; select $$$i = 4$$$: we'll get 111010 $$$\\rightarrow$$$ 11110 $$$\\rightarrow$$$ 0; select $$$i = 5$$$: we'll get 111010 $$$\\rightarrow$$$ 11100 $$$\\rightarrow$$$ 00; select $$$i = 6$$$: we'll get 111010 $$$\\rightarrow$$$ 11101 $$$\\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the maximum number of operations you can perform.", "sample_inputs": ["5\n6\n111010\n1\n0\n1\n1\n2\n11\n6\n101010"], "sample_outputs": ["3\n1\n1\n1\n3"], "notes": "NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string."}, "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n var n = nextInt\n val s = nextLine\n var lim = s.length\n var a, b, res = 0\n val deleted = Array.fill(n)(false)\n while (n > 0) {\n while (a < lim - 1 && s(a) != s(a + 1)) {\n a += 1\n }\n n -= 1\n deleted(a) = true\n a += 1\n if (a == lim) {\n lim -= 1\n a -= 2\n }\n// if (a == b) {\n// b += 1\n// }\n// println(a, n, lim)\n if (n > 0) {\n while (b < s.length && deleted(b)) {\n b += 1\n }\n val b0 = b\n while (b <= lim && b < s.length && s(b) == s(b0)) {\n if (!deleted(b)) n -= 1\n b += 1\n }\n// println(b, b0)\n if (a < b) a = b\n }\n// println(a, b, n, lim)\n res += 1\n }\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": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n var n = nextInt\n val s = nextLine\n var lim = s.length\n var a, b, res = 0\n while (n > 0) {\n while (a < lim - 1 && s(a) != s(a + 1)) {\n a += 1\n }\n n -= 1\n if (a == lim - 1) {\n lim -= 1\n a -= 1\n }\n if (a == b) {\n b += 1\n }\n// println(a, n, lim)\n if (n > 0) {\n val b0 = b\n while (b <= lim && b < s.length && s(b) == s(b0)) {\n b += 1\n }\n n -= (b - b0)\n// println(b, b0)\n if (a < b) a = b\n }\n// println(a, b, n, lim)\n res += 1\n }\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": "d0030996e6b29c8580463fae43bb04d4"} {"nl": {"description": "The BFS algorithm is defined as follows. Consider an undirected graph with vertices numbered from $$$1$$$ to $$$n$$$. Initialize $$$q$$$ as a new queue containing only vertex $$$1$$$, mark the vertex $$$1$$$ as used. Extract a vertex $$$v$$$ from the head of the queue $$$q$$$. Print the index of vertex $$$v$$$. Iterate in arbitrary order through all such vertices $$$u$$$ that $$$u$$$ is a neighbor of $$$v$$$ and is not marked yet as used. Mark the vertex $$$u$$$ as used and insert it into the tail of the queue $$$q$$$. If the queue is not empty, continue from step 2. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex $$$1$$$. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) which denotes the number of nodes in the tree. The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x, y \\le n$$$)\u00a0\u2014 the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains $$$n$$$ distinct integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the sequence to check.", "output_spec": "Print \"Yes\" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and \"No\" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n1 2\n1 3\n2 4\n1 2 3 4", "4\n1 2\n1 3\n2 4\n1 2 4 3"], "sample_outputs": ["Yes", "No"], "notes": "NoteBoth sample tests have the same tree in them.In this tree, there are two valid BFS orderings: $$$1, 2, 3, 4$$$, $$$1, 3, 2, 4$$$. The ordering $$$1, 2, 4, 3$$$ doesn't correspond to any valid BFS order."}, "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 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\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"}, {"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}"}], "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "You are given a positive integer $$$x$$$. Find any such $$$2$$$ positive integers $$$a$$$ and $$$b$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$.As a reminder, $$$GCD(a,b)$$$ is the greatest integer that divides both $$$a$$$ and $$$b$$$. Similarly, $$$LCM(a,b)$$$ is the smallest integer such that both $$$a$$$ and $$$b$$$ divide it.It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 100)$$$ \u00a0\u2014 the number of testcases. Each testcase consists of one line containing a single integer, $$$x$$$ $$$(2 \\le x \\le 10^9)$$$.", "output_spec": "For each testcase, output a pair of positive integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9)$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$. It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.", "sample_inputs": ["2\n2\n14"], "sample_outputs": ["1 1\n6 4"], "notes": "NoteIn the first testcase of the sample, $$$GCD(1,1)+LCM(1,1)=1+1=2$$$.In the second testcase of the sample, $$$GCD(6,4)+LCM(6,4)=2+12=14$$$."}, "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 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"}, {"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"} {"nl": {"description": "You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$n - 1 \\le m \\le min(2 \\cdot 10^5, \\frac{n(n-1)}{2})$$$) \u2014 the number of vertices and edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$u_i \\ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i.\u2009e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \\ne u_i$$$ is satisfied.", "output_spec": "Print $$$n-1$$$ lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge $$$(v, u)$$$ is considered the same as the edge $$$(u, v)$$$). If there are multiple possible answers, print any of them.", "sample_inputs": ["5 5\n1 2\n2 3\n3 5\n4 3\n1 5", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "8 9\n1 2\n2 3\n2 5\n1 6\n3 4\n6 5\n4 5\n2 7\n5 8"], "sample_outputs": ["3 5\n2 1\n3 2\n3 4", "4 1\n1 2\n1 3", "3 2\n2 5\n8 5\n6 1\n2 7\n1 2\n3 4"], "notes": "NotePicture corresponding to the first example: In this example the number of edges of spanning tree incident to the vertex $$$3$$$ is $$$3$$$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.Picture corresponding to the second example: In this example the number of edges of spanning tree incident to the vertex $$$1$$$ is $$$3$$$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.Picture corresponding to the third example: In this example the number of edges of spanning tree incident to the vertex $$$2$$$ is $$$4$$$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex $$$5$$$ instead of $$$2$$$."}, "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 (from, to) = na2(M, -1)\n val g = packUGraph(N, from, to)\n val mxV = g.zipWithIndex.maxBy(_._1.length)._2\n\n case class Edge(v: Int, u: Int)\n val ans = new ArrayBuffer[Edge]()\n\n val uf = new UnionFind(N)\n REP(g(mxV).length) { i =>\n val u = g(mxV)(i)\n uf.unite(mxV, u)\n ans += Edge(mxV, u)\n }\n\n REP(M) { i =>\n if (uf.find(from(i)) != uf.find(to(i))) {\n uf.unite(from(i), to(i))\n ans += Edge(from(i), to(i))\n }\n }\n\n REP(N - 1) { i =>\n val e = ans(i)\n out.println(s\"${e.v+1} ${e.u+1}\")\n }\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 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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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 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": "fd593d74545da6d133708d58bdde2197"} {"nl": {"description": "Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to n and the number of a hill is equal to the distance in meters between it and the island. The distance between the n-th hill and the shore is also 1 meter.Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is d, the frog will jump from the island on the hill d, then \u2014 on the hill 2d, then 3d and so on until they get to the shore (i.e. find itself beyond the hill n).However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.", "input_spec": "The first line contains three integers n, m and k (1\u2009\u2264\u2009n\u2009\u2264\u2009109, 1\u2009\u2264\u2009m,\u2009k\u2009\u2264\u2009100) \u2014 the number of hills, frogs and mosquitoes respectively. The second line contains m integers di (1\u2009\u2264\u2009di\u2009\u2264\u2009109) \u2014 the lengths of the frogs\u2019 jumps. The third line contains k integers \u2014 the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.", "output_spec": "In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line \u2014 their numbers in increasing order separated by spaces. The frogs are numbered from 1 to m in the order of the jump length given in the input data.", "sample_inputs": ["5 3 5\n2 3 4\n1 2 3 4 5", "1000000000 2 3\n2 5\n999999995 999999998 999999996"], "sample_outputs": ["2\n2 3", "1\n2"], "notes": null}, "positive_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 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"}, {"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"} {"nl": {"description": "There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.", "input_spec": "The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout. The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout. The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.", "output_spec": "Print the text if the same keys were pressed in the second layout.", "sample_inputs": ["qwertyuiopasdfghjklzxcvbnm\nveamhjsgqocnrbfxdtwkylupzi\nTwccpQZAvb2017", "mnbvcxzlkjhgfdsapoiuytrewq\nasdfghjklqwertyuiopzxcvbnm\n7abaCABAABAcaba7"], "sample_outputs": ["HelloVKCup2017", "7uduGUDUUDUgudu7"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. \"It would look much better when I'll swap some of them!\"\u00a0\u2014 thought the girl\u00a0\u2014 \"but how to do it?\". After a while, she got an idea. IA will look at all prefixes with lengths from $$$1$$$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.", "input_spec": "The first and the only line contains a string $$$s$$$ ($$$1 \\le |s| \\le 1000$$$), describing the initial string formed by magnets. The string $$$s$$$ consists only of characters 'a' and 'b'.", "output_spec": "Output exactly $$$|s|$$$ integers. If IA should reverse the $$$i$$$-th prefix (that is, the substring from $$$1$$$ to $$$i$$$), the $$$i$$$-th integer should be equal to $$$1$$$, and it should be equal to $$$0$$$ otherwise. If there are multiple possible sequences leading to the optimal answer, print any of them.", "sample_inputs": ["bbab", "aaaaa"], "sample_outputs": ["0 1 1 0", "1 0 0 0 1"], "notes": "NoteIn the first example, IA can reverse the second and the third prefix and get a string \"abbb\". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.In the second example, she can reverse any subset of prefixes\u00a0\u2014 all letters are 'a'."}, "positive_code": [{"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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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: \u5de6\u5bc4\u305b, 1: \u53f3\u5bc4\u305b\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"} {"nl": {"description": "Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days\u00a0\u2014 the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint\u00a0\u2014 one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.", "input_spec": "The first line of input contains three integers n, m and k (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 0\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of socks, the number of days and the number of available colors respectively. The second line contain n integers c1, c2, ..., cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009k)\u00a0\u2014 current colors of Arseniy's socks. Each of the following m lines contains two integers li and ri (1\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u2009n, li\u2009\u2260\u2009ri)\u00a0\u2014 indices of socks which Arseniy should wear during the i-th day.", "output_spec": "Print one integer\u00a0\u2014 the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.", "sample_inputs": ["3 2 3\n1 2 3\n1 2\n2 3", "3 2 2\n1 1 2\n1 2\n2 1"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors."}, "positive_code": [{"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 colors = in.next().split(' ').map(_.toInt)\n val socks = Array.range(0, n)\n val size = Array.fill(n){1}\n\n def parent(i: Int): Int = {\n if (socks(i) == i)\n i\n else\n parent(socks(i))\n }\n\n (1 to m).foreach { _ =>\n val Array(f, s) = in.next().split(' ').map(_.toInt - 1)\n val fParent = parent(f)\n val sParent = parent(s)\n if (fParent != sParent) {\n if (size(fParent) > size(sParent)) {\n size(fParent) += size(sParent)\n size(sParent) = 0\n socks(sParent) = fParent\n } else {\n size(sParent) += size(fParent)\n size(fParent) = 0\n socks(fParent) = sParent\n }\n }\n }\n\n val res = socks.indices.map{i => (parent(i), colors(i))}.groupBy(_._1).filter(_._2.length > 1).map(i => i._2.length - i._2.groupBy(_._2).map(_._2.length).max)\n println(res.sum)\n\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, k) = in.next().split(' ').map(_.toInt)\n val colors = in.next().split(' ').map(_.toInt)\n val socks = Array.range(0, n)\n val size = Array.fill(n){1}\n\n def parent(i: Int): Int = {\n if (socks(i) == i)\n i\n else\n parent(socks(i))\n }\n\n (1 to m).foreach { _ =>\n val Array(f, s) = in.next().split(' ').map(_.toInt - 1)\n val fParent = parent(f)\n val sParent = parent(s)\n if (fParent != sParent) {\n if (size(fParent) > size(sParent)) {\n size(fParent) += size(sParent)\n size(sParent) = 0\n socks(sParent) = fParent\n } else {\n size(sParent) += size(fParent)\n size(fParent) = 0\n socks(fParent) = sParent\n }\n }\n }\n\n val res = socks.indices.map{i => (parent(i), colors(i))}.groupBy(_._1).filter(_._2.length > 1).map(i => i._2.length - i._2.groupBy(_._2).head._2.length)\n println(res.sum)\n\n\n\n}\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 colors = in.next().split(' ').map(_.toInt)\n val socks = Array.range(0, n)\n val size = Array.fill(n){1}\n\n def parent(i: Int): Int = {\n if (socks(i) == i)\n i\n else\n parent(socks(i))\n }\n\n (1 to m).foreach { _ =>\n val Array(f, s) = in.next().split(' ').map(_.toInt - 1)\n val fParent = parent(f)\n val sParent = parent(s)\n if (fParent != sParent) {\n if (size(fParent) > size(sParent)) {\n size(fParent) += size(sParent)\n size(sParent) = 0\n socks(sParent) = fParent\n } else {\n size(sParent) += size(fParent)\n size(fParent) = 0\n socks(fParent) = sParent\n }\n }\n }\n\n val res = socks.indices.map{i => (parent(i), colors(i))}.groupBy(_._1).map(i => i._2.length - i._2.groupBy(_._2).head._2.length)\n println(res.sum)\n\n\n\n}\n\n\n"}], "src_uid": "39232c03c033da238c5d1e20e9595d6d"} {"nl": {"description": "Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m\u2009\u2264\u20094n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m\u2009>\u20092n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. The seating for n\u2009=\u20099 and m\u2009=\u200936. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.", "input_spec": "The only line contains two integers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009m\u2009\u2264\u20094n) \u2014 the number of pairs of rows and the number of passengers.", "output_spec": "Print m distinct integers from 1 to m \u2014 the order in which the passengers will get off the bus.", "sample_inputs": ["2 7", "9 36"], "sample_outputs": ["5 1 6 2 7 3 4", "19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18"], "notes": null}, "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 println((1 to n).foldLeft(List.empty[List[Int]]) {\n case (acc, i) =>\n val shift = (i - 1) * 2\n List(2 * n + 1 + shift, 1 + shift, 2 * n + 2 + shift, 2 + shift).filter(_ <= m) :: acc\n }.reverse.flatten.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "0a701242ca81029a1791df74dc8ca59b"} {"nl": {"description": "This is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are $$$666$$$ black rooks and $$$1$$$ white king on the chess board of size $$$999 \\times 999$$$. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square $$$(x, y)$$$, it can move to the square $$$(nx, ny)$$$ if and only $$$\\max (|nx - x|, |ny - y|) = 1$$$ , $$$1 \\leq nx, ny \\leq 999$$$. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes $$$2000$$$ turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.", "input_spec": "In the beginning your program will receive $$$667$$$ lines from input. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\leq x, y \\leq 999$$$) \u2014 the piece's coordinates. The first line contains the coordinates of the king and the next $$$666$$$ contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.", "output_spec": "After getting king checked, you program should terminate immediately without printing anything extra.", "sample_inputs": ["999 999\n1 1\n1 2\n2 1\n2 2\n1 3\n2 3\n<...>\n26 13\n26 14\n26 15\n26 16\n\n1 700 800\n\n2 1 2\n\n<...>\n\n-1 -1 -1"], "sample_outputs": ["999 998\n\n999 997\n\n<...>\n\n999 26"], "notes": "NoteThe example is trimmed. The full initial positions of the rooks in the first test are available at https://pastebin.com/qQCTXgKP. It is not guaranteed that they will behave as in the example."}, "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 MID = 500\n var curX, curY = ni()\n var lb, rb, lt, rt = 0\n val Rx, Ry = Array.ofDim[Int](666) // \u30eb\u30fc\u30af\u306eID\u306f0-index\u3002\u5834\u6240\u306f1-index\n REP(666) { i =>\n val x, y = ni()\n Rx(i) = x\n Ry(i) = y\n inc(i)\n }\n\n def inc(k: Int): Unit = {\n if (Rx(k) > MID && Ry(k) > MID) rt += 1\n if (Rx(k) > MID && Ry(k) < MID) rb += 1\n if (Rx(k) < MID && Ry(k) > MID) lt += 1\n if (Rx(k) < MID && Ry(k) < MID) lb += 1\n }\n\n def dec(k: Int): Unit = {\n if (Rx(k) > MID && Ry(k) > MID) rt -= 1\n if (Rx(k) > MID && Ry(k) < MID) rb -= 1\n if (Rx(k) < MID && Ry(k) > MID) lt -= 1\n if (Rx(k) < MID && Ry(k) < MID) lb -= 1\n }\n\n sealed trait Result\n case object Continue extends Result\n case object Error extends Result\n case object Success extends Result\n\n def readAnswer(): Result = {\n val k, x, y = ni()\n if (k == 0 && x == 0 && y == 0) {\n return Error\n } else if (k == -1 && x == -1 && y == -1) {\n return Success\n }\n\n val i = k - 1\n dec(i)\n Rx(i) = x\n Ry(i) = y\n inc(i)\n\n Continue\n }\n\n def exists(x: Int, y: Int) = {\n 0 until 666 exists { i =>\n Rx(i) == x && Ry(i) == y\n }\n }\n\n def moveTo(x: Int, y: Int): Result = {\n while(x != curX || y != curY) {\n val nextX = curX + Integer.signum(x - curX)\n val nextY = curY + Integer.signum(y - curY)\n val eat = exists(nextX, nextY)\n curX += Integer.signum(x - curX)\n if (!eat) curY += Integer.signum(y - curY) // \u98df\u3079\u3061\u3083\u3046\u306e\u306f\u659c\u3081\u79fb\u52d5\u3060\u3051\u306a\u306e\u3067\u3001x, y\u3069\u3061\u3089\u304b\u306e\u79fb\u52d5\u3092\u3084\u3081\u308c\u3070\u30c1\u30a7\u30c3\u30af\u3059\u308b\u306f\u305a\n out.println(s\"$curX $curY\")\n out.flush()\n\n readAnswer() match {\n case Error => return Error\n case Success => return Success\n case Continue =>\n }\n }\n\n Continue\n }\n\n moveTo(MID, MID) match {\n case Success =>\n case Error =>\n case Continue =>\n val ms = min(min(lt, lb), min(rt, rb))\n\n val (distX, distY) =\n if (ms == lb) (999, 999)\n else if (ms == rb) (1, 999)\n else if (ms == lt) (999, 1)\n else (1, 1)\n\n moveTo(distX, distY) match {\n case Continue =>\n // \u5931\u6557\n throw new IllegalStateException(s\"$distX $distY\")\n\n case _ =>\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}"}], "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 MID = 500\n var curX, curY = ni()\n var r, up = 0\n val Rx, Ry = Array.ofDim[Int](666) // \u30eb\u30fc\u30af\u306eID\u306f0-index\u3002\u5834\u6240\u306f1-index\n REP(666) { i =>\n val x, y = ni()\n Rx(i) = x\n Ry(i) = y\n inc(i)\n }\n\n def inc(k: Int): Unit = {\n if (Rx(k) > MID) r += 1\n if (Ry(k) > MID) up += 1\n }\n\n def dec(k: Int): Unit = {\n if (Rx(k) > MID) r -= 1\n if (Ry(k) > MID) up -= 1\n }\n\n sealed trait Result\n case object Continue extends Result\n case object Error extends Result\n case object Success extends Result\n\n def readAnswer(): Result = {\n val k, x, y = ni()\n if (k == 0 && x == 0 && y == 0) {\n return Error\n } else if (k == -1 && x == -1 && y == -1) {\n return Success\n }\n\n val i = k - 1\n dec(i)\n Rx(i) = x\n Ry(i) = y\n inc(i)\n\n Continue\n }\n\n def exists(x: Int, y: Int) = {\n 0 until 666 exists { i =>\n Rx(i) == x && Ry(i) == y\n }\n }\n\n def moveTo(x: Int, y: Int): Result = {\n while(x != curX || y != curY) {\n val nextX = curX + Integer.signum(x - curX)\n val nextY = curY + Integer.signum(y - curY)\n val eat = exists(nextX, nextY)\n curX += Integer.signum(x - curX)\n if (!eat) curY += Integer.signum(y - curY) // \u98df\u3079\u3061\u3083\u3046\u306e\u306f\u659c\u3081\u79fb\u52d5\u3060\u3051\u306a\u306e\u3067\u3001x, y\u3069\u3061\u3089\u304b\u306e\u79fb\u52d5\u3092\u3084\u3081\u308c\u3070\u30c1\u30a7\u30c3\u30af\u3059\u308b\u306f\u305a\n out.println(s\"$curX $curY\")\n out.flush()\n\n readAnswer() match {\n case Error => return Error\n case Success => return Success\n case Continue =>\n }\n }\n\n Continue\n }\n\n moveTo(MID, MID) match {\n case Success =>\n case Error =>\n case Continue =>\n val distX = if (r < 333) 1 else 999\n val distY = if (up < 333) 1 else 999\n moveTo(distX, distY) match {\n case Continue =>\n throw new IllegalStateException(\"Fail to achieve\")\n\n case _ =>\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": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 curX, curY = ni()\n var l, r, up, down = 0\n val Rx, Ry = Array.ofDim[Int](666) // \u30eb\u30fc\u30af\u306eID\u306f0-index\u3002\u5834\u6240\u306f1-index\n REP(666) { i =>\n val x, y = ni()\n Rx(i) = x\n Ry(i) = y\n if (x > 455) r += 1\n if (x < 455) l += 1\n if (y > 455) up += 1\n if (y < 455) down += 1\n }\n\n def inc(k: Int): Unit = {\n if (Rx(k) > 455) r += 1\n if (Rx(k) < 455) l += 1\n if (Ry(k) > 455) up += 1\n if (Ry(k) < 455) down += 1\n }\n\n def dec(k: Int): Unit = {\n if (Rx(k) > 455) r -= 1\n if (Rx(k) < 455) l -= 1\n if (Ry(k) > 455) up -= 1\n if (Ry(k) < 455) down -= 1\n }\n\n def readAnswer(): Unit = {\n val k, x, y = ni()\n if (k == 0 && x == 0 && y == 0) {\n throw new IllegalArgumentException(\"Wrong Answer\")\n } else if (k == -1 && x == -1 && y == -1) {\n return\n }\n\n val i = k - 1\n dec(i)\n Rx(i) = x\n Ry(i) = y\n inc(i)\n }\n\n def moveTo(x: Int, y: Int): Unit = {\n while(x != curX || y != curY) {\n curX += Integer.signum(x - curX)\n curY += Integer.signum(y - curY)\n out.println(s\"$curX $curY\")\n out.flush()\n\n readAnswer()\n }\n }\n\n moveTo(455, 455)\n val distX = if (l > r) 0 else 999\n val distY = if (down > up) 0 else 999\n moveTo(distX, distY)\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 MID = 500\n var curX, curY = ni()\n var r, up = 0\n val Rx, Ry = Array.ofDim[Int](666) // \u30eb\u30fc\u30af\u306eID\u306f0-index\u3002\u5834\u6240\u306f1-index\n REP(666) { i =>\n val x, y = ni()\n Rx(i) = x\n Ry(i) = y\n inc(i)\n }\n\n def inc(k: Int): Unit = {\n if (Rx(k) > MID) r += 1\n if (Ry(k) > MID) up += 1\n }\n\n def dec(k: Int): Unit = {\n if (Rx(k) > MID) r -= 1\n if (Ry(k) > MID) up -= 1\n }\n\n sealed trait Result\n case object Continue extends Result\n case object Error extends Result\n case object Success extends Result\n\n def readAnswer(): Result = {\n val k, x, y = ni()\n if (k == 0 && x == 0 && y == 0) {\n return Error\n } else if (k == -1 && x == -1 && y == -1) {\n return Success\n }\n\n val i = k - 1\n dec(i)\n Rx(i) = x\n Ry(i) = y\n inc(i)\n\n Continue\n }\n\n def exists(x: Int, y: Int) = {\n 0 until 666 exists { i =>\n Rx(i) == x && Ry(i) == y\n }\n }\n\n def moveTo(x: Int, y: Int): Result = {\n while(x != curX || y != curY) {\n val nextX = curX + Integer.signum(x - curX)\n val nextY = curY + Integer.signum(y - curY)\n val eat = exists(nextX, nextY)\n curX += Integer.signum(x - curX)\n if (!eat) curY += Integer.signum(y - curY) // \u98df\u3079\u3061\u3083\u3046\u306e\u306f\u659c\u3081\u79fb\u52d5\u3060\u3051\u306a\u306e\u3067\u3001x, y\u3069\u3061\u3089\u304b\u306e\u79fb\u52d5\u3092\u3084\u3081\u308c\u3070\u30c1\u30a7\u30c3\u30af\u3059\u308b\u306f\u305a\n out.println(s\"$curX $curY\")\n out.flush()\n\n readAnswer() match {\n case Error => return Error\n case Success => return Success\n case Continue =>\n }\n }\n\n Continue\n }\n\n moveTo(MID, MID) match {\n case Success =>\n case Error =>\n case Continue =>\n val distX = if (r < 333) 1 else 999\n val distY = if (up < 333) 1 else 999\n moveTo(distX, distY) match {\n case Continue =>\n // \u5931\u6557\n out.println(s\"$r $up, $distX $distY\")\n out.flush()\n\n case _ =>\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": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 MID = 500\n var curX, curY = ni()\n var r, up = 0\n val Rx, Ry = Array.ofDim[Int](666) // \u30eb\u30fc\u30af\u306eID\u306f0-index\u3002\u5834\u6240\u306f1-index\n REP(666) { i =>\n val x, y = ni()\n Rx(i) = x\n Ry(i) = y\n inc(i)\n }\n\n def inc(k: Int): Unit = {\n if (Rx(k) > MID) r += 1\n if (Ry(k) > MID) up += 1\n }\n\n def dec(k: Int): Unit = {\n if (Rx(k) > MID) r -= 1\n if (Ry(k) > MID) up -= 1\n }\n\n sealed trait Result\n case object Continue extends Result\n case object Error extends Result\n case object Success extends Result\n\n def readAnswer(): Result = {\n val k, x, y = ni()\n if (k == 0 && x == 0 && y == 0) {\n return Error\n } else if (k == -1 && x == -1 && y == -1) {\n return Success\n }\n\n val i = k - 1\n dec(i)\n Rx(i) = x\n Ry(i) = y\n inc(i)\n\n Continue\n }\n\n def exists(x: Int, y: Int) = {\n 0 until 666 exists { i =>\n Rx(i) == x && Ry(i) == y\n }\n }\n\n def moveTo(x: Int, y: Int): Result = {\n while(x != curX || y != curY) {\n val nextX = curX + Integer.signum(x - curX)\n val nextY = curY + Integer.signum(y - curY)\n val eat = exists(nextX, nextY)\n curX += Integer.signum(x - curX)\n if (!eat) curY += Integer.signum(y - curY) // \u98df\u3079\u3061\u3083\u3046\u306e\u306f\u659c\u3081\u79fb\u52d5\u3060\u3051\u306a\u306e\u3067\u3001x, y\u3069\u3061\u3089\u304b\u306e\u79fb\u52d5\u3092\u3084\u3081\u308c\u3070\u30c1\u30a7\u30c3\u30af\u3059\u308b\u306f\u305a\n out.println(s\"$curX $curY\")\n out.flush()\n\n readAnswer() match {\n case Error => return Error\n case Success => return Success\n case Continue =>\n }\n }\n\n Continue\n }\n\n moveTo(MID, MID) match {\n case Success =>\n case Error =>\n case Continue =>\n val distX = if (r < 333) 1 else 999\n val distY = if (up < 333) 1 else 999\n System.err.println(s\"r: $r up: $up\")\n System.err.println(s\"move to $distX $distY\")\n moveTo(distX, distY) match {\n case Continue =>\n System.err.println(s\"Fail to achieve\")\n throw new IllegalStateException(\"Fail to achieve\")\n\n case _ =>\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}"}], "src_uid": "3d38584c3bb29e6f84546643b1be8026"} {"nl": {"description": "Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him \u2014 his keyboard will consist of only one row, where all $$$26$$$ lowercase Latin letters will be arranged in some order.Polycarp uses the same password $$$s$$$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $$$s$$$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $$$s$$$, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of test cases. Then $$$T$$$ lines follow, each containing one string $$$s$$$ ($$$1 \\le |s| \\le 200$$$) representing the test case. $$$s$$$ consists of lowercase Latin letters only. There are no two adjacent equal characters in $$$s$$$.", "output_spec": "For each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of $$$26$$$ lowercase Latin letters \u2014 the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ", "sample_inputs": ["5\nababa\ncodedoca\nabcda\nzxzytyz\nabcdefghijklmnopqrstuvwxyza"], "sample_outputs": ["YES\nbacdefghijklmnopqrstuvwxyz\nYES\nedocabfghijklmnpqrstuvwxyz\nNO\nYES\nxzytabcdefghijklmnopqrsuvw\nNO"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009bi,\u20091\u2009\u2264\u2009ci\u2009\u2264\u2009100) \u2014 road is directed from city ai to city bi, redirecting the traffic costs ci.", "output_spec": "Output single integer \u2014 the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.", "sample_inputs": ["3\n1 3 1\n1 2 1\n3 2 1", "3\n1 3 1\n1 2 5\n3 2 1", "6\n1 5 4\n5 3 8\n2 4 15\n1 6 16\n2 3 23\n4 6 42", "4\n1 2 9\n2 3 8\n3 4 7\n4 1 5"], "sample_outputs": ["1", "2", "39", "0"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n val edge = Array.fill[List[(Int, Int)]](n)(Nil)\n\n in.take(n).map(_.split(' ').map(_.toInt)).foreach {\n case Array(a, b, c) =>\n edge(a - 1) ::= (b - 1, 0)\n edge(b - 1) ::= (a - 1, c)\n }\n\n def count(index: Int) = {\n val visited = Array.ofDim[Boolean](n)\n val next = edge(0)(index)\n visited(0) = true\n\n val (res, i) = (1 until n - 1).foldLeft(next._2, next._1) {\n case ((sum, i), _) =>\n visited(i) = true\n val candidate = edge(i).find(e => !visited(e._1)).get\n (candidate._2 + sum, candidate._1)\n }\n res + edge(i).find(e => e._1 == 0).get._2\n }\n\n println(Math.min(count(0), count(1)))\n}"}], "negative_code": [], "src_uid": "d85c7a8f7e6f5fc6dffed554bffef3ec"} {"nl": {"description": "You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string \"aba,123;1a;0\": \"aba\", \"123\", \"1a\", \"0\". A word can be empty: for example, the string s=\";;\" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings \"101\", \"0\" are INTEGER numbers, but \"01\" and \"1.0\" are not.For example, for the string aba,123;1a;0 the string a would be equal to \"123,0\" and string b would be equal to \"aba,1a\".", "input_spec": "The only line of input contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.", "output_spec": "Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.", "sample_inputs": ["aba,123;1a;0", "1;;01,a0,", "1", "a"], "sample_outputs": ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""], "notes": "NoteIn the second example the string s contains five words: \"1\", \"\", \"01\", \"a0\", \"\"."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a integer $$$n$$$ ($$$n > 0$$$). Find any integer $$$s$$$ which satisfies these conditions, or report that there are no such numbers:In the decimal representation of $$$s$$$: $$$s > 0$$$, $$$s$$$ consists of $$$n$$$ digits, no digit in $$$s$$$ equals $$$0$$$, $$$s$$$ is not divisible by any of it's digits. ", "input_spec": "The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 400$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case contains one positive integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print an integer $$$s$$$ which satisfies the conditions described above, or \"-1\" (without quotes), if no such number exists. If there are multiple possible solutions for $$$s$$$, print any solution.", "sample_inputs": ["4\n1\n2\n3\n4"], "sample_outputs": ["-1\n57\n239\n6789"], "notes": "NoteIn the first test case, there are no possible solutions for $$$s$$$ consisting of one digit, because any such solution is divisible by itself.For the second test case, the possible solutions are: $$$23$$$, $$$27$$$, $$$29$$$, $$$34$$$, $$$37$$$, $$$38$$$, $$$43$$$, $$$46$$$, $$$47$$$, $$$49$$$, $$$53$$$, $$$54$$$, $$$56$$$, $$$57$$$, $$$58$$$, $$$59$$$, $$$67$$$, $$$68$$$, $$$69$$$, $$$73$$$, $$$74$$$, $$$76$$$, $$$78$$$, $$$79$$$, $$$83$$$, $$$86$$$, $$$87$$$, $$$89$$$, $$$94$$$, $$$97$$$, and $$$98$$$.For the third test case, one possible solution is $$$239$$$ because $$$239$$$ is not divisible by $$$2$$$, $$$3$$$ or $$$9$$$ and has three digits (none of which equals zero)."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $$$n$$$ rows and $$$n$$$ columns of square cells. The rows are numbered from $$$1$$$ to $$$n$$$, from top to bottom, and the columns are numbered from $$$1$$$ to $$$n$$$, from left to right. The position of a cell at row $$$r$$$ and column $$$c$$$ is represented as $$$(r, c)$$$. There are only two colors for the cells in cfpaint \u2014 black and white.There is a tool named eraser in cfpaint. The eraser has an integer size $$$k$$$ ($$$1 \\le k \\le n$$$). To use the eraser, Gildong needs to click on a cell $$$(i, j)$$$ where $$$1 \\le i, j \\le n - k + 1$$$. When a cell $$$(i, j)$$$ is clicked, all of the cells $$$(i', j')$$$ where $$$i \\le i' \\le i + k - 1$$$ and $$$j \\le j' \\le j + k - 1$$$ become white. In other words, a square with side equal to $$$k$$$ cells and top left corner at $$$(i, j)$$$ is colored white.A white line is a row or a column without any black cells.Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2000$$$) \u2014 the number of rows and columns, and the size of the eraser. The next $$$n$$$ lines contain $$$n$$$ characters each without spaces. The $$$j$$$-th character in the $$$i$$$-th line represents the cell at $$$(i,j)$$$. Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.", "output_spec": "Print one integer: the maximum number of white lines after using the eraser exactly once.", "sample_inputs": ["4 2\nBWWW\nWBBW\nWBBW\nWWWB", "3 1\nBWB\nWWB\nBWB", "5 3\nBWBBB\nBWBBB\nBBBBB\nBBBBB\nWBBBW", "2 2\nBW\nWB", "2 1\nWW\nWW"], "sample_outputs": ["4", "2", "2", "4", "4"], "notes": "NoteIn the first example, Gildong can click the cell $$$(2, 2)$$$, then the working screen becomes: BWWWWWWWWWWWWWWBThen there are four white lines \u2014 the $$$2$$$-nd and $$$3$$$-rd row, and the $$$2$$$-nd and $$$3$$$-rd column.In the second example, clicking the cell $$$(2, 3)$$$ makes the $$$2$$$-nd row a white line.In the third example, both the $$$2$$$-nd column and $$$5$$$-th row become white lines by clicking the cell $$$(3, 2)$$$."}, "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\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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Ringo found a string $$$s$$$ of length $$$n$$$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $$$s$$$ into a palindrome by applying two types of operations to the string. The first operation allows him to choose $$$i$$$ ($$$2 \\le i \\le n-1$$$) and to append the substring $$$s_2s_3 \\ldots s_i$$$ ($$$i - 1$$$ characters) reversed to the front of $$$s$$$.The second operation allows him to choose $$$i$$$ ($$$2 \\le i \\le n-1$$$) and to append the substring $$$s_i s_{i + 1}\\ldots s_{n - 1}$$$ ($$$n - i$$$ characters) reversed to the end of $$$s$$$.Note that characters in the string in this problem are indexed from $$$1$$$.For example suppose $$$s=$$$abcdef. If he performs the first operation with $$$i=3$$$ then he appends cb to the front of $$$s$$$ and the result will be cbabcdef. Performing the second operation on the resulted string with $$$i=5$$$ will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $$$30$$$ times. The length of the resulting palindrome must not exceed $$$10^6$$$It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.", "input_spec": "The only line contains the string $$$S$$$ ($$$3 \\le |s| \\le 10^5$$$) of lowercase letters from the English alphabet.", "output_spec": "The first line should contain $$$k$$$ ($$$0\\le k \\le 30$$$) \u00a0\u2014 the number of operations performed. Each of the following $$$k$$$ lines should describe an operation in form L i or R i. $$$L$$$ represents the first operation, $$$R$$$ represents the second operation, $$$i$$$ represents the index chosen. The length of the resulting palindrome must not exceed $$$10^6$$$.", "sample_inputs": ["abac", "acccc", "hannah"], "sample_outputs": ["2\nR 2\nR 5", "2\nL 4\nL 2", "0"], "notes": "NoteFor the first example the following operations are performed:abac $$$\\to$$$ abacab $$$\\to$$$ abacabaThe second sample performs the following operations: acccc $$$\\to$$$ cccacccc $$$\\to$$$ ccccaccccThe third example is already a palindrome so no operations are required."}, "positive_code": [{"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 var t=1\n while(t>0)\n {\n var str:String=StdIn.readLine()\n var n:Int=str.length\n ans.append(\"4\\n\")\n ans.append(\"L 2\\n\")\n n+=1\n\n ans.append(\"R 3\\n\")\n n+=n-3\n\n ans.append(\"R 2\\n\")\n n+=n-2\n\n ans.append(\"R \").append(n-1).append(\"\\n\")\n\n t-=1;\n }\n println(ans.toString());\n\n\n }\n}\n"}], "negative_code": [], "src_uid": "6ca35987757bf64860eb08f98a9e6d90"} {"nl": {"description": "You are given two integers $$$l$$$ and $$$r$$$, $$$l\\le r$$$. Find the largest possible value of $$$a \\bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\\ge a \\ge b \\ge l$$$.As a reminder, $$$a \\bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \\bmod 8 = 2$$$.", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\\le t\\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\\le l \\le r \\le 10^9$$$).", "output_spec": "For every test case, output the largest possible value of $$$a \\bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\\ge a \\ge b \\ge l$$$.", "sample_inputs": ["4\n1 1\n999999999 1000000000\n8 26\n1 999999999"], "sample_outputs": ["0\n1\n12\n499999999"], "notes": "NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \\bmod b = 1 \\bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \\bmod b = 1$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1,\u2009a2,\u2009...,\u2009ak the element ai is a record if for every integer j (1\u2009\u2264\u2009j\u2009<\u2009i) the following holds: aj\u2009<\u2009ai. ", "input_spec": "The first line contains the only integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the length of the permutation. The second line contains n integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n)\u00a0\u2014 the permutation. All the integers are distinct.", "output_spec": "Print the only integer\u00a0\u2014 the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.", "sample_inputs": ["1\n1", "5\n5 1 2 3 4"], "sample_outputs": ["1", "5"], "notes": "NoteIn the first example the only element can be removed."}, "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": "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"}, {"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"} {"nl": {"description": "You have a string $$$s_1 s_2 \\ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \\le k \\le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \\ldots s_k s_k s_{k - 1} \\ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. ", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10\\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the lexicographically smallest string you can see.", "sample_inputs": ["4\n10\ncodeforces\n9\ncbacbacba\n3\naaa\n4\nbbaa"], "sample_outputs": ["cc\ncbaabc\naa\nbb"], "notes": "NoteIn the first test case choose $$$k = 1$$$ to obtain \"cc\".In the second test case choose $$$k = 3$$$ to obtain \"cbaabc\".In the third test case choose $$$k = 1$$$ to obtain \"aa\".In the fourth test case choose $$$k = 1$$$ to obtain \"bb\"."}, "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 = nextInt\n val s = nextLine\n var i = 1\n\n while (i < n && (s(i) < s(i - 1) || (s(i) == s(i - 1) && s(i) != s(0)))) {\n i += 1\n }\n\n val res = s.take(i) ++ s.take(i).reverse\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": "object B {\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 var i = 1\n\n while (i < n && s(i) < s(i - 1)) {\n i += 1\n }\n\n val res = s.take(i) ++ s.take(i).reverse\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": "dd7faacff9f57635f8e00c2f8f5a4650"} {"nl": {"description": "You are given a cube of size k\u2009\u00d7\u2009k\u2009\u00d7\u2009k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face.Your task is to paint each of k3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied: each white cube has exactly 2 neighbouring cubes of white color; each black cube has exactly 2 neighbouring cubes of black color. ", "input_spec": "The first line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009100), which is size of the cube.", "output_spec": "Print -1 if there is no solution. Otherwise, print the required painting of the cube consequently by layers. Print a k\u2009\u00d7\u2009k matrix in the first k lines, showing how the first layer of the cube should be painted. In the following k lines print a k\u2009\u00d7\u2009k matrix \u2014 the way the second layer should be painted. And so on to the last k-th layer. Note that orientation of the cube in the space does not matter. Mark a white unit cube with symbol \"w\" and a black one with \"b\". Use the format of output data, given in the test samples. You may print extra empty lines, they will be ignored.", "sample_inputs": ["1", "2"], "sample_outputs": ["-1", "bb\nww\n\nbb\nww"], "notes": null}, "positive_code": [{"source_code": "object A extends App {\n\n def solve(n: Int): Int = {\n\n n\n } \n\n def readString = Console.readLine\n\n val n = readString.toInt\n\n if (n % 2 == 0) {\n for (i <- 0 until n) {\n val ii = (i / 2) % 2\n for (j <- 0 until n) {\n val b1 = (j / 2) % 2 == ii\n println((0 until n).map(k => if ((k % 2 == 0) == b1) 'b' else 'w').mkString) \n }\n println\n }\n } else println(-1)\n}"}], "negative_code": [{"source_code": "object A extends App {\n\n def solve(n: Int): Int = {\n\n n\n } \n\n def readString = Console.readLine\n\n val k = readString.toInt\n\n if (k == 2) {\n println(\"bb\") \n println(\"ww\") \n println(\"\") \n println(\"bb\") \n println(\"ww\") \n } else println(-1)\n}"}, {"source_code": "object A extends App {\n\n def solve(n: Int): Int = {\n\n n\n } \n\n def readString = Console.readLine\n def readInts = readString.split(\" \").map(_.toInt)\n\n val n = readString.toInt\n\n println(solve(n)) \n}"}], "src_uid": "1e8040308997b9497a2c295591992b66"} {"nl": {"description": "Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x,\u2009y), he can move to (or attack) positions (x\u2009+\u20091,\u2009y), (x\u20131,\u2009y), (x,\u2009y\u2009+\u20091) and (x,\u2009y\u20131).Iahub wants to know how many Coders can be placed on an n\u2009\u00d7\u2009n chessboard, so that no Coder attacks any other Coder.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000).", "output_spec": "On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.", "sample_inputs": ["2"], "sample_outputs": ["2\nC.\n.C"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "This is an interactive problem!Ehab plays a game with Laggy. Ehab has 2 hidden integers $$$(a,b)$$$. Laggy can ask a pair of integers $$$(c,d)$$$ and Ehab will reply with: 1 if $$$a \\oplus c>b \\oplus d$$$. 0 if $$$a \\oplus c=b \\oplus d$$$. -1 if $$$a \\oplus c<b \\oplus d$$$. Operation $$$a \\oplus b$$$ is the bitwise-xor operation of two numbers $$$a$$$ and $$$b$$$.Laggy should guess $$$(a,b)$$$ with at most 62 questions. You'll play this game. You're Laggy and the interactor is Ehab.It's guaranteed that $$$0 \\le a,b<2^{30}$$$.", "input_spec": "See the interaction section.", "output_spec": "To print the answer, print \"! a b\" (without quotes). Don't forget to flush the output after printing the answer.", "sample_inputs": ["1\n-1\n0"], "sample_outputs": ["? 2 1\n? 1 2\n? 2 0\n! 3 1"], "notes": "NoteIn the sample:The hidden numbers are $$$a=3$$$ and $$$b=1$$$.In the first query: $$$3 \\oplus 2 = 1$$$ and $$$1 \\oplus 1 = 0$$$, so the answer is 1.In the second query: $$$3 \\oplus 1 = 2$$$ and $$$1 \\oplus 2 = 3$$$, so the answer is -1.In the third query: $$$3 \\oplus 2 = 1$$$ and $$$1 \\oplus 0 = 1$$$, so the answer is 0.Then, we printed the answer."}, "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 = 0\n\n def query(k: Int, c: Int, d: Int): Int = {\n out.println(s\"? ${a | (c << k)} ${b | (d << k)}\")\n out.flush()\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n val ans00 = Array.fill[Int](31)(100) // 0, -1\u304c\u3064\u304b\u3048\u306a\u3044\u306e\u3067\u5909\u306a\u5024\u3060\u3051\u3069100\u3067\u521d\u671f\u5316\n\n REP_r(30) { k =>\n if (ans00(k+1) == 100) {\n ans00(k+1) = query(k, 0, 0)\n }\n\n val ans10 = query(k, 1, 0)\n val ans01 = query(k, 0, 1)\n\n (ans10, ans01) match {\n // (1, 1)\n case (-1, 1) =>\n a |= 1 << k\n b |= 1 << k\n ans00(k) = ans00(k+1)\n\n // (0, 0)\n case (1, -1) =>\n ans00(k) = ans00(k+1)\n\n // ans10 == ans01 == ans00(k)\n case (1, 1) | (-1, -1) | (0, 0) =>\n ans00(k) = ans10\n ans00(k + 1) match {\n // (1, 0)\n case 1 =>\n a |= 1 <\n b |= 1 < ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 var a, b = 0\n\n def query(k: Int, c: Int, d: Int): Int = {\n out.println(s\"? $c $d\")\n out.flush()\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n REP_r(30) { k =>\n /*\n (c, d) = (1, 1)\n\n a b xor\n 1 1 0\n 1 0 -1\n 0 1 1\n 0 0 0\n */\n query(k, a | (1 << k), b | (1 << k)) match {\n case -1 =>\n a |= 1 << k\n\n case 1 =>\n b |= 1 << k\n\n case 0 =>\n /*\n (c, d) = (1, 0)\n\n a b xor\n 1 1 -1\n 1 0 0\n 0 1 0\n 0 0 1\n */\n query(k, a | (1 << k), b) match {\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n\n case 1 =>\n\n case x =>\n throw new Exception(x.toString)\n }\n\n case x =>\n throw new Exception(x.toString)\n }\n }\n\n answer(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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 var a, b = 0\n\n def query(k: Int, c: Int, d: Int): Int = {\n out.println(s\"? $c $d\")\n out.flush()\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n REP_r(30) { k =>\n query(k, a, b) match {\n case 1 =>\n\n /*\n a > b\n (c, d) = (1, 0)\n\n a b xor\n 0 0 1\n 1 0 0\n 1 1 -1\n */\n query(k, a | (1 << k), b) match {\n case 1 =>\n case 0 =>\n a |= 1 << k\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n }\n\n case -1 =>\n\n /*\n a < b\n (c, d) = (0, 1)\n\n a b xor\n 1 1 1\n 0 1 0\n 0 0 -1\n */\n query(k, a, b| (1 << k)) match {\n case 1 =>\n a |= 1 << k\n b |= 1 << k\n case 0 =>\n b |= 1 << k\n case -1 =>\n }\n\n case 0 =>\n /*\n a == b\n (c, d) = (1, 0)\n\n a b xor\n 1 1 -1\n 0 0 1\n */\n query(k, a | (1 << k), b) match {\n case 1 =>\n\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n\n case x =>\n throw new Exception(x.toString)\n }\n\n case x =>\n throw new Exception(x.toString)\n }\n }\n\n answer(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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 var a, b = 0\n\n def query(k: Int, cbit: Int, dbit: Int): Int = {\n val c = cbit << k\n val d = dbit << k\n out.println(s\"? $c $d\")\n out.flush()\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n REP(30) { k =>\n query(k, 1, 1) match {\n case -1 =>\n a |= 1 << k\n\n case 1 =>\n b |= 1 << k\n\n case 0 =>\n query(k, 1, 0) match {\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n\n case 1 =>\n\n case x =>\n throw new Exception(x.toString)\n }\n }\n }\n\n answer(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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 var a, b = 0\n\n def query(k: Int, c: Int, d: Int): Int = {\n out.println(s\"? $c $d\")\n out.flush()\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n REP_r(3) { k =>\n /*\n (c, d) = (1, 1)\n\n a b xor\n 1 1 0\n 1 0 -1\n 0 1 1\n 0 0 0\n */\n query(k, a | (1 << k), b | (1 << k)) match {\n case -1 =>\n a |= 1 << k\n\n case 1 =>\n b |= 1 << k\n\n case 0 =>\n /*\n (c, d) = (1, 0)\n\n a b xor\n 1 1 -1\n 1 0 0\n 0 1 0\n 0 0 1\n */\n query(k, a | (1 << k), b) match {\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n\n case 1 =>\n\n case x =>\n throw new Exception(x.toString)\n }\n\n case x =>\n throw new Exception(x.toString)\n }\n }\n\n answer(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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 var a, b = 0\n\n def query(k: Int, c: Int, d: Int): Int = {\n out.println(s\"? $c $d\")\n out.flush()\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n REP_r(30) { k =>\n query(k, a, b) match {\n case 1 =>\n\n /*\n a > b\n (c, d) = (1, 0)\n\n a b xor\n 0 0 1\n 1 0 0\n 1 1 -1\n */\n query(k, a | (1 << k), b) match {\n case 1 =>\n case 0 =>\n a |= 1 << k\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n }\n\n case -1 =>\n\n /*\n a < b\n (c, d) = (0, 1)\n\n a b xor\n 1 1 1\n 0 1 0\n 0 0 -1\n */\n query(k, a | (1 << k), b) match {\n case 1 =>\n a |= 1 << k\n b |= 1 << k\n case 0 =>\n b |= 1 << k\n case -1 =>\n }\n\n case 0 =>\n /*\n a == b\n (c, d) = (1, 0)\n\n a b xor\n 1 1 -1\n 0 0 1\n */\n query(k, a | (1 << k), b) match {\n case 1 =>\n\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n\n case x =>\n throw new Exception(x.toString)\n }\n\n case x =>\n throw new Exception(x.toString)\n }\n }\n\n answer(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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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 var a, b = 0\n\n def query(k: Int, c: Int, d: Int): Int = {\n println(s\"? $c $d\")\n ni()\n }\n\n def answer(a: Int, b: Int): Unit = {\n println(s\"! $a $b\")\n }\n\n REP_r(30) { k =>\n /*\n (c, d) = (1, 1)\n\n a b xor\n 1 1 0\n 1 0 -1\n 0 1 1\n 0 0 0\n */\n query(k, a | (1 << k), b | (1 << k)) match {\n case -1 =>\n a |= 1 << k\n\n case 1 =>\n b |= 1 << k\n\n case 0 =>\n /*\n (c, d) = (1, 0)\n\n a b xor\n 1 1 -1\n 1 0 0\n 0 1 0\n 0 0 1\n */\n query(k, a | (1 << k), b) match {\n case -1 =>\n a |= 1 << k\n b |= 1 << k\n\n case 1 =>\n\n case x =>\n throw new Exception(x.toString)\n }\n\n case x =>\n throw new Exception(x.toString)\n }\n }\n\n answer(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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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": "7dc1137dd1f0c645cc7ec6dfdb92f5df"} {"nl": {"description": "Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.", "input_spec": "The first line of the input contains six positive integers x1,\u2009y1,\u2009x2,\u2009y2,\u2009x3,\u2009y3 (1\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2,\u2009x3,\u2009y3\u2009\u2264\u2009100), where xi and yi determine the length and width of the logo of the i-th company respectively.", "output_spec": "If it is impossible to place all the three logos on a square shield, print a single integer \"-1\" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters \"A\", \"B\" or \"C\". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters \"A\" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters \"B\" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters \"C\" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.", "sample_inputs": ["5 1 2 5 5 2", "4 4 2 6 4 2"], "sample_outputs": ["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"], "notes": null}, "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 //\u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u043c 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": "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"}, {"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 //\u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u043c a\n if (y2 == a) {\n if (y3 == a) {\n //\u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u043c a b \u0438 \u0441 \u0433\u043e\u0440\u0438\u0437\u043e\u043d\u0442\u0430\u043b\u044c\u043d\u043e\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 //\u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u043c a\n if (y2 == a) {\n if (y3 == a) {\n //\u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u043c a b \u0438 \u0441 \u0433\u043e\u0440\u0438\u0437\u043e\u043d\u0442\u0430\u043b\u044c\u043d\u043e\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"} {"nl": {"description": "You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \\le k \\le n$$$ that $$$k \\bmod x = y$$$, where $$$\\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 5 \\cdot 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \\le x \\le 10^9;~ 0 \\le y < x;~ y \\le n \\le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints.", "output_spec": "For each test case, print the answer \u2014 maximum non-negative integer $$$k$$$ such that $$$0 \\le k \\le n$$$ and $$$k \\bmod x = y$$$. It is guaranteed that the answer always exists.", "sample_inputs": ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"], "sample_outputs": ["12339\n0\n15\n54306\n999999995\n185\n999999998"], "notes": "NoteIn the first test case of the example, the answer is $$$12339 = 7 \\cdot 1762 + 5$$$ (thus, $$$12339 \\bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$."}, "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": "\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}"}, {"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"} {"nl": {"description": " You have one chip and one chance to play roulette. Are you feeling lucky?", "input_spec": null, "output_spec": "Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).", "sample_inputs": [], "sample_outputs": [], "notes": null}, "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) = println(\"black\")\n}\n\t\t \t \n \t \t\t\t\t \n\t\t\t \t\t\t\t\t\n \t \t\t \t\t \t"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n println(1)\n }\n}\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 "}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n println(0)\n }\n}\n\t\t \t \t\n \t\t \t\t \n \t\t \t\t\t \t\n\t\t \t\t \t"}], "src_uid": "f2a71cb9706b76317f2f442a9129055f"} {"nl": {"description": "Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first $$$n$$$ olympiads the organizers introduced the following rule of the host city selection.The host cities of the olympiads are selected in the following way. There are $$$m$$$ cities in Berland wishing to host the olympiad, they are numbered from $$$1$$$ to $$$m$$$. The host city of each next olympiad is determined as the city that hosted the olympiad the smallest number of times before. If there are several such cities, the city with the smallest index is selected among them.Misha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first $$$n$$$ olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \\leq n, m, q \\leq 500\\,000$$$)\u00a0\u2014 the number of olympiads before the rule was introduced, the number of cities in Berland wishing to host the olympiad, and the number of years Misha's mother is interested in, respectively. The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq m$$$), where $$$a_i$$$ denotes the city which hosted the olympiad in the $$$i$$$-th year. Note that before the rule was introduced the host city was chosen arbitrarily. Each of the next $$$q$$$ lines contains an integer $$$k_i$$$ ($$$n + 1 \\leq k_i \\leq 10^{18}$$$)\u00a0\u2014 the year number Misha's mother is interested in host city in.", "output_spec": "Print $$$q$$$ integers. The $$$i$$$-th of them should be the city the olympiad will be hosted in the year $$$k_i$$$.", "sample_inputs": ["6 4 10\n3 1 1 1 2 2\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16", "4 5 4\n4 4 5 1\n15\n9\n13\n6"], "sample_outputs": ["4\n3\n4\n2\n3\n4\n1\n2\n3\n4", "5\n3\n3\n3"], "notes": "NoteIn the first example Misha's mother is interested in the first $$$10$$$ years after the rule was introduced. The host cities these years are 4, 3, 4, 2, 3, 4, 1, 2, 3, 4.In the second example the host cities after the new city is introduced are 2, 3, 1, 2, 3, 5, 1, 2, 3, 4, 5, 1."}, "positive_code": [{"source_code": "import java.util.Comparator\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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n case class City(i: Int, held: Int)\n case class Query(id: Int, year: Long)\n\n def solve(): Unit = {\n val M, N, Q = ni()\n val C = Array.ofDim[Int](N)\n REP(M) { _ =>\n val i = ni() - 1\n C(i) += 1\n }\n\n debug(C)\n\n val queryQueue = new java.util.PriorityQueue[Query](Q, new Comparator[Query] {\n override def compare(o1: Query, o2: Query): Int = {\n java.lang.Long.compare(o1.year, o2.year)\n }\n })\n REP(Q) { i =>\n queryQueue.add(Query(i, nl() - M - 1)) // 0\u5e74\u30b9\u30bf\u30fc\u30c8\n }\n\n val cityQueue = new java.util.PriorityQueue[City](N, new Comparator[City] {\n override def compare(o1: City, o2: City): Int = {\n if (o1.held == o2.held) Integer.compare(o1.i, o2.i)\n else Integer.compare(o1.held, o2.held)\n }\n })\n\n val minHeld = C.min\n REP(N) { i =>\n cityQueue.add(City(i, C(i) - minHeld))\n }\n\n val INF = 1e18.toLong\n\n val ans = Array.ofDim[Int](Q)\n var year = 0L\n var cityCnt = 0\n var held = 0L\n val bit = new BIT(N, 0)(_+_)\n def expectedHeld(targetYear: Long): Long = {\n if (cityCnt == 0) INF else (targetYear - year) / cityCnt + held\n }\n\n def findCity(targetYear: Long): Int = {\n val cnt = (targetYear - year) % cityCnt + 1\n debug(s\"fincCity($targetYear) cnt:$cnt\")\n def test(i: Int): Boolean = {\n cnt <= bit.sum(i + 1)\n }\n\n findMin(test, 0, N - 1)\n }\n\n while(!queryQueue.isEmpty) {\n val q = queryQueue.poll()\n debug(s\"q:$q\")\n // q.year\u4ee5\u524d\u306b\u8ffd\u52a0\u3055\u308c\u308bcity\u3092\u3053\u3053\u3067\u8ffd\u52a0\u3059\u308b\n while(!cityQueue.isEmpty && expectedHeld(q.year) >= cityQueue.peek().held) {\n val city = cityQueue.poll()\n year += (city.held - held) * cityCnt // \u4eca\u306ecities\u3060\u3051\u3067city.held\u307e\u3067\u9032\u3081\u308b\n held = city.held\n bit.add(city.i, 1)\n cityCnt += 1\n debug(s\"city add $city year:$year cityCnt:$cityCnt held:$held\")\n }\n ans(q.id) = findCity(q.year) + 1\n }\n\n ans.foreach(out.println)\n }\n\n def findMin(f: Int => Boolean, min: Int, max: Int): Int = {\n var l = min - 1\n var h = max\n while(h - l > 1) {\n val x = (h + l) / 2\n if (f(x)) h = x\n else l = x\n }\n h\n }\n\nclass BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {\n def this(n: Int) = this(n, 0)(_ + _)\n\n private val N = 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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\n */\n def sum(i: Int): Int = {\n assert(i <= n)\n var x = i\n var s: Int = 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: 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 /**\n * [l, r)\n */\n def query(l: Int, r: Int)(sub: (Int, Int) => Int): Int = {\n assert(r > l)\n sub(sum(r), sum(l))\n }\n}\n}"}], "negative_code": [], "src_uid": "c90c7a562c8221dd428c807c919ae156"} {"nl": {"description": "3R2 - Standby for ActionOur dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show \"1 vs. $$$n$$$\"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are $$$s$$$ ($$$s > 0$$$) opponents remaining and $$$t$$$ ($$$0 \\le t \\le s$$$) of them make a mistake on it, JOE receives $$$\\displaystyle\\frac{t}{s}$$$ dollars, and consequently there will be $$$s - t$$$ opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?", "input_spec": "The first and single line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), denoting the number of JOE's opponents in the show.", "output_spec": "Print a number denoting the maximum prize (in dollars) JOE could have. Your answer will be considered correct if it's absolute or relative error won't exceed $$$10^{-4}$$$. In other words, if your answer is $$$a$$$ and the jury answer is $$$b$$$, then it must hold that $$$\\frac{|a - b|}{max(1, b)} \\le 10^{-4}$$$.", "sample_inputs": ["1", "2"], "sample_outputs": ["1.000000000000", "1.500000000000"], "notes": "NoteIn the second example, the best scenario would be: one contestant fails at the first question, the other fails at the next one. The total reward will be $$$\\displaystyle \\frac{1}{2} + \\frac{1}{1} = 1.5$$$ dollars."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val n = readInt\n val s = (1 to n).foldLeft(0.0){\n case (d, i) => d + (1.0 / i)\n }\n println(s)\n }\n}"}], "negative_code": [], "src_uid": "260666df22ee510fcce3ebdfbb8b71a2"} {"nl": {"description": "You are given three strings $$$a$$$, $$$b$$$ and $$$c$$$ of the same length $$$n$$$. The strings consist of lowercase English letters only. The $$$i$$$-th letter of $$$a$$$ is $$$a_i$$$, the $$$i$$$-th letter of $$$b$$$ is $$$b_i$$$, the $$$i$$$-th letter of $$$c$$$ is $$$c_i$$$.For every $$$i$$$ ($$$1 \\leq i \\leq n$$$) you must swap (i.e. exchange) $$$c_i$$$ with either $$$a_i$$$ or $$$b_i$$$. So in total you'll perform exactly $$$n$$$ swap operations, each of them either $$$c_i \\leftrightarrow a_i$$$ or $$$c_i \\leftrightarrow b_i$$$ ($$$i$$$ iterates over all integers between $$$1$$$ and $$$n$$$, inclusive).For example, if $$$a$$$ is \"code\", $$$b$$$ is \"true\", and $$$c$$$ is \"help\", you can make $$$c$$$ equal to \"crue\" taking the $$$1$$$-st and the $$$4$$$-th letters from $$$a$$$ and the others from $$$b$$$. In this way $$$a$$$ becomes \"hodp\" and $$$b$$$ becomes \"tele\".Is it possible that after these swaps the string $$$a$$$ becomes exactly the same as the string $$$b$$$?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a string of lowercase English letters $$$a$$$. The second line of each test case contains a string of lowercase English letters $$$b$$$. The third line of each test case contains a string of lowercase English letters $$$c$$$. It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding $$$100$$$.", "output_spec": "Print $$$t$$$ lines with answers for all test cases. For each test case: If it is possible to make string $$$a$$$ equal to string $$$b$$$ print \"YES\" (without quotes), otherwise print \"NO\" (without quotes). You can print either lowercase or uppercase letters in the answers.", "sample_inputs": ["4\naaa\nbbb\nccc\nabc\nbca\nbca\naabb\nbbaa\nbaba\nimi\nmii\niim"], "sample_outputs": ["NO\nYES\nYES\nNO"], "notes": "NoteIn the first test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.In the second test case, you should swap $$$c_i$$$ with $$$a_i$$$ for all possible $$$i$$$. After the swaps $$$a$$$ becomes \"bca\", $$$b$$$ becomes \"bca\" and $$$c$$$ becomes \"abc\". Here the strings $$$a$$$ and $$$b$$$ are equal.In the third test case, you should swap $$$c_1$$$ with $$$a_1$$$, $$$c_2$$$ with $$$b_2$$$, $$$c_3$$$ with $$$b_3$$$ and $$$c_4$$$ with $$$a_4$$$. Then string $$$a$$$ becomes \"baba\", string $$$b$$$ becomes \"baba\" and string $$$c$$$ becomes \"abab\". Here the strings $$$a$$$ and $$$b$$$ are equal.In the fourth test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$."}, "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 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"}, {"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"} {"nl": {"description": "Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped $$$n$$$ grains. Nastya read that each grain weighs some integer number of grams from $$$a - b$$$ to $$$a + b$$$, inclusive (numbers $$$a$$$ and $$$b$$$ are known), and the whole package of $$$n$$$ grains weighs from $$$c - d$$$ to $$$c + d$$$ grams, inclusive (numbers $$$c$$$ and $$$d$$$ are known). The weight of the package is the sum of the weights of all $$$n$$$ grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $$$i$$$-th grain weighs some integer number $$$x_i$$$ $$$(a - b \\leq x_i \\leq a + b)$$$, and in total they weigh from $$$c - d$$$ to $$$c + d$$$, inclusive ($$$c - d \\leq \\sum\\limits_{i=1}^{n}{x_i} \\leq c + d$$$).", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$ \u00a0\u2014 the number of test cases. The next $$$t$$$ lines contain descriptions of the test cases, each line contains $$$5$$$ integers: $$$n$$$ $$$(1 \\leq n \\leq 1000)$$$ \u00a0\u2014 the number of grains that Nastya counted and $$$a, b, c, d$$$ $$$(0 \\leq b < a \\leq 1000, 0 \\leq d < c \\leq 1000)$$$ \u00a0\u2014 numbers that determine the possible weight of one grain of rice (from $$$a - b$$$ to $$$a + b$$$) and the possible total weight of the package (from $$$c - d$$$ to $$$c + d$$$).", "output_spec": "For each test case given in the input print \"Yes\", if the information about the weights is not inconsistent, and print \"No\" if $$$n$$$ grains with masses from $$$a - b$$$ to $$$a + b$$$ cannot make a package with a total mass from $$$c - d$$$ to $$$c + d$$$.", "sample_inputs": ["5\n7 20 3 101 18\n11 11 10 234 2\n8 9 7 250 122\n19 41 21 321 10\n3 10 8 6 1"], "sample_outputs": ["Yes\nNo\nYes\nNo\nYes"], "notes": "NoteIn the first test case of the example, we can assume that each grain weighs $$$17$$$ grams, and a pack $$$119$$$ grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs $$$16$$$ grams, and a pack $$$128$$$ grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that $$$3$$$ grains of rice weigh $$$2$$$, $$$2$$$, and $$$3$$$ grams, and a pack is $$$7$$$ grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains."}, "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, 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}"}, {"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"} {"nl": {"description": "This is a harder version of the problem. In this version $$$n \\le 500\\,000$$$The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \\le a_i \\le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 500\\,000$$$)\u00a0\u2014 the number of plots. The second line contains the integers $$$m_1, m_2, \\ldots, m_n$$$ ($$$1 \\leq m_i \\leq 10^9$$$)\u00a0\u2014 the limit on the number of floors for every possible number of floors for a skyscraper on each plot.", "output_spec": "Print $$$n$$$ integers $$$a_i$$$\u00a0\u2014 the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.", "sample_inputs": ["5\n1 2 3 2 1", "3\n10 6 8"], "sample_outputs": ["1 2 3 2 1", "10 6 6"], "notes": "NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal."}, "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}"}, {"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"}], "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"} {"nl": {"description": "An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons \u2014 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: \"0124:5678:90ab:cdef:0124:5678:90ab:cdef\". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: \"a56f:00d3:0000:0124:0001:f19a:1000:0000\" \u2009\u2192\u2009 \"a56f:d3:0:0124:01:f19a:1000:00\". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to \"::\". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: \"a56f:00d3:0000:0124:0001:0000:0000:0000\" \u2009\u2192\u2009 \"a56f:00d3:0000:0124:0001::\"; \"a56f:0000:0000:0124:0001:0000:1234:0ff0\" \u2009\u2192\u2009 \"a56f::0124:0001:0000:1234:0ff0\"; \"a56f:0000:0000:0000:0001:0000:1234:0ff0\" \u2009\u2192\u2009 \"a56f:0000::0000:0001:0000:1234:0ff0\"; \"a56f:00d3:0000:0124:0001:0000:0000:0000\" \u2009\u2192\u2009 \"a56f:00d3:0000:0124:0001::0000\"; \"0000:0000:0000:0000:0000:0000:0000:0000\" \u2009\u2192\u2009 \"::\". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters \"::\" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.", "input_spec": "The first line contains a single integer n \u2014 the number of records to restore (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the following n lines contains a string \u2014 the short IPv6 addresses. Each string only consists of string characters \"0123456789abcdef:\". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.", "output_spec": "For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.", "sample_inputs": ["6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0"], "sample_outputs": ["a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told \"no genome, no degree\". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.", "input_spec": "The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.", "output_spec": "Print \"YES\", if the dwarves belong to the same race. Otherwise, print \"NO\".", "sample_inputs": ["ab\nba", "aa\nab"], "sample_outputs": ["YES", "NO"], "notes": "Note First example: you can simply swap two letters in string \"ab\". So we get \"ba\". Second example: we can't change string \"aa\" into string \"ab\", because \"aa\" does not contain letter \"b\". "}, "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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i\u2009-\u2009j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1\u2009=\u20091,\u2009p2,\u2009...,\u2009pk is equal to units of energy.Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i\u2009\u2264\u2009ai\u2009\u2264\u2009ai\u2009+\u20091) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1\u2009=\u20091,\u2009p2,\u2009...,\u2009pk then for each 1\u2009\u2264\u2009i\u2009<\u2009k satisfying pi\u2009+\u20091\u2009=\u2009api and api\u2009\u2260\u2009pi Mike will spend only 1 unit of energy instead of |pi\u2009-\u2009pi\u2009+\u20091| walking from the intersection pi to intersection pi\u2009+\u20091. For example, if Mike chooses a sequence p1\u2009=\u20091,\u2009p2\u2009=\u2009ap1,\u2009p3\u2009=\u2009ap2,\u2009...,\u2009pk\u2009=\u2009apk\u2009-\u20091, he spends exactly k\u2009-\u20091 units of total energy walking around them.Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1\u2009\u2264\u2009i\u2009\u2264\u2009n Mike is interested in finding minimum possible total energy of some sequence p1\u2009=\u20091,\u2009p2,\u2009...,\u2009pk\u2009=\u2009i.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of Mike's city intersection. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (i\u2009\u2264\u2009ai\u2009\u2264\u2009n , , describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).", "output_spec": "In the only line print n integers m1,\u2009m2,\u2009...,\u2009mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.", "sample_inputs": ["3\n2 2 3", "5\n1 2 3 4 5", "7\n4 4 4 4 7 7 7"], "sample_outputs": ["0 1 2", "0 1 2 3 4", "0 1 2 1 2 3 3"], "notes": "NoteIn the first sample case desired sequences are:1:\u20091; m1\u2009=\u20090;2:\u20091,\u20092; m2\u2009=\u20091;3:\u20091,\u20093; m3\u2009=\u2009|3\u2009-\u20091|\u2009=\u20092.In the second sample case the sequence for any intersection 1\u2009<\u2009i is always 1,\u2009i and mi\u2009=\u2009|1\u2009-\u2009i|.In the third sample case\u00a0\u2014 consider the following intersection sequences:1:\u20091; m1\u2009=\u20090;2:\u20091,\u20092; m2\u2009=\u2009|2\u2009-\u20091|\u2009=\u20091;3:\u20091,\u20094,\u20093; m3\u2009=\u20091\u2009+\u2009|4\u2009-\u20093|\u2009=\u20092;4:\u20091,\u20094; m4\u2009=\u20091;5:\u20091,\u20094,\u20095; m5\u2009=\u20091\u2009+\u2009|4\u2009-\u20095|\u2009=\u20092;6:\u20091,\u20094,\u20096; m6\u2009=\u20091\u2009+\u2009|4\u2009-\u20096|\u2009=\u20093;7:\u20091,\u20094,\u20095,\u20097; m7\u2009=\u20091\u2009+\u2009|4\u2009-\u20095|\u2009+\u20091\u2009=\u20093."}, "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": "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"}, {"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 \u21d2\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 \u21d2 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 \u21d2\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 \u21d2\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 \u21d2 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 \u21d2\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"} {"nl": {"description": "Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string \"abab\" has two divisors \u2014 \"ab\" and \"abab\".Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.", "input_spec": "The first input line contains a non-empty string s1. The second input line contains a non-empty string s2. Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.", "output_spec": "Print the number of common divisors of strings s1 and s2. ", "sample_inputs": ["abcdabcd\nabcdabcdabcdabcd", "aaa\naa"], "sample_outputs": ["2", "1"], "notes": "NoteIn first sample the common divisors are strings \"abcd\" and \"abcdabcd\".In the second sample the common divisor is a single string \"a\". String \"aa\" isn't included in the answer as it isn't a divisor of string \"aaa\"."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * @author chengyi\n */\nobject CommonDivisors {\n \n //common divisor for string\n def cd(s1:String, s2:String):Int={\n val smin = if (s1.length()>s2.length()) s2 else s1\n val smax = if (s1.length()>s2.length()) s1 else s2\n val sminl = smin.length()\n val smaxl = smax.length()\n val sqrt:Float = Math.sqrt(sminl).toFloat\n var rnd:Int = Math.round(sqrt)\n if (sqrt < rnd){\n rnd = rnd -1\n }\n var tryList:List[Int] = List()\n (1 to rnd).map{\n x=> if (sminl % x==0){\n if (!tryList.contains(sminl/x))\n tryList = tryList.::(sminl/x)\n if (!tryList.contains(x))\n tryList = tryList:+x\n }\n }\n tryList = tryList.sorted(Ordering[Int].reverse)\n //println(tryList)\n var num:Int =0\n for (a<-0 to tryList.length-1){\n val tryLen = tryList(a)\n if (smaxl % tryLen == 0){\n val maxrp = smaxl / tryLen\n val minrp = sminl / tryLen\n val substr = smin.substring(0, tryLen)\n if (smax.equals(List.fill(maxrp)(substr).mkString(\"\")) && smin.equals(List.fill(minrp)(substr).mkString(\"\")))\n num = num + 1\n }\n }\n num\n }\n \n \n def main(args:Array[String]){\n val s1=StdIn.readLine()\n val s2=StdIn.readLine()\n println(cd(s1,s2))\n }\n \n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * @author chengyi\n */\nobject CommonDivisors {\n \n //common divisor for string\n def cd(s1:String, s2:String):Int={\n val smin = if (s1.length()>s2.length()) s2 else s1\n val smax = if (s1.length()>s2.length()) s1 else s2\n val sminl = smin.length()\n val smaxl = smax.length()\n val sqrt:Float = Math.sqrt(sminl).toFloat\n var rnd:Int = Math.round(sqrt)\n if (sqrt < rnd){\n rnd = rnd -1\n }\n var tryList:List[Int] = List()\n (1 to rnd).map{\n x=> if (sminl % x==0){\n tryList = tryList.::(sminl/x)\n tryList = tryList:+x\n }\n }\n tryList = tryList.sorted(Ordering[Int].reverse)\n //println(tryList)\n var num:Int =0\n for (a<-0 to tryList.length-1){\n val tryLen = tryList(a)\n if (smaxl % tryLen == 0){\n val maxrp = smaxl / tryLen\n val minrp = sminl / tryLen\n val substr = smin.substring(0, tryLen)\n if (smax.equals(List.fill(maxrp)(substr).mkString(\"\")) && smin.equals(List.fill(minrp)(substr).mkString(\"\")))\n num = num + 1\n }\n }\n num\n }\n \n \n def main(args:Array[String]){\n val s1=StdIn.readLine()\n val s2=StdIn.readLine()\n println(cd(s1,s2))\n }\n \n}"}, {"source_code": "import scala.io.StdIn\n\n/**\n * @author chengyi\n */\nobject CommonDivisors {\n \n //common divisor for string\n def cd(s1:String, s2:String):Int={\n val smin = if (s1.length()>s2.length()) s2 else s1\n val smax = if (s1.length()>s2.length()) s1 else s2\n val sminl = smin.length()\n val smaxl = smax.length()\n val sqrt:Float = Math.sqrt(sminl).toFloat\n var rnd:Int = Math.round(sqrt)\n if (sqrt < rnd){\n rnd = rnd -1\n }\n var tryList:List[Int] = List()\n (1 to rnd).map{\n x=> if (sminl % x==0){\n tryList = tryList.::(sminl/x)\n tryList = tryList:+x\n }\n }\n tryList = tryList.sorted(Ordering[Int].reverse)\n println(tryList)\n var num:Int =0\n for (a<-0 to tryList.length-1){\n val tryLen = tryList(a)\n if (smaxl % tryLen == 0){\n val maxrp = smaxl / tryLen\n val minrp = sminl / tryLen\n val substr = smin.substring(0, tryLen)\n if (smax.equals(List.fill(maxrp)(substr).mkString(\"\")) && smin.equals(List.fill(minrp)(substr).mkString(\"\")))\n num = num + 1\n }\n }\n num\n }\n \n \n def main(args:Array[String]){\n val s1=StdIn.readLine()\n val s2=StdIn.readLine()\n println(cd(s1,s2))\n }\n \n}"}], "src_uid": "d28614f0365ea53530e35c6bd1e6f1dd"} {"nl": {"description": "This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting \u00ab+\u00bb and \u00ab1\u00bb into it we can get a correct mathematical expression. For example, sequences \u00ab(())()\u00bb, \u00ab()\u00bb and \u00ab(()(()))\u00bb are regular, while \u00ab)(\u00bb, \u00ab(()\u00bb and \u00ab(()))(\u00bb are not. You are given a string of \u00ab(\u00bb and \u00ab)\u00bb characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.", "input_spec": "The first line of the input file contains a non-empty string, consisting of \u00ab(\u00bb and \u00ab)\u00bb characters. Its length does not exceed 106.", "output_spec": "Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing \"0 1\".", "sample_inputs": [")((())))(()())", "))("], "sample_outputs": ["6 2", "0 1"], "notes": null}, "positive_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 + 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "N ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the i-th lady by Bi, her intellect by Ii and her richness by Ri. Then i-th lady is a probable self-murderer if there is some j-th lady that Bi\u2009<\u2009Bj,\u2009Ii\u2009<\u2009Ij,\u2009Ri\u2009<\u2009Rj. Find the number of probable self-murderers.", "input_spec": "The first line contains one integer N (1\u2009\u2264\u2009N\u2009\u2264\u2009500000). The second line contains N integer numbers Bi, separated by single spaces. The third and the fourth lines contain sequences Ii and Ri in the same format. It is guaranteed that 0\u2009\u2264\u2009Bi,\u2009Ii,\u2009Ri\u2009\u2264\u2009109.", "output_spec": "Output the answer to the problem.", "sample_inputs": ["3\n1 4 2\n4 3 2\n2 5 3"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util.Comparator\n\nobject LadyOrder extends App {\n\n val comparator = new Comparator[Lady] {\n override def compare(o1: Lady, o2: Lady): Int = o1.a.compareTo(o2.a)\n }\n\n val bcomparator = new Comparator[Lady] {\n override def compare(o1: Lady, o2: Lady): Int = o1.b.compareTo(o2.b)\n }\n\n val s = new BufferedReader(new InputStreamReader(System.in), 8192 * 3)\n val n = s.readLine().toInt\n val as = s.readLine().split(\" \")\n val bs = s.readLine().split(\" \")\n val cs = s.readLine().split(\" \")\n var ladiesColl = (0 until n).map(i => Lady(as(i).toInt, 0, 0))\n val ladies = ladiesColl.toArray\n (0 until n).foreach(x => ladies(x).b = bs(x).toInt)\n (0 until n).foreach(x => ladies(x).c = cs(x).toInt)\n inline()\n util.Arrays.sort(ladies, comparator)\n val maxy = ladies.maxBy(_.b).b\n val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)\n var result = 0\n var lastx = 0\n\n\n\n def inline(): Unit = {\n util.Arrays.sort(ladies, bcomparator)\n val sorted = ladies\n var i = 0\n var cnt = 0\n while (i< n) {\n val cur = sorted(i).b\n while (i < n && sorted(i).b == cur) {\n sorted(i).b = cnt\n i += 1\n }\n cnt += 1\n }\n }\n\n var i = n - 1\n while (i >= 0) {\n var start = i\n lastx = ladies(i).a\n while (i >= 0 && ladies(i).a == lastx) {\n val cur = ladies(i)\n val x = mrq.query(cur.b + 1, maxy + 1)\n if (cur.c < x) result += 1\n i -= 1\n }\n var cnt = math.max(i, 0) + 1\n while (cnt <= start) {\n val cur = ladies(cnt)\n if (mrq.tree(cur.b + mrq.n) < cur.c) {\n mrq.update(cur.b, cur.c)\n }\n cnt += 1\n }\n }\n\n println(result)\n\n class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {\n\n var n = 1 << ((math.log(size) / math.log(2)).toInt + 1)\n\n val tree = Array.fill[Int](n * 2)(initValue)\n\n def update(i: Int, v: Int): Unit = {\n var cur = i + n\n tree(cur) = v\n while (cur != 1) {\n cur = cur / 2\n tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))\n }\n }\n\n def query(left: Int, right: Int): Int = {\n var l = left + n\n var r = right + n - 1\n var ans = minVal\n while (l <= r) {\n if ((l & 1) == 1) {\n ans = func(ans, tree(l))\n }\n if ((r & 1) == 0) {\n ans = func(ans, tree(r))\n }\n l = (l + 1) / 2\n r = (r - 1) / 2\n }\n ans\n }\n\n }\n\n case class Lady(var a: Int, var b: Int, var c: Int)\n\n}\n"}], "negative_code": [{"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject LadyOrder extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray\n (0 until n).foreach(x => ladies(x).b = s.nextInt())\n (0 until n).foreach(x => ladies(x).c = s.nextInt())\n ladies = ladies.sortBy(_.a)\n val maxy = ladies.maxBy(_.b).b\n val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)\n var result = 0\n var lastx = ladies.last.a\n\n var i = n - 1\n while (i > 0) {\n var start = i\n lastx = ladies(i).a\n while (i >= 0 && ladies(i).a == lastx) {\n val cur = ladies(i)\n val x = mrq.query(cur.b + 1, maxy + 1)\n if (cur.c < x) result += 1\n i -= 1\n }\n var cnt = math.max(i, 0)\n while (cnt <= start) {\n val cur = ladies(cnt)\n if (mrq.tree(cur.b + mrq.n) < cur.c) {\n mrq.update(cur.b, cur.c)\n }\n cnt += 1\n }\n }\n\n println(result)\n\n class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {\n\n val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)\n val tree = Array.fill[Int](n * 2)(initValue)\n\n def update(i: Int, v: Int): Unit = {\n var cur = i + n\n tree(cur) = v\n while (cur != 1) {\n cur = cur / 2\n tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))\n }\n }\n\n def query(left: Int, right: Int): Int = {\n var l = left + n\n var r = right + n - 1\n var ans = minVal\n while (l <= r) {\n if ((l & 1) == 1) {\n ans = func(ans, tree(l))\n }\n if ((r & 1) == 0) {\n ans = func(ans, tree(r))\n }\n l = (l + 1) / 2\n r = (r - 1) / 2\n }\n ans\n }\n\n }\n\n case class Lady(var a: Int, var b: Int, var c: Int)\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject LadyOrder extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray\n (0 until n).foreach(x => ladies(x).b = s.nextInt())\n (0 until n).foreach(x => ladies(x).c = s.nextInt())\n ladies = ladies.sortBy(_.a)\n val maxy = ladies.maxBy(_.b).b\n val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)\n var result = 0\n var lastx = ladies.last.a\n\n var i = n - 1\n while (i >= 0) {\n var start = i\n lastx = ladies(i).a\n while (i >= 0 && ladies(i).a == lastx) {\n val cur = ladies(i)\n val x = mrq.query(cur.b + 1, maxy + 1)\n if (cur.c < x) result += 1\n i -= 1\n }\n var cnt = math.max(i, 0)\n while (cnt <= start) {\n val cur = ladies(cnt)\n if (mrq.tree(cur.b + mrq.n) < cur.c) {\n mrq.update(cur.b, cur.c)\n }\n cnt += 1\n }\n }\n\n println(result)\n\n class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {\n\n val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)\n val tree = Array.fill[Int](n * 2)(initValue)\n\n def update(i: Int, v: Int): Unit = {\n var cur = i + n\n tree(cur) = v\n while (cur != 1) {\n cur = cur / 2\n tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))\n }\n }\n\n def query(left: Int, right: Int): Int = {\n var l = left + n\n var r = right + n - 1\n var ans = minVal\n while (l <= r) {\n if ((l & 1) == 1) {\n ans = func(ans, tree(l))\n }\n if ((r & 1) == 0) {\n ans = func(ans, tree(r))\n }\n l = (l + 1) / 2\n r = (r - 1) / 2\n }\n ans\n }\n\n }\n\n case class Lady(var a: Int, var b: Int, var c: Int)\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject LadyOrder extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray\n (0 until n).foreach(x => ladies(x).b = s.nextInt())\n (0 until n).foreach(x => ladies(x).c = s.nextInt())\n ladies = ladies.sortBy(_.a)\n val maxy = ladies.maxBy(_.b).b\n val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)\n var result = 0\n\n (n - 1 to 0 by -1).foreach { i =>\n val cur = ladies(i)\n val x = mrq.query(cur.b + 1, maxy + 1)\n if (cur.c < x) result += 1\n if (mrq.tree(cur.b + mrq.n) < cur.c) {\n mrq.update(cur.b, cur.c)\n }\n }\n\n println(result)\n\n class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {\n\n val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)\n val tree = Array.fill[Int](n * 2)(initValue)\n\n def update(i: Int, v: Int): Unit = {\n var cur = i + n\n tree(cur) = v\n while (cur != 1) {\n cur = cur / 2\n tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))\n }\n }\n\n def query(left: Int, right: Int): Int = {\n var l = left + n\n var r = right + n - 1\n var ans = minVal\n while (l <= r) {\n if ((l & 1) == 1) {\n ans = func(ans, tree(l))\n }\n if ((r & 1) == 0) {\n ans = func(ans, tree(r))\n }\n l = (l + 1) / 2\n r = (r - 1) / 2\n }\n ans\n }\n\n }\n\n case class Lady(var a: Int, var b: Int, var c: Int)\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject LadyOrder extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray\n (0 until n).foreach(x => ladies(x).b = s.nextInt())\n (0 until n).foreach(x => ladies(x).c = s.nextInt())\n ladies = ladies.sortBy(_.a)\n val maxy = ladies.maxBy(_.b).b\n val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)\n var result = 0\n var lastx = ladies.last.a\n\n (n - 1 to 0 by -1).foreach { i =>\n val cur = ladies(i)\n val x = mrq.query(cur.b + 1, maxy + 1)\n if (cur.a < lastx) {\n lastx = cur.a\n if (cur.c < x) result += 1\n }\n if (mrq.tree(cur.b + mrq.n) < cur.c) {\n mrq.update(cur.b, cur.c)\n }\n }\n\n println(result)\n\n class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {\n\n val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)\n val tree = Array.fill[Int](n * 2)(initValue)\n\n def update(i: Int, v: Int): Unit = {\n var cur = i + n\n tree(cur) = v\n while (cur != 1) {\n cur = cur / 2\n tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))\n }\n }\n\n def query(left: Int, right: Int): Int = {\n var l = left + n\n var r = right + n - 1\n var ans = minVal\n while (l <= r) {\n if ((l & 1) == 1) {\n ans = func(ans, tree(l))\n }\n if ((r & 1) == 0) {\n ans = func(ans, tree(r))\n }\n l = (l + 1) / 2\n r = (r - 1) / 2\n }\n ans\n }\n\n }\n\n case class Lady(var a: Int, var b: Int, var c: Int)\n\n}\n"}], "src_uid": "316187d15c7604025fb6fe4a17a19647"} {"nl": {"description": "Emuskald is an avid horticulturist and owns the world's longest greenhouse \u2014 it is effectively infinite in length.Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m\u2009-\u20091 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.", "input_spec": "The first line of input contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20095000, n\u2009\u2265\u2009m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1\u2009\u2264\u2009si\u2009\u2264\u2009m), and one real number xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order \"from left to the right\", that is in the ascending order of their xi coordinates (xi\u2009<\u2009xi\u2009+\u20091,\u20091\u2009\u2264\u2009i\u2009<\u2009n).", "output_spec": "Output a single integer \u2014 the minimum number of plants to be replanted.", "sample_inputs": ["3 2\n2 1\n1 2.0\n1 3.100", "3 3\n1 5.0\n2 5.5\n3 6.0", "6 3\n1 14.284235\n2 17.921382\n1 20.328172\n3 20.842331\n1 25.790145\n1 27.204125"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.In the second test case, the species are already in the correct order, so no replanting is needed."}, "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)._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": "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"} {"nl": {"description": "A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.You are given an integer $$$n$$$. Your goal is to construct and print exactly $$$n$$$ different regular bracket sequences of length $$$2n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 50$$$) \u2014 the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \\le n \\le 50$$$).", "output_spec": "For each test case, print $$$n$$$ lines, each containing a regular bracket sequence of length exactly $$$2n$$$. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible.", "sample_inputs": ["3\n3\n1\n3"], "sample_outputs": ["()()()\n((()))\n(()())\n()\n((()))\n(())()\n()(())"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Boboniu gives you $$$r$$$ red balls, $$$g$$$ green balls, $$$b$$$ blue balls, $$$w$$$ white balls. He allows you to do the following operation as many times as you want: Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations. ", "input_spec": "The first line contains one integer $$$T$$$ ($$$1\\le T\\le 100$$$) denoting the number of test cases. For each of the next $$$T$$$ cases, the first line contains four integers $$$r$$$, $$$g$$$, $$$b$$$ and $$$w$$$ ($$$0\\le r,g,b,w\\le 10^9$$$).", "output_spec": "For each test case, print \"Yes\" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print \"No\".", "sample_inputs": ["4\n0 1 1 1\n8 1 9 3\n0 0 0 0\n1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["No\nYes\nYes\nYes"], "notes": "NoteIn the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.In the second test case, after doing one operation, changing $$$(8,1,9,3)$$$ to $$$(7,0,8,6)$$$, one of those possible palindromes may be \"rrrwwwbbbbrbbbbwwwrrr\".A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, \"rggbwbggr\", \"b\", \"gg\" are palindromes while \"rgbb\", \"gbbgr\" are not. Notice that an empty word, phrase, or sequence is palindrome."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.", "input_spec": "The first line of the input contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible total length of words in Andrew's article.", "sample_inputs": ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"], "sample_outputs": ["9", "6"], "notes": "NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}."}, "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": "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"}, {"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"} {"nl": {"description": "You are given a set $$$S$$$, which contains the first $$$n$$$ positive integers: $$$1, 2, \\ldots, n$$$.You can perform the following operation on $$$S$$$ any number of times (possibly zero): Choose a positive integer $$$k$$$ where $$$1 \\le k \\le n$$$, such that there exists a multiple of $$$k$$$ in $$$S$$$. Then, delete the smallest multiple of $$$k$$$ from $$$S$$$. This operation requires a cost of $$$k$$$. You are given a set $$$T$$$, which is a subset of $$$S$$$. Find the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$. We can show that such a transformation is always possible.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line contains a single positive integer $$$n$$$ ($$$1 \\le n \\le 10^6$$$). The second line of each test case contains a binary string of length $$$n$$$, describing the set $$$T$$$. The $$$i$$$-th character of the string is '1' if and only if $$$i$$$ is an element of $$$T$$$, and '0' otherwise. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. ", "output_spec": "For each test case, output one non-negative integer\u00a0\u2014 the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$.", "sample_inputs": ["6\n\n6\n\n111111\n\n7\n\n1101001\n\n4\n\n0000\n\n4\n\n0010\n\n8\n\n10010101\n\n15\n\n110011100101100"], "sample_outputs": ["0\n11\n4\n4\n17\n60"], "notes": "NoteIn the first test case, we shall not perform any operations as $$$S$$$ is already equal to $$$T$$$, which is the set $$$\\{1, 2, 3, 4, 5, 6\\}$$$.In the second test case, initially, $$$S = \\{1, 2, 3, 4, 5, 6, 7\\}$$$, and $$$T = \\{1, 2, 4, 7\\}$$$. We shall perform the following operations: Choose $$$k=3$$$, then delete $$$3$$$ from $$$S$$$. Choose $$$k=3$$$, then delete $$$6$$$ from $$$S$$$. Choose $$$k=5$$$, then delete $$$5$$$ from $$$S$$$. The total cost is $$$3+3+5 = 11$$$. It can be shown that this is the smallest cost possible.In the third test case, initially, $$$S = \\{1, 2, 3, 4\\}$$$ and $$$T = \\{\\}$$$ (empty set). We shall perform $$$4$$$ operations of $$$k=1$$$ to delete $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$.In the fourth test case, initially, $$$S = \\{1, 2, 3, 4\\}$$$ and $$$T = \\{3\\}$$$. We shall perform two operations with $$$k=1$$$ to delete $$$1$$$ and $$$2$$$, then perform one operation with $$$k=2$$$ to delete $$$4$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * @author zhuxi\r\n * @since 2022/9/28 11:11\r\n * @note\r\n * 1734C. Removing Smallest Multiples | \u96be\u5ea6\uff1a1200\r\n */\r\nobject Solution1734C {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n for (_ <- 0 until t) {\r\n val n = StdIn.readInt()\r\n val visit = new Array[Boolean](n + 1)\r\n val str = StdIn.readLine()\r\n var res = 0L\r\n for (i <- 1 to n) {\r\n var break = false\r\n for (j <- i to n by i if !break) {\r\n if (str(j - 1) == '1') break = true\r\n else if (!visit(j)) {\r\n visit(j) = true\r\n res += i\r\n }\r\n }\r\n }\r\n println(res)\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 11:11\r\n * @note\r\n * 1734C. Removing Smallest Multiples | \u96be\u5ea6\uff1a1200\r\n */\r\nobject Solution1734C {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n for (_ <- 0 until t) {\r\n val n = StdIn.readInt()\r\n val visit = new Array[Boolean](n + 1)\r\n val str = StdIn.readLine()\r\n var res = 0\r\n for (i <- 1 to n) {\r\n var break = false\r\n for (j <- i to n by i if !break) {\r\n if (str(j - 1) == '1') break = true\r\n else if (!visit(j)) {\r\n visit(j) = true\r\n res += i\r\n }\r\n }\r\n }\r\n println(res)\r\n }\r\n }\r\n}"}], "src_uid": "28277036765f76f20c327ab2fda6c43b"} {"nl": {"description": "Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi,\u2009j items in the basket. Vasya knows that: the cashier needs 5 seconds to scan one item; after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of cashes in the shop. The second line contains n space-separated integers: k1,\u2009k2,\u2009...,\u2009kn (1\u2009\u2264\u2009ki\u2009\u2264\u2009100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi,\u20091,\u2009mi,\u20092,\u2009...,\u2009mi,\u2009ki (1\u2009\u2264\u2009mi,\u2009j\u2009\u2264\u2009100)\u00a0\u2014 the number of products the j-th person in the queue for the i-th cash has.", "output_spec": "Print a single integer \u2014 the minimum number of seconds Vasya needs to get to the cashier.", "sample_inputs": ["1\n1\n1", "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8"], "sample_outputs": ["20", "100"], "notes": "NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100\u00b75\u2009+\u200915\u2009=\u2009515 seconds. But if he chooses the second queue, he will need 1\u00b75\u2009+\u20092\u00b75\u2009+\u20092\u00b75\u2009+\u20093\u00b75\u2009+\u20094\u00b715\u2009=\u2009100 seconds. He will need 1\u00b75\u2009+\u20099\u00b75\u2009+\u20091\u00b75\u2009+\u20093\u00b715\u2009=\u2009100 seconds for the third one and 7\u00b75\u2009+\u20098\u00b75\u2009+\u20092\u00b715\u2009=\u2009105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue."}, "positive_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.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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x,\u2009y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0,\u2009y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0,\u2009y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. ", "input_spec": "The first line contains three integers n, x0 \u0438 y0 (1\u2009\u2264\u2009n\u2009\u2264\u20091000, \u2009-\u2009104\u2009\u2264\u2009x0,\u2009y0\u2009\u2264\u2009104) \u2014 the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi (\u2009-\u2009104\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009104) \u2014 the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.", "output_spec": "Print a single integer \u2014 the minimum number of shots Han Solo needs to destroy all the stormtroopers. ", "sample_inputs": ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"], "sample_outputs": ["2", "1"], "notes": "NoteExplanation to the first and second samples from the statement, respectively: "}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Valentin participates in a show called \"Shockers\". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of actions Valentin did. The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types: Valentin pronounced some word and didn't get an electric shock. This action is described by the string \". w\" (without quotes), in which \".\" is a dot (ASCII-code 46), and w is the word that Valentin said. Valentin pronounced some word and got an electric shock. This action is described by the string \"! w\" (without quotes), in which \"!\" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said. Valentin made a guess about the selected letter. This action is described by the string \"? s\" (without quotes), in which \"?\" is a question mark (ASCII-code 63), and s is the guess\u00a0\u2014 a lowercase English letter. All words consist only of lowercase English letters. The total length of all words does not exceed 105. It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.", "output_spec": "Output a single integer\u00a0\u2014 the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.", "sample_inputs": ["5\n! abc\n. ad\n. b\n! cd\n? c", "8\n! hello\n! codeforces\n? c\n. o\n? d\n? h\n. l\n? e", "7\n! ababahalamaha\n? a\n? b\n? a\n? b\n? a\n? h"], "sample_outputs": ["1", "2", "0"], "notes": "NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a,\u2009b,\u2009c. After the second action we can note that the selected letter is not a. Valentin tells word \"b\" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks."}, "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"}, {"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"}], "negative_code": [], "src_uid": "3583a9762191ee8f8c3c2a287cb1ec1d"} {"nl": {"description": "\u0412 \u0441\u0430\u043c\u043e\u043b\u0451\u0442\u0435 \u0435\u0441\u0442\u044c n \u0440\u044f\u0434\u043e\u0432 \u043c\u0435\u0441\u0442. \u0415\u0441\u043b\u0438 \u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c \u043d\u0430 \u0440\u044f\u0434\u044b \u0441\u0432\u0435\u0440\u0445\u0443, \u0442\u043e \u0432 \u043a\u0430\u0436\u0434\u043e\u043c \u0440\u044f\u0434\u0443 \u0435\u0441\u0442\u044c 3 \u043c\u0435\u0441\u0442\u0430 \u0441\u043b\u0435\u0432\u0430, \u0437\u0430\u0442\u0435\u043c \u043f\u0440\u043e\u0445\u043e\u0434 \u043c\u0435\u0436\u0434\u0443 \u0440\u044f\u0434\u0430\u043c\u0438, \u0437\u0430\u0442\u0435\u043c 4 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0445 \u043c\u0435\u0441\u0442\u0430, \u0437\u0430\u0442\u0435\u043c \u0435\u0449\u0451 \u043e\u0434\u0438\u043d \u043f\u0440\u043e\u0445\u043e\u0434 \u043c\u0435\u0436\u0434\u0443 \u0440\u044f\u0434\u0430\u043c\u0438, \u0430 \u0437\u0430\u0442\u0435\u043c \u0435\u0449\u0451 3 \u043c\u0435\u0441\u0442\u0430 \u0441\u043f\u0440\u0430\u0432\u0430.\u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043c\u0435\u0441\u0442\u0430 \u0443\u0436\u0435 \u0437\u0430\u043d\u044f\u0442\u044b \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u0430\u043c\u0438. \u0412\u0441\u0435\u0433\u043e \u0435\u0441\u0442\u044c \u0434\u0432\u0430 \u0432\u0438\u0434\u0430 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432 \u2014 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0435 (\u0442\u0435, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0447\u0430\u0441\u0442\u043e \u043b\u0435\u0442\u0430\u044e\u0442) \u0438 \u043e\u0431\u044b\u0447\u043d\u044b\u0435. \u041f\u0435\u0440\u0435\u0434 \u0432\u0430\u043c\u0438 \u0441\u0442\u043e\u0438\u0442 \u0437\u0430\u0434\u0430\u0447\u0430 \u0440\u0430\u0441\u0441\u0430\u0434\u0438\u0442\u044c \u0435\u0449\u0451 k \u043e\u0431\u044b\u0447\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432 \u0442\u0430\u043a, \u0447\u0442\u043e\u0431\u044b \u0441\u0443\u043c\u043c\u0430\u0440\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0443 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432 \u0431\u044b\u043b\u043e \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b\u043c. \u0414\u0432\u0430 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u0430 \u0441\u0447\u0438\u0442\u0430\u044e\u0442\u0441\u044f \u0441\u043e\u0441\u0435\u0434\u044f\u043c\u0438, \u0435\u0441\u043b\u0438 \u043e\u043d\u0438 \u0441\u0438\u0434\u044f\u0442 \u0432 \u043e\u0434\u043d\u043e\u043c \u0440\u044f\u0434\u0443 \u0438 \u043c\u0435\u0436\u0434\u0443 \u043d\u0438\u043c\u0438 \u043d\u0435\u0442 \u0434\u0440\u0443\u0433\u0438\u0445 \u043c\u0435\u0441\u0442 \u0438 \u043f\u0440\u043e\u0445\u043e\u0434\u0430 \u043c\u0435\u0436\u0434\u0443 \u0440\u044f\u0434\u0430\u043c\u0438. \u0415\u0441\u043b\u0438 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0441\u043e\u0441\u0435\u0434\u043d\u0438\u043c \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u043c \u0434\u043b\u044f \u0434\u0432\u0443\u0445 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u0442\u043e \u0435\u0433\u043e \u0441\u043b\u0435\u0434\u0443\u0435\u0442 \u0443\u0447\u0438\u0442\u044b\u0432\u0430\u0442\u044c \u0432 \u0441\u0443\u043c\u043c\u0435 \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0434\u0432\u0430\u0436\u0434\u044b.", "input_spec": "\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043b\u0435\u0434\u0443\u044e\u0442 \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u200910\u00b7n) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0440\u044f\u0434\u043e\u0432 \u043c\u0435\u0441\u0442 \u0432 \u0441\u0430\u043c\u043e\u043b\u0451\u0442\u0435 \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0443\u0436\u043d\u043e \u0440\u0430\u0441\u0441\u0430\u0434\u0438\u0442\u044c. \u0414\u0430\u043b\u0435\u0435 \u0441\u043b\u0435\u0434\u0443\u0435\u0442 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0440\u044f\u0434\u043e\u0432 \u043c\u0435\u0441\u0442 \u0441\u0430\u043c\u043e\u043b\u0451\u0442\u0430 \u043f\u043e \u043e\u0434\u043d\u043e\u043c\u0443 \u0440\u044f\u0434\u0443 \u0432 \u0441\u0442\u0440\u043e\u043a\u0435. \u0415\u0441\u043b\u0438 \u043e\u0447\u0435\u0440\u0435\u0434\u043d\u043e\u0439 \u0441\u0438\u043c\u0432\u043e\u043b \u0440\u0430\u0432\u0435\u043d '-', \u0442\u043e \u044d\u0442\u043e \u043f\u0440\u043e\u0445\u043e\u0434 \u043c\u0435\u0436\u0434\u0443 \u0440\u044f\u0434\u0430\u043c\u0438. \u0415\u0441\u043b\u0438 \u043e\u0447\u0435\u0440\u0435\u0434\u043d\u043e\u0439 \u0441\u0438\u043c\u0432\u043e\u043b \u0440\u0430\u0432\u0435\u043d '.', \u0442\u043e \u044d\u0442\u043e \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u043e\u0435 \u043c\u0435\u0441\u0442\u043e. \u0415\u0441\u043b\u0438 \u043e\u0447\u0435\u0440\u0435\u0434\u043d\u043e\u0439 \u0441\u0438\u043c\u0432\u043e\u043b \u0440\u0430\u0432\u0435\u043d 'S', \u0442\u043e \u043d\u0430 \u0442\u0435\u043a\u0443\u0449\u0435\u043c \u043c\u0435\u0441\u0442\u0435 \u0431\u0443\u0434\u0435\u0442 \u0441\u0438\u0434\u0435\u0442\u044c \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0439 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440. \u0415\u0441\u043b\u0438 \u043e\u0447\u0435\u0440\u0435\u0434\u043d\u043e\u0439 \u0441\u0438\u043c\u0432\u043e\u043b \u0440\u0430\u0432\u0435\u043d 'P', \u0442\u043e \u043d\u0430 \u0442\u0435\u043a\u0443\u0449\u0435\u043c \u043c\u0435\u0441\u0442\u0435 \u0431\u0443\u0434\u0435\u0442 \u0441\u0438\u0434\u0435\u0442\u044c \u043e\u0431\u044b\u0447\u043d\u044b\u0439 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u044b\u0445 \u043c\u0435\u0441\u0442 \u043d\u0435 \u043c\u0435\u043d\u044c\u0448\u0435 k. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 \u0440\u044f\u0434\u044b \u0443\u0434\u043e\u0432\u043b\u0435\u0442\u0432\u043e\u0440\u044f\u044e\u0442 \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u043e\u043c\u0443 \u0432 \u0443\u0441\u043b\u043e\u0432\u0438\u0438 \u0444\u043e\u0440\u043c\u0430\u0442\u0443.", "output_spec": "\u0412 \u043f\u0435\u0440\u0432\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0441\u0443\u043c\u043c\u0430\u0440\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0443 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432. \u0414\u0430\u043b\u0435\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043f\u043b\u0430\u043d \u0440\u0430\u0441\u0441\u0430\u0434\u043a\u0438 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043c\u0438\u043d\u0438\u043c\u0438\u0437\u0438\u0440\u0443\u0435\u0442 \u0441\u0443\u043c\u043c\u0430\u0440\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0443 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u0432 \u0442\u043e\u043c \u0436\u0435 \u0444\u043e\u0440\u043c\u0430\u0442\u0435, \u0447\u0442\u043e \u0438 \u0432\u043e \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445. \u0415\u0441\u043b\u0438 \u0432 \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u043e\u0435 \u043c\u0435\u0441\u0442\u043e \u043d\u0443\u0436\u043d\u043e \u043f\u043e\u0441\u0430\u0434\u0438\u0442\u044c \u043e\u0434\u043d\u043e\u0433\u043e \u0438\u0437 k \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u0442\u0440\u043e\u0447\u043d\u0443\u044e \u0431\u0443\u043a\u0432\u0443 'x' \u0432\u043c\u0435\u0441\u0442\u043e \u0441\u0438\u043c\u0432\u043e\u043b\u0430 '.'. ", "sample_inputs": ["1 2\nSP.-SS.S-S.S", "4 9\nPP.-PPPS-S.S\nPSP-PPSP-.S.\n.S.-S..P-SS.\nP.S-P.PP-PSP"], "sample_outputs": ["5\nSPx-SSxS-S.S", "15\nPPx-PPPS-S.S\nPSP-PPSP-xSx\nxSx-SxxP-SSx\nP.S-PxPP-PSP"], "notes": "\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u043d\u0443\u0436\u043d\u043e \u043f\u043e\u0441\u0430\u0434\u0438\u0442\u044c \u0435\u0449\u0451 \u0434\u0432\u0443\u0445 \u043e\u0431\u044b\u0447\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432. \u0414\u043b\u044f \u043c\u0438\u043d\u0438\u043c\u0438\u0437\u0430\u0446\u0438\u0438 \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0443 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u043d\u0443\u0436\u043d\u043e \u043f\u043e\u0441\u0430\u0434\u0438\u0442\u044c \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u0438\u0437 \u043d\u0438\u0445 \u043d\u0430 \u0442\u0440\u0435\u0442\u044c\u0435 \u0441\u043b\u0435\u0432\u0430 \u043c\u0435\u0441\u0442\u043e, \u0430 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u043d\u0430 \u043b\u044e\u0431\u043e\u0435 \u0438\u0437 \u043e\u0441\u0442\u0430\u0432\u0448\u0438\u0445\u0441\u044f \u0434\u0432\u0443\u0445 \u043c\u0435\u0441\u0442, \u0442\u0430\u043a \u043a\u0430\u043a \u043d\u0435\u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e \u043e\u0442 \u0432\u044b\u0431\u043e\u0440\u0430 \u043c\u0435\u0441\u0442\u0430 \u043e\u043d \u0441\u0442\u0430\u043d\u0435\u0442 \u0441\u043e\u0441\u0435\u0434\u043e\u043c \u0434\u0432\u0443\u0445 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432. \u0418\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e, \u0443 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u043e\u0433\u043e \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u0430, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0441\u0438\u0434\u0438\u0442 \u043d\u0430 \u0441\u0430\u043c\u043e\u043c \u043b\u0435\u0432\u043e\u043c \u043c\u0435\u0441\u0442\u0435 \u0443\u0436\u0435 \u0435\u0441\u0442\u044c \u0441\u043e\u0441\u0435\u0434. \u0422\u0430\u043a\u0436\u0435 \u043d\u0430 \u0447\u0435\u0442\u0432\u0451\u0440\u0442\u043e\u043c \u0438 \u043f\u044f\u0442\u043e\u043c \u043c\u0435\u0441\u0442\u0430\u0445 \u0441\u043b\u0435\u0432\u0430 \u0441\u0438\u0434\u044f\u0442 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0435 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u044b, \u044f\u0432\u043b\u044f\u044e\u0449\u0438\u0435\u0441\u044f \u0441\u043e\u0441\u0435\u0434\u044f\u043c\u0438 \u0434\u0440\u0443\u0433 \u0434\u043b\u044f \u0434\u0440\u0443\u0433\u0430 (\u0447\u0442\u043e \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u0442 \u043a \u0441\u0443\u043c\u043c\u0435 2).\u0422\u0430\u043a\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c, \u043f\u043e\u0441\u043b\u0435 \u043f\u043e\u0441\u0430\u0434\u043a\u0438 \u0435\u0449\u0451 \u0434\u0432\u0443\u0445 \u043e\u0431\u044b\u0447\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432, \u0438\u0442\u043e\u0433\u043e\u0432\u043e\u0435 \u0441\u0443\u043c\u043c\u0430\u0440\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u043e\u0441\u0435\u0434\u0435\u0439 \u0443 \u0441\u0442\u0430\u0442\u0443\u0441\u043d\u044b\u0445 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u043e\u0432 \u0441\u0442\u0430\u043d\u0435\u0442 \u0440\u0430\u0432\u043d\u043e \u043f\u044f\u0442\u0438."}, "positive_code": [{"source_code": "object CF928A extends App {\nval sc = new java.util.Scanner(System.in)\nval n: Int = sc.nextInt()\nval k: Int = sc.nextInt()\nsc.nextLine()\nval planOfAirplan: List[String] = (1 to n).toList.foldLeft(List.empty[String]){case (list, _) => list :+ sc.nextLine()}\ndef findCountOfPlacesAtTheLineFirstStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if(current == '.' && next != 'S' && previos != 'S') 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n val first = if ((line.startsWith(\".P\") || line.startsWith(\"..\")) && countAtAll < k) 1 else 0\n val second = if ((line.endsWith(\"P.\") || line.endsWith(\"..\")) && countAtAll + first < k) 1 else 0\n countInLine(line match {\n case _ if first == 1 && second == 1 => line.replaceFirst(\"^\\\\.P\", \"xP\").replaceFirst(\"P\\\\.$\", \"Px\").replaceFirst(\"^\\\\.\\\\.\", \"x.\").replaceFirst(\"\\\\.\\\\.$\", \".x\")\n case _ if first == 1 => line.replaceFirst(\"^\\\\.P\", \"xP\").replaceFirst(\"^\\\\.\\\\.\", \"x.\")\n case _ if second == 1 => line.replaceFirst(\"P\\\\.$\", \"Px\").replaceFirst(\"\\\\.\\\\.$\", \".x\")\n case _ => line\n }, count = first + second)\n} else (0, line)\ndef findCountOfPlacesAtTheLineSecondStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next != previos && (next == 'S' || previos == 'S')) 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n val first = if (line.startsWith(\".S\") && countAtAll < k) 1 else 0\n val second = if (line.endsWith(\"S.\") && countAtAll + first < k) 1 else 0\n countInLine(line match {\n case _ if first == 1 && second == 1 => line.replaceFirst(\"^\\\\.S\", \"xS\").replaceFirst(\"S\\\\.$\", \"Sx\")\n case _ if first == 1 => line.replaceFirst(\"^\\\\.S\", \"xS\")\n case _ if second == 1 => line.replaceFirst(\"S\\\\.$\", \"Sx\")\n case _ => line\n }, count = first + second)\n} else (0, line)\ndef findCountOfPlacesAtTheLineThirdStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next == 'S' && previos == 'S') 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n countInLine(line)\n} else (0, line)\ndef findCountOfPlacesAtTheLinFinalStage(line: String): Int = if (line.contains('P') || line.contains('x') || line.contains('S')) {\n def isNeeded(previos: Char, current: Char, next: Char): Int = if ((current != '.' && current != '-') && (previos == 'S' || next == 'S')) if (previos == next) 2 else 1 else 0\n def countInLine(currentString: String, count: Int = 0): Int = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty) {\n countInLine(tail, count + isNeeded(currentString.head, tail.head, tailTail.head))\n } else count\n }\n val head = line.head\n val last = line.last\n countInLine(line) + (if (head != '.' && head != '-' && line.tail.head == 'S') 1 else 0) + (if (last != '.' && last != '-' && line.init.last == 'S') 1 else 0)\n} else 0\nval firstResult = planOfAirplan.foldLeft((0, List.empty[String])){(tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineFirstStage(line, tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n}\nval fullResult = if (firstResult._1 < k) {\n val secondResult = firstResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineSecondStage(line, firstResult._1 + tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n if (secondResult._1 < k)\n secondResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineThirdStage(line, firstResult._1 + secondResult._1 + tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n else\n secondResult\n} else {\n firstResult\n}\nval result = fullResult._2.map(findCountOfPlacesAtTheLinFinalStage).sum\nprintln(result)\nfullResult._2.map(println)\n}"}], "negative_code": [{"source_code": "object CF928A extends App {\n val sc = new java.util.Scanner(System.in)\n val n: Int = sc.nextInt()\n val k: Int = sc.nextInt()\n sc.nextLine()\n val planOfAirplan: List[String] = (1 to n).toList.foldLeft(List.empty[String]){case (list, _) => list :+ sc.nextLine()}\n def findCountOfPlacesAtTheLineFirstStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if(current == '.' && next != 'S' && previos != 'S') 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n val res = countInLine(line.replaceFirst(\"^\\\\.P\", \"xP\").replaceFirst(\"P\\\\.$\", \"Px\"))\n res.copy(_1 = res._1 + (if (line.startsWith(\".P\")) 1 else 0) + (if (line.endsWith(\"P.\")) 1 else 0))\n } else (0, line)\n def findCountOfPlacesAtTheLineSecondStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next != previos && (next == 'S' || previos == 'S')) 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n val res = countInLine(line.replaceFirst(\"^\\\\.S\", \"xS\").replaceFirst(\"S\\\\.$\", \"Sx\"))\n res.copy(_1 = res._1 + (if (line.startsWith(\".S\")) 1 else 0) + (if (line.endsWith(\"S.\")) 1 else 0))\n } else (0, line)\n def findCountOfPlacesAtTheLineThirdStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next == 'S' && previos == 'S') 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n countInLine(line)\n } else (0, line)\n def findCountOfPlacesAtTheLinFinalStage(line: String): Int = if (line.contains('P') || line.contains('x') || line.contains('S')) {\n def isNeeded(previos: Char, current: Char, next: Char): Int = if ((current != '.' && current != '-') && (previos == 'S' || next == 'S')) if (previos == next) 2 else 1 else 0\n def countInLine(currentString: String, count: Int = 0): Int = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty) {\n countInLine(tail, count + isNeeded(currentString.head, tail.head, tailTail.head))\n } else count\n }\n val head = line.head\n val last = line.last\n countInLine(line) + (if (head != '.' && head != '-' && line.tail.head != '.' && line.tail.head == 'S') 1 else 0) + (if (last != '.' && last != '-' && line.init.last != '.' && line.init.last == 'S') 1 else 0)\n } else 0\n val firstResult = planOfAirplan.foldLeft((0, List.empty[String])){(tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineFirstStage(line, tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n val fullResult = if (firstResult._1 < k) {\n val secondResult = firstResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineSecondStage(line, firstResult._1 + tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n if (secondResult._1 < k)\n secondResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineThirdStage(line, firstResult._1 + secondResult._1 + tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n else \n secondResult\n } else {\n firstResult\n }\n val result = fullResult._2.map(findCountOfPlacesAtTheLinFinalStage).sum\n println(result)\n fullResult._2.map(println)\n}"}, {"source_code": "object CF928A extends App {\nval sc = new java.util.Scanner(System.in)\nval n: Int = sc.nextInt()\nval k: Int = sc.nextInt()\nsc.nextLine()\nval planOfAirplan: List[String] = (1 to n).toList.foldLeft(List.empty[String]){case (list, _) => list :+ sc.nextLine()}\ndef findCountOfPlacesAtTheLineFirstStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if(current == '.' && next != 'S' && previos != 'S') 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n val first = if (line.startsWith(\".P\") && countAtAll < k) 1 else 0\n val second = if (line.endsWith(\"P.\") && countAtAll + first < k) 1 else 0\n countInLine(line match {\n case _ if first == 1 && second == 1 => line.replaceFirst(\"^\\\\.P\", \"xP\").replaceFirst(\"P\\\\.$\", \"Px\")\n case _ if first == 1 => line.replaceFirst(\"^\\\\.P\", \"xP\")\n case _ if second == 1 => line.replaceFirst(\"P\\\\.$\", \"Px\")\n case _ => line\n }, count = first + second)\n} else (0, line)\ndef findCountOfPlacesAtTheLineSecondStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next != previos && (next == 'S' || previos == 'S')) 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n val first = if (line.startsWith(\".S\") && countAtAll < k) 1 else 0\n val second = if (line.endsWith(\"S.\") && countAtAll + first < k) 1 else 0\n countInLine(line match {\n case _ if first == 1 && second == 1 => line.replaceFirst(\"^\\\\.S\", \"xS\").replaceFirst(\"S\\\\.$\", \"Sx\")\n case _ if first == 1 => line.replaceFirst(\"^\\\\.S\", \"xS\")\n case _ if second == 1 => line.replaceFirst(\"S\\\\.$\", \"Sx\")\n case _ => line\n }, count = first + second)\n} else (0, line)\ndef findCountOfPlacesAtTheLineThirdStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {\n def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next == 'S' && previos == 'S') 1 else 0\n def countInLine(currentString: String, count: Int = 0, completedString: String = \"\"): (Int, String) = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty && count + countAtAll < k) {\n val head = currentString.head\n val tailHead = tail.head\n val isFreeResult = isFree(head, tailHead, tailTail.head)\n countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)\n } else (count, completedString + currentString)\n }\n countInLine(line)\n} else (0, line)\ndef findCountOfPlacesAtTheLinFinalStage(line: String): Int = if (line.contains('P') || line.contains('x') || line.contains('S')) {\n def isNeeded(previos: Char, current: Char, next: Char): Int = if ((current != '.' && current != '-') && (previos == 'S' || next == 'S')) if (previos == next) 2 else 1 else 0\n def countInLine(currentString: String, count: Int = 0): Int = {\n val tail = currentString.tail\n val tailTail = tail.tail\n if (tailTail.nonEmpty) {\n countInLine(tail, count + isNeeded(currentString.head, tail.head, tailTail.head))\n } else count\n }\n val head = line.head\n val last = line.last\n countInLine(line) + (if (head != '.' && head != '-' && line.tail.head != '.' && line.tail.head == 'S') 1 else 0) + (if (last != '.' && last != '-' && line.init.last != '.' && line.init.last == 'S') 1 else 0)\n} else 0\nval firstResult = planOfAirplan.foldLeft((0, List.empty[String])){(tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineFirstStage(line, tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n}\nval fullResult = if (firstResult._1 < k) {\n val secondResult = firstResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineSecondStage(line, firstResult._1 + tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n if (secondResult._1 < k)\n secondResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>\n val tupOld = findCountOfPlacesAtTheLineThirdStage(line, firstResult._1 + secondResult._1 + tupNew._1)\n (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)\n }\n else\n secondResult\n} else {\n firstResult\n}\nval result = fullResult._2.map(findCountOfPlacesAtTheLinFinalStage).sum\nprintln(result)\nfullResult._2.map(println)\n}"}], "src_uid": "4f45c5fd31e500c1128cf6cb5e41e3d6"} {"nl": {"description": "You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \\le k < m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n, m \\le 5 \\cdot 10^5$$$; $$$n \\cdot m \\le 10^6$$$)\u00a0\u2014 the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \\dots, a_{im}$$$ ($$$1 \\le a_{ij} \\le 10^6$$$). The sum of $$$n \\cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.", "output_spec": "For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print \"NO\". Otherwise, first, print \"YES\". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \\le k < m$$$)\u00a0\u2014 the number of columns from the left that are cut.", "sample_inputs": ["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"], "sample_outputs": ["YES\nBRBRB 1\nNO\nYES\nRB 3"], "notes": "NoteThe coloring and the cut for the first testcase: "}, "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 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 = 998244353\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 m = readInt()\n val arr = Array.ofDim[Int](n+1, m+1)\n val lmin = Array.ofDim[Int](n+1, m+2)\n val lmax = Array.ofDim[Int](n+1, m+2)\n val rmin = Array.ofDim[Int](n+1, m+2)\n val rmax = Array.ofDim[Int](n+1, m+2)\n for (i <- 1 to n){\n lmin(i)(0) = 1000000\n lmax(i)(0) = 1\n for (j <- 1 to m) {\n arr(i)(j) = readInt()\n lmin(i)(j) = min(lmin(i)(j-1), arr(i)(j))\n lmax(i)(j) = max(lmax(i)(j-1), arr(i)(j))\n }\n }\n for (i <- 1 to n) {\n rmin(i)(m+1) = 1000000\n rmax(i)(m+1) = 1\n for (j <- (1 to m).reverse) {\n rmin(i)(j) = min(rmin(i)(j+1), arr(i)(j))\n rmax(i)(j) = max(rmax(i)(j+1), arr(i)(j))\n }\n }\n var ans = -1\n var col = new Array[Char](n+1)\n var j = 1\n while (j < m && ans == -1) {\n val rows = new Array[pair](n)\n for (i <- 1 to n) {\n rows(i-1) = pair(lmin(i)(j), lmax(i)(j), rmin(i)(j+1), rmax(i)(j+1), i)\n }\n quickSort(rows)\n val minr = new Array[Int](n+1)\n val maxr = new Array[Int](n+1)\n maxr(n) = 0\n for (i <- (0 to n-1).reverse)\n maxr(i) = max(maxr(i+1), rows(i).maxr)\n var close = 0\n var i = 0\n while (i < n-1 && ans == -1) {\n if (i == 0)\n minr(i) = rows(i).minr\n else\n minr(i) = min(minr(i-1), rows(i).minr)\n close = max(close, rows(i).maxl)\n if (close < rows(i+1).minl) {\n if (maxr(i+1) < minr(i)) {\n ans = j\n for (k <- 0 to i)\n col(rows(k).ind) = 'B'\n for (k <- i+1 to n-1)\n col(rows(k).ind) = 'R'\n }\n }\n i += 1\n }\n j += 1\n }\n if (ans == -1) {\n writer.println(\"NO\")\n } else {\n writer.println(\"YES\")\n for (i <- 1 to n)\n writer.print(col(i))\n writer.println(\" \" + ans)\n }\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "10751c875f4d7667ba21685c57cddd9e"} {"nl": {"description": "A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a\u2009\u2264\u2009b, he or she likes it if and only if he can climb into this car and 2a\u2009\u2265\u2009b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.", "input_spec": "You are given four integers V1, V2, V3, Vm(1\u2009\u2264\u2009Vi\u2009\u2264\u2009100)\u00a0\u2014 sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1\u2009>\u2009V2\u2009>\u2009V3.", "output_spec": "Output three integers\u00a0\u2014 sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print \"-1\" (without quotes).", "sample_inputs": ["50 30 10 10", "100 50 10 21"], "sample_outputs": ["50\n30\n10", "-1"], "notes": "NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20."}, "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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \\le x \\le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print \"-1\" (without quotes).", "input_spec": "The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k \\le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the sequence itself.", "output_spec": "Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print \"-1\" (without quotes).", "sample_inputs": ["7 4\n3 7 5 1 10 3 20", "7 2\n3 7 5 1 10 3 20"], "sample_outputs": ["6", "-1"], "notes": "NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number."}, "positive_code": [{"source_code": "object Problem_977C {\n // Less or Equal\n // The first line of the input contains integer numbers n and k (1\u2264n\u22642\u22c5105, 0\u2264k\u2264n).\n // The second line of the input contains n integer numbers a1,a2,\u2026,an (1\u2264ai\u2264109) \u2014 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"}, {"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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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": "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"}, {"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"}], "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\u2264n\u22642\u22c5105, 0\u2264k\u2264n).\n // The second line of the input contains n integer numbers a1,a2,\u2026,an (1\u2264ai\u2264109) \u2014 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\u2264n\u22642\u22c5105, 0\u2264k\u2264n).\n // The second line of the input contains n integer numbers a1,a2,\u2026,an (1\u2264ai\u2264109) \u2014 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string si\u00a0\u2014 the name of the i-th polyhedron in Anton's collection. The string can look like this: \"Tetrahedron\" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. \"Cube\" (without quotes), if the i-th polyhedron in Anton's collection is a cube. \"Octahedron\" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. \"Dodecahedron\" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. \"Icosahedron\" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron. ", "output_spec": "Output one number\u00a0\u2014 the total number of faces in all the polyhedrons in Anton's collection.", "sample_inputs": ["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"], "sample_outputs": ["42", "28"], "notes": "NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20\u2009+\u20096\u2009+\u20094\u2009+\u200912\u2009=\u200942 faces."}, "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": "\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"}, {"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"} {"nl": {"description": "There are $$$n$$$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The value of the line is the sum of each person's count.For example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are $$$[0, 3, 2, 3, 4]$$$, and the value is $$$0+3+2+3+4=12$$$.You are given the initial arrangement of people in the line. For each $$$k$$$ from $$$1$$$ to $$$n$$$, determine the maximum value of the line if you can change the direction of at most $$$k$$$ people.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2\\cdot10^5$$$)\u00a0\u2014 the length of the line. The following line contains a string consisting of $$$n$$$ characters, each of which is either L or R, representing a person facing left or right, respectively\u00a0\u2014 the description of the line. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot10^5$$$. Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).", "output_spec": "For each test case, output $$$n$$$ space-separated non-negative integers\u00a0\u2014 the maximum value of the line if you can change the direction of at most $$$k$$$ people for each $$$k$$$ from $$$1$$$ to $$$n$$$, inclusive.", "sample_inputs": ["6\n\n3\n\nLLR\n\n5\n\nLRRLL\n\n1\n\nL\n\n12\n\nLRRRLLLRLLRL\n\n10\n\nLLLLLRRRRR\n\n9\n\nLRLRLRLRL"], "sample_outputs": ["3 5 5 \n16 16 16 16 16 \n0 \n86 95 98 101 102 102 102 102 102 102 102 102 \n29 38 45 52 57 62 65 68 69 70 \n44 50 54 56 56 56 56 56 56"], "notes": "NoteIn the first test case: $$$k=1$$$: change the direction of $$$1$$$ person to make the line RLR. The total value is $$$2+1+0=3$$$. $$$k=2$$$: change the direction of $$$2$$$ people to make the line RLL. The total value is $$$2+1+2=5$$$. $$$k=3$$$: change the direction of $$$2$$$ people to make the line RLL. The total value is $$$2+1+2=5$$$. Note that you have to change the direction of at most $$$k$$$ people. In the second test case, it is optimal to only change the direction of the first person for all $$$k$$$ from $$$1$$$ to $$$5$$$ (that is, make the line RRRLL)."}, "positive_code": [{"source_code": "object _1722D 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, s) = io.read[(Int, String)]\n val score = (s.zipWithIndex map {\n case ('L', i) => i.toLong\n case ('R', i) => (n-i-1).toLong\n case _ => 0L\n }).sum\n\n val ans = (s.zipWithIndex map {\n case ('L', i) => (i max (n - i - 1)) - i.toLong\n case ('R', i) => (i max (n - i - 1)) - (n - i - 1).toLong\n case _ => 0L\n }).sorted(desc[Long])\n .scanLeft(score)({case (x, y) => x + y})\n .tail\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 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": "f0402399cbaf8997993ac2ee59a60696"} {"nl": {"description": "Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1,\u2009x2,\u2009...,\u2009xk (k\u2009>\u20091) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1,\u2009x2,\u2009...,\u2009xk (k\u2009>\u20091) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1,\u2009s2,\u2009...,\u2009sn (n\u2009>\u20091). Let's denote sequence sl,\u2009sl\u2009+\u20091,\u2009...,\u2009sr as s[l..r] (1\u2009\u2264\u2009l\u2009<\u2009r\u2009\u2264\u2009n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence.", "input_spec": "The first line contains integer n (1\u2009<\u2009n\u2009\u2264\u2009105). The second line contains n distinct integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the maximum lucky number among all lucky numbers of sequences s[l..r].", "sample_inputs": ["5\n5 2 1 4 3", "5\n9 8 3 5 7"], "sample_outputs": ["7", "15"], "notes": "NoteFor the first sample you can choose s[4..5]\u2009=\u2009{4,\u20093} and its lucky number is (4\u00a0xor\u00a03)\u2009=\u20097. You can also choose s[1..2].For the second sample you must choose s[2..5]\u2009=\u2009{8,\u20093,\u20095,\u20097}."}, "positive_code": [{"source_code": "import java.util._;\n\nobject Solution {\n def main(args : Array[String]) = {\n val sc = new Scanner(System.in)\n val n = sc.nextInt()\n val st = new Stack[Integer]()\n val vals = new Array[Integer](n)\n var ans = 0\n for(i <- 0 until n) {\n vals(i) = sc.nextInt()\n while(!st.empty() && st.peek() < vals(i))\n ans = Math.max(ans, st.pop() ^ vals(i))\n st.push(vals(i))\n }\n st.clear()\n for(i <- n - 1 to 0 by -1) {\n while(!st.empty() && st.peek() < vals(i))\n ans = Math.max(ans, st.pop() ^ vals(i))\n st.push(vals(i))\n }\n println(ans)\n }\n}"}], "negative_code": [], "src_uid": "c9b9c56d50eaf605e7bc088385a42a1d"} {"nl": {"description": "Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.", "input_spec": "The first line of input contains integers n, k and m (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively. The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct. The third line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) where ai is the cost of sending the i-th word. The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1\u2009\u2264\u2009x\u2009\u2264\u2009n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group. The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.", "output_spec": "The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.", "sample_inputs": ["5 4 4\ni loser am the second\n100 1 1 5 10\n1 1\n1 3\n2 2 5\n1 4\ni am the second", "5 4 4\ni loser am the second\n100 20 1 5 10\n1 1\n1 3\n2 2 5\n1 4\ni am the second"], "sample_outputs": ["107", "116"], "notes": "NoteIn the first sample, Mahmoud should replace the word \"second\" with the word \"loser\" because it has less cost so the cost will be 100+1+5+1=107.In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116."}, "positive_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[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}"}, {"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"} {"nl": {"description": "You are playing a computer game, where you lead a party of $$$m$$$ soldiers. Each soldier is characterised by his agility $$$a_i$$$.The level you are trying to get through can be represented as a straight line segment from point $$$0$$$ (where you and your squad is initially located) to point $$$n + 1$$$ (where the boss is located).The level is filled with $$$k$$$ traps. Each trap is represented by three numbers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$. $$$l_i$$$ is the location of the trap, and $$$d_i$$$ is the danger level of the trap: whenever a soldier with agility lower than $$$d_i$$$ steps on a trap (that is, moves to the point $$$l_i$$$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $$$r_i$$$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.You have $$$t$$$ seconds to complete the level \u2014 that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring all of the chosen soldiers to the boss. To do so, you may perform the following actions: if your location is $$$x$$$, you may move to $$$x + 1$$$ or $$$x - 1$$$. This action consumes one second; if your location is $$$x$$$ and the location of your squad is $$$x$$$, you may move to $$$x + 1$$$ or to $$$x - 1$$$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i.\u2009e. the point your squad is moving into contains a non-disarmed trap with $$$d_i$$$ greater than agility of some soldier from the squad). This action consumes one second; if your location is $$$x$$$ and there is a trap $$$i$$$ with $$$r_i = x$$$, you may disarm this trap. This action is done instantly (it consumes no time). Note that after each action both your coordinate and the coordinate of your squad should be integers.You have to choose the maximum number of soldiers such that they all can be brought from the point $$$0$$$ to the point $$$n + 1$$$ (where the boss waits) in no more than $$$t$$$ seconds.", "input_spec": "The first line contains four integers $$$m$$$, $$$n$$$, $$$k$$$ and $$$t$$$ ($$$1 \\le m, n, k, t \\le 2 \\cdot 10^5$$$, $$$n < t$$$) \u2014 the number of soldiers, the number of integer points between the squad and the boss, the number of traps and the maximum number of seconds you may spend to bring the squad to the boss, respectively. The second line contains $$$m$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$), where $$$a_i$$$ is the agility of the $$$i$$$-th soldier. Then $$$k$$$ lines follow, containing the descriptions of traps. Each line contains three numbers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$, $$$1 \\le d_i \\le 2 \\cdot 10^5$$$) \u2014 the location of the trap, the location where the trap can be disarmed, and its danger level, respectively.", "output_spec": "Print one integer \u2014 the maximum number of soldiers you may choose so that you may bring them all to the boss in no more than $$$t$$$ seconds.", "sample_inputs": ["5 6 4 14\n1 2 3 4 5\n1 5 2\n1 2 5\n2 3 5\n3 5 3"], "sample_outputs": ["3"], "notes": "NoteIn the first example you may take soldiers with agility $$$3$$$, $$$4$$$ and $$$5$$$ with you. The course of action is as follows: go to $$$2$$$ without your squad; disarm the trap $$$2$$$; go to $$$3$$$ without your squad; disartm the trap $$$3$$$; go to $$$0$$$ without your squad; go to $$$7$$$ with your squad. The whole plan can be executed in $$$13$$$ seconds."}, "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 /**\n * \u5358\u8abf\u6e1b\u5c11\n * [l, h) \u65b9\u5f0f\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\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 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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val m, n, k, t = ni()\n val A = na(m)\n sort(A)\n reverse(A)\n val open, close = Array.fill[ArrayBuffer[Int]](n + 1)(ArrayBuffer())\n REP(k) { _ =>\n val l, r, d = ni()\n open(l) += d\n close(r) += d\n }\n\n def test(num: Int): Boolean = {\n val agility = A(num - 1)\n var cnt = 0\n var balance = 0\n TO(1, n) { i =>\n REP(open(i).length) { j =>\n val d = open(i)(j)\n if (d > agility) balance += 1\n }\n\n if (balance > 0) cnt += 1\n\n REP(close(i).length) { j =>\n val d = close(i)(j)\n if (d > agility) balance -= 1\n }\n }\n t >= n + 1 + cnt * 2\n }\n\n val ans = findMax(test, 0, m)\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "14d158dd02d65096946445e14a5f210d"} {"nl": {"description": "Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print \"NO\".", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \\dots, a_{n^2}$$$ ($$$1 \\le a_i \\le 1000$$$) \u2014 the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.", "output_spec": "If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print \"YES\". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers \u2014 the resulting matrix. If it's impossible to construct any matrix, then print \"NO\". You can print each letter in any case (upper or lower). For example, \"YeS\", \"no\" and \"yES\" are all acceptable.", "sample_inputs": ["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"], "sample_outputs": ["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"], "notes": "NoteNote that there exist multiple answers for the first two examples."}, "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 g = Array.ofDim[Int](N, N)\n val A = na(N * N)\n val C = Array.ofDim[Int](1001)\n REP(A.length) { i =>\n C(A(i)) += 1\n }\n\n // 0 => 1, 1 => 2, 2 => 4\n val nums = Array.fill[mutable.Queue[Int]](3)(mutable.Queue())\n\n REP(C.length) { i =>\n while(C(i) >= 4) {\n C(i) -= 4\n nums(2) += i\n }\n\n while(C(i) >= 2) {\n C(i) -= 2\n nums(1) += i\n }\n\n while(C(i) >= 1) {\n C(i) -= 1\n nums(0) += i\n }\n }\n\n def claim(i: Int): Unit = {\n if (nums(i).isEmpty && i < 2) {\n claim(i + 1)\n if (nums(i + 1).nonEmpty) {\n val a = nums(i + 1).dequeue()\n REP(2) { _ => nums(i) += a }\n }\n }\n }\n\n case class Coord(r: Int, c: Int)\n\n def samePos(r: Int, c: Int): Array[Coord] = {\n val set = mutable.Set[Coord]()\n\n (for {\n rr <- Seq(r, N - 1 - r)\n cc <- Seq(c, N - 1 - c)\n } yield Coord(rr, cc)).toSet.toArray\n }\n\n def fillAll(i: Int, ps: Array[Coord]): Unit = {\n claim(i)\n if (nums(i).nonEmpty) {\n val a = nums(i).dequeue()\n REP(ps.length) { i =>\n g(ps(i).r)(ps(i).c) = a\n }\n }\n }\n\n def fill(r: Int, c: Int): Unit = {\n val ps = samePos(r, c)\n ps.length match {\n case 1 => fillAll(0, ps)\n case 2 => fillAll(1, ps)\n case 4 => fillAll(2, ps)\n }\n }\n\n REP(N) { r =>\n REP(N) { c =>\n if (g(r)(c) == 0) {\n fill(r, c)\n }\n }\n }\n\n val ok = g.forall(_.forall(_ != 0))\n if (!ok) out.println(\"NO\")\n else {\n out.println(\"YES\")\n REP(N) { r =>\n out.println(g(r).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 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": [], "src_uid": "20928dd8e512bee2d86c6611c5e76390"} {"nl": {"description": "Recently, your friend discovered one special operation on an integer array $$$a$$$: Choose two indices $$$i$$$ and $$$j$$$ ($$$i \\neq j$$$); Set $$$a_i = a_j = |a_i - a_j|$$$. After playing with this operation for a while, he came to the next conclusion: For every array $$$a$$$ of $$$n$$$ integers, where $$$1 \\le a_i \\le 10^9$$$, you can find a pair of indices $$$(i, j)$$$ such that the total sum of $$$a$$$ will decrease after performing the operation. This statement sounds fishy to you, so you want to find a counterexample for a given integer $$$n$$$. Can you find such counterexample and prove him wrong?In other words, find an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) such that for all pairs of indices $$$(i, j)$$$ performing the operation won't decrease the total sum (it will increase or not change the sum).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first and only line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 1000$$$)\u00a0\u2014 the length of array $$$a$$$.", "output_spec": "For each test case, if there is no counterexample array $$$a$$$ of size $$$n$$$, print NO. Otherwise, print YES followed by the array $$$a$$$ itself ($$$1 \\le a_i \\le 10^9$$$). If there are multiple counterexamples, print any.", "sample_inputs": ["3\n\n2\n\n512\n\n3"], "sample_outputs": ["YES\n1 337\nNO\nYES\n31 4 159"], "notes": "NoteIn the first test case, the only possible pairs of indices are $$$(1, 2)$$$ and $$$(2, 1)$$$.If you perform the operation on indices $$$(1, 2)$$$ (or $$$(2, 1)$$$), you'll get $$$a_1 = a_2 = |1 - 337| = 336$$$, or array $$$[336, 336]$$$. In both cases, the total sum increases, so this array $$$a$$$ is a counterexample."}, "positive_code": [{"source_code": " import scala.io.StdIn.readLine\r\n \r\n object Solution {\r\n \r\n def solve() = {\r\n val len = readLine().toInt\r\n if (len < 20) {\r\n println(\"YES\")\r\n for (\r\n i <- 0 until len\r\n ) print(s\"${Math.pow(3, i).toInt} \")\r\n println()\r\n }\r\n else println(\"NO\")\r\n \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 ) solve()\r\n \r\n }\r\n }"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n\n def solve() = {\n val len = readLine().toInt\n if (len < 19) {\n println(\"YES\")\n for (\n i <- 0 until len\n ) print(s\"${Math.pow(3, i).toInt} \")\n println()\n }\n else println(\"NO\")\n \n }\n\n def main(args: Array[String]): Unit = {\n\n val cases = readLine().toInt\n for (\n i <- 0 until cases\n ) solve()\n\n }\n}\n"}], "src_uid": "c8fddee2f1c7d325437a7d0b82758b03"} {"nl": {"description": "Codeforces user' handle color depends on his rating\u00a0\u2014 it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri (\u2009-\u20094000\u2009\u2264\u2009beforei,\u2009afteri\u2009\u2264\u20094000)\u00a0\u2014 participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters \u00ab_\u00bb and \u00ab-\u00bb characters. It is guaranteed that all handles are distinct.", "output_spec": "Print \u00abYES\u00bb (quotes for clarity), if Anton has performed good in the contest and \u00abNO\u00bb (quotes for clarity) otherwise.", "sample_inputs": ["3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749", "3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest."}, "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": "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"}, {"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"} {"nl": {"description": "Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a,\u2009b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of elements in the array. The next line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the values of the array elements.", "output_spec": "In a single line print a single integer \u2014 the maximum number of points Artem can get.", "sample_inputs": ["5\n3 1 5 2 6", "5\n1 2 3 4 5", "5\n1 100 101 100 1"], "sample_outputs": ["11", "6", "102"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k\u2009\u2265\u20090) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k\u2009-\u20091 into one box of side length 2k, or as in the following figure: Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.", "input_spec": "The first line of input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0\u2009\u2264\u2009ki\u2009\u2264\u2009109, 1\u2009\u2264\u2009ai\u2009\u2264\u2009109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.", "output_spec": "Output a single integer p, such that the smallest magical box that can contain all of Emuskald\u2019s boxes has side length 2p.", "sample_inputs": ["2\n0 3\n1 5", "1\n0 4", "2\n1 10\n2 2"], "sample_outputs": ["3", "1", "3"], "notes": "NotePicture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.In the second test case, we can put all four small boxes into a box with side length 2."}, "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": "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}"}, {"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"} {"nl": {"description": "According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1,\u2009a2,\u2009...,\u2009an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1,\u20092) and (2,\u20091) should be regarded as different.", "input_spec": "The first line contains two integers n and d (1\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009109) \u2014 amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers \u2014 heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.", "output_spec": "Output one number \u2014 amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.", "sample_inputs": ["5 10\n10 20 50 60 65", "5 1\n55 30 29 31 55"], "sample_outputs": ["6", "6"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are $$$n$$$ flights from A to B, they depart at time moments $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ and arrive at B $$$t_a$$$ moments later.There are $$$m$$$ flights from B to C, they depart at time moments $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ and arrive at C $$$t_b$$$ moments later.The connection time is negligible, so one can use the $$$i$$$-th flight from A to B and the $$$j$$$-th flight from B to C if and only if $$$b_j \\ge a_i + t_a$$$.You can cancel at most $$$k$$$ flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $$$k$$$ flights. If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$.", "input_spec": "The first line contains five integers $$$n$$$, $$$m$$$, $$$t_a$$$, $$$t_b$$$ and $$$k$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le n + m$$$, $$$1 \\le t_a, t_b \\le 10^9$$$)\u00a0\u2014 the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively. The second line contains $$$n$$$ distinct integers in increasing order $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ ($$$1 \\le a_1 < a_2 < \\ldots < a_n \\le 10^9$$$)\u00a0\u2014 the times the flights from A to B depart. The third line contains $$$m$$$ distinct integers in increasing order $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ ($$$1 \\le b_1 < b_2 < \\ldots < b_m \\le 10^9$$$)\u00a0\u2014 the times the flights from B to C depart.", "output_spec": "If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$. Otherwise print the earliest time Arkady can arrive at C if you cancel $$$k$$$ flights in such a way that maximizes this time.", "sample_inputs": ["4 5 1 1 2\n1 3 5 7\n1 2 3 9 10", "2 2 4 4 2\n1 10\n10 20", "4 3 2 3 1\n1 999999998 999999999 1000000000\n3 4 1000000000"], "sample_outputs": ["11", "-1", "1000000003"], "notes": "NoteConsider the first example. The flights from A to B depart at time moments $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ and arrive at B at time moments $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, respectively. The flights from B to C depart at time moments $$$1$$$, $$$2$$$, $$$3$$$, $$$9$$$, and $$$10$$$ and arrive at C at time moments $$$2$$$, $$$3$$$, $$$4$$$, $$$10$$$, $$$11$$$, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment $$$4$$$, and take the last flight from B to C arriving at C at time moment $$$11$$$.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C."}, "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 Array(n, m, ta, tb, k) = readInts(5)\n val as = readLongs(n)\n val bs = readLongs(m)\n\n if (n <= k || m <= k) {\n println(-1)\n } else {\n var j = 0\n var max = 0L\n for (i <- 0 to k) {\n val at = as(i) + ta\n while (j < m && at > bs(j)) j += 1\n val j2 = j + (k - i)\n if (j2 >= m) {\n println(-1)\n System.exit(0)\n } else {\n val m = bs(j2) + tb\n if (m > max) max = m\n }\n }\n println(max)\n }\n}\n"}], "negative_code": [], "src_uid": "bf60899aa2bd7350c805437d0fee1583"} {"nl": {"description": "Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u,\u2009v) find the minimal possible weight of the spanning tree that contains the edge (u,\u2009v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.", "input_spec": "First line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u2009n\u2009-\u20091\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of vertices and edges in graph. Each of the next m lines contains three integers ui,\u2009vi,\u2009wi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi,\u20091\u2009\u2264\u2009wi\u2009\u2264\u2009109) \u2014 the endpoints of the i-th edge and its weight.", "output_spec": "Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge. The edges are numbered from 1 to m in order of their appearing in input.", "sample_inputs": ["5 7\n1 2 3\n1 3 1\n1 4 5\n2 3 2\n2 5 3\n3 4 2\n4 5 4"], "sample_outputs": ["9\n8\n11\n8\n8\n8\n9"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "You are given $$$n$$$ pairs of integers $$$(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)$$$. All of the integers in the pairs are distinct and are in the range from $$$1$$$ to $$$2 \\cdot n$$$ inclusive.Let's call a sequence of integers $$$x_1, x_2, \\ldots, x_{2k}$$$ good if either $$$x_1 < x_2 > x_3 < \\ldots < x_{2k-2} > x_{2k-1} < x_{2k}$$$, or $$$x_1 > x_2 < x_3 > \\ldots > x_{2k-2} < x_{2k-1} > x_{2k}$$$. You need to choose a subset of distinct indices $$$i_1, i_2, \\ldots, i_t$$$ and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be $$$a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \\ldots, a_{i_t}, b_{i_t}$$$), this sequence is good.What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence $$$i_1, i_2, \\ldots, i_t$$$.", "input_spec": "The first line contains single integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the number of pairs. Each of the next $$$n$$$ lines contain two numbers\u00a0\u2014 $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le 2 \\cdot n$$$)\u00a0\u2014 the elements of the pairs. It is guaranteed that all integers in the pairs are distinct, that is, every integer from $$$1$$$ to $$$2 \\cdot n$$$ is mentioned exactly once.", "output_spec": "In the first line print a single integer $$$t$$$\u00a0\u2014 the number of pairs in the answer. Then print $$$t$$$ distinct integers $$$i_1, i_2, \\ldots, i_t$$$\u00a0\u2014 the indexes of pairs in the corresponding order.", "sample_inputs": ["5\n1 7\n6 4\n2 10\n9 8\n3 5", "3\n5 4\n3 2\n6 1"], "sample_outputs": ["3\n1 5 3", "3\n3 2 1"], "notes": "NoteThe final sequence in the first example is $$$1 < 7 > 3 < 5 > 2 < 10$$$.The final sequence in the second example is $$$6 > 1 < 3 > 2 < 5 > 4$$$."}, "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\n val Array(n) = readInts(1)\n case class P(a: Int, b: Int, id: Int)\n\n val ps = Array.tabulate(n) { id =>\n val Array(a, b) = readInts(2)\n P(a, b, id + 1)\n }\n\n val (pos, neg) = ps.partition(p => p.a > p.b)\n\n val res = if (pos.length > neg.length) pos.sortBy(_.a).map(_.id) else neg.sortBy(-_.a).map(_.id)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.length)\n println(res.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 def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val Array(n) = readInts(1)\n case class P(a: Int, b: Int, id: Int)\n\n def lisLen(as: Array[P]): Array[Int] = {\n\n val minByLen = Array.fill(as.size) {\n 0\n }\n var i, len = 0\n\n while (i < as.size) {\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)).b < as(i).a) 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 minByLen.take(len)\n }\n\n val ps = Array.tabulate(n) { id =>\n val Array(a, b) = readInts(2)\n P(a, b, id + 1)\n }\n\n val (_pos, _neg) = ps.partition(p => p.a > p.b)\n val pos = _pos.sortBy(_.a)\n val neg = _neg.map(p => P(-p.a, -p.b, p.id)).sortBy(_.a) //reverse???\n\n val lis1 = lisLen(pos)\n val lis2 = lisLen(neg)\n//println(pos.mkString(\" \"))\n// println(neg.mkString(\" \"))\n val res = if (lis1.length > lis2.length) lis1.map(pos(_).id) else lis2.reverse.map(neg(_).id)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.length)\n println(res.mkString(\" \"))\n\n Console.flush\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 case class P(a: Int, b: Int, id: Int)\n\n def lisLen(as: Array[P]): Array[Int] = {\n\n val minByLen = Array.fill(as.size) {\n 0\n }\n var i, len = 0\n\n while (i < as.size) {\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)).b < as(i).a) 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 minByLen.take(len)\n }\n\n val ps = Array.tabulate(n) { id =>\n val Array(a, b) = readInts(2)\n P(a, b, id + 1)\n }\n\n val (_pos, _neg) = ps.partition(p => p.a > p.b)\n val pos = _pos.sortBy(- _.b)\n val neg = _neg.map(p => P(-p.a, -p.b, p.id)).sortBy(- _.b) //reverse???\n\n val lis1 = lisLen(pos)\n val lis2 = lisLen(neg)\n//println(pos.mkString(\" \"))\n// println(neg.mkString(\" \"))\n val res = if (lis1.length > lis2.length) lis1.map(pos(_).id) else lis2.reverse.map(neg(_).id)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.length)\n println(res.mkString(\" \"))\n\n Console.flush\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 case class P(a: Int, b: Int, id: Int)\n\n def lisLen(as: Array[P]): Array[Int] = {\n\n val minByLen = Array.fill(as.size) {\n 0\n }\n var i, len = 0\n\n while (i < as.size) {\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)).b < as(i).a) 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 minByLen.take(len)\n }\n\n val ps = Array.tabulate(n) { id =>\n val Array(a, b) = readInts(2)\n P(a, b, id + 1)\n }\n\n val (_pos, _neg) = ps.partition(p => p.a > p.b)\n val pos = _pos.sortBy(_.b)\n val neg = _neg.map(p => P(-p.a, -p.b, p.id)).sortBy(_.b) //reverse???\n\n val lis1 = lisLen(pos)\n val lis2 = lisLen(neg)\n//println(pos.mkString(\" \"))\n// println(neg.mkString(\" \"))\n val res = if (lis1.length > lis2.length) lis1.map(pos(_).id) else lis2.reverse.map(neg(_).id)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.length)\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "src_uid": "6b720be3d26719ce649158e8903527e3"} {"nl": {"description": "The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n\u2009\u00d7\u2009m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.", "input_spec": "The first line contains three space-separated integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u2009500000) \u2014 the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each \u2014 the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0\u2009\u2264\u2009p\u2009\u2264\u2009106. Next k lines contain queries in the format \"si xi yi\", where si is one of the characters \"\u0441\", \"r\" or \"g\", and xi, yi are two integers. If si = \"c\", then the current query is the query to swap columns with indexes xi and yi (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009m,\u2009x\u2009\u2260\u2009y); If si = \"r\", then the current query is the query to swap rows with indexes xi and yi (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n,\u2009x\u2009\u2260\u2009y); If si = \"g\", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns \u2014 from left to right from 1 to m.", "output_spec": "For each query to obtain a number (si = \"g\") print the required number. Print the answers to the queries in the order of the queries in the input.", "sample_inputs": ["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"], "sample_outputs": ["8\n9\n6", "5"], "notes": "NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5."}, "positive_code": [{"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 data = (1 to n).map(_ => in.next().split(' ').map(_.toInt))\n val lines = Array.range(0, n)\n val columns = Array.range(0, m)\n var resultCount = 0\n val query = (1 to k).map{ _ =>\n val Array(t, a, b) = in.next().split(' ')\n val head = t.head\n if (head == 'g')\n resultCount += 1\n (t.head, a.toInt - 1, b.toInt - 1)\n }\n val result = Array.ofDim[Int](resultCount)\n var i = 0\n query.foreach {\n case ('c', a, b) =>\n val tmp = columns(a)\n columns(a) = columns(b)\n columns(b) = tmp\n case ('r', a, b) =>\n val tmp = lines(a)\n lines(a) = lines(b)\n lines(b) = tmp\n case ('g', a, b) =>\n result(i) = data(lines(a))(columns(b))\n i += 1\n }\n println(result.mkString(\"\\n\"))\n}"}], "negative_code": [], "src_uid": "290d9779a6be44ce6a2e62989aee0dbd"} {"nl": {"description": "You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s|\u2009-\u20091 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s|\u2009-\u20091.The decoding of the lever description is given below. If the i-th character of the string equals \"^\", that means that at coordinate i there is the pivot under the bar. If the i-th character of the string equals \"=\", that means that at coordinate i there is nothing lying on the bar. If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.", "input_spec": "The first line contains the lever description as a non-empty string s (3\u2009\u2264\u2009|s|\u2009\u2264\u2009106), consisting of digits (1-9) and characters \"^\" and \"=\". It is guaranteed that the line contains exactly one character \"^\". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar. To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.", "output_spec": "Print \"left\" if the given lever tilts to the left, \"right\" if it tilts to the right and \"balance\", if it is in balance.", "sample_inputs": ["=^==", "9===^==1", "2==^7==", "41^52=="], "sample_outputs": ["balance", "left", "right", "balance"], "notes": "NoteAs you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.The pictures to the examples: "}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Acingel is a small town. There was only one doctor here\u00a0\u2014 Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $$$m$$$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $$$1$$$ to $$$n$$$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.However, some facts are very suspicious\u00a0\u2013 how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? \"In the morning some of neighbours must have been sleeping!\"\u00a0\u2014 thinks Gawry\u00a0\u2014 \"and in the evening there's been too dark to see somebody's face...\". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that\u00a0\u2014 some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.In how many ways he can do it? Two ways are called different if the remaining common part is different.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100\\,000$$$, $$$1 \\le m \\le 10$$$)\u00a0\u2014 the number of suspects and the number of asked neighbors. Each of the next $$$m$$$ lines contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that these integers form a correct permutation (that is, each number from $$$1$$$ to $$$n$$$ appears exactly once).", "output_spec": "Output a single integer denoting the number of ways to delete some prefix and some suffix of each permutation (possibly empty), such that the remaining parts will be equal and non-empty.", "sample_inputs": ["3 2\n1 2 3\n2 3 1", "5 6\n1 2 3 4 5\n2 3 1 4 5\n3 4 5 1 2\n3 5 4 2 1\n2 3 5 4 1\n1 2 3 4 5", "2 2\n1 2\n2 1"], "sample_outputs": ["4", "5", "2"], "notes": "NoteIn the first example, all possible common parts are $$$[1]$$$, $$$[2]$$$, $$$[3]$$$ and $$$[2, 3]$$$.In the second and third examples, you can only leave common parts of length $$$1$$$."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "A positive integer $$$x$$$ is called a power of two if it can be represented as $$$x = 2^y$$$, where $$$y$$$ is a non-negative integer. So, the powers of two are $$$1, 2, 4, 8, 16, \\dots$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Your task is to represent $$$n$$$ as the sum of exactly $$$k$$$ powers of two.", "input_spec": "The only line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^9$$$, $$$1 \\le k \\le 2 \\cdot 10^5$$$).", "output_spec": "If it is impossible to represent $$$n$$$ as the sum of $$$k$$$ powers of two, print NO. Otherwise, print YES, and then print $$$k$$$ positive integers $$$b_1, b_2, \\dots, b_k$$$ such that each of $$$b_i$$$ is a power of two, and $$$\\sum \\limits_{i = 1}^{k} b_i = n$$$. If there are multiple answers, you may print any of them.", "sample_inputs": ["9 4", "8 1", "5 1", "3 7"], "sample_outputs": ["YES\n1 2 2 4", "YES\n8", "NO", "NO"], "notes": null}, "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 = 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}"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "10d6179b479e1238a51154a9a6fc13cb"} {"nl": {"description": "An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!Each grid (main and reserve) has a head node (its number is $$$1$$$). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly $$$n$$$ nodes, which do not spread electricity further.In other words, every grid is a rooted directed tree on $$$n$$$ leaves with a root in the node, which number is $$$1$$$. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.Also, the palace has $$$n$$$ electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device. In this example the main grid contains $$$6$$$ nodes (the top tree) and the reserve grid contains $$$4$$$ nodes (the lower tree). There are $$$3$$$ devices with numbers colored in blue. It is guaranteed that the whole grid (two grids and $$$n$$$ devices) can be shown in this way (like in the picture above): main grid is a top tree, whose wires are directed 'from the top to the down', reserve grid is a lower tree, whose wires are directed 'from the down to the top', devices\u00a0\u2014 horizontal row between two grids, which are numbered from $$$1$$$ to $$$n$$$ from the left to the right, wires between nodes do not intersect. Formally, for each tree exists a depth-first search from the node with number $$$1$$$, that visits leaves in order of connection to devices $$$1, 2, \\dots, n$$$ (firstly, the node, that is connected to the device $$$1$$$, then the node, that is connected to the device $$$2$$$, etc.).Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of devices in the palace. The next line contains an integer $$$a$$$ ($$$1 + n \\le a \\le 1000 + n$$$) \u2014 the amount of nodes in the main grid. Next line contains $$$a - 1$$$ integers $$$p_i$$$ ($$$1 \\le p_i \\le a$$$). Each integer $$$p_i$$$ means that the main grid contains a wire from $$$p_i$$$-th node to $$$(i + 1)$$$-th. The next line contains $$$n$$$ integers $$$x_i$$$ ($$$1 \\le x_i \\le a$$$) \u2014 the number of a node in the main grid that is connected to the $$$i$$$-th device. The next line contains an integer $$$b$$$ ($$$1 + n \\le b \\le 1000 + n$$$) \u2014 the amount of nodes in the reserve grid. Next line contains $$$b - 1$$$ integers $$$q_i$$$ ($$$1 \\le q_i \\le b$$$). Each integer $$$q_i$$$ means that the reserve grid contains a wire from $$$q_i$$$-th node to $$$(i + 1)$$$-th. The next line contains $$$n$$$ integers $$$y_i$$$ ($$$1 \\le y_i \\le b$$$) \u2014 the number of a node in the reserve grid that is connected to the $$$i$$$-th device. It is guaranteed that each grid is a tree, which has exactly $$$n$$$ leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node $$$1$$$, that visits leaves in order of connection to devices.", "output_spec": "Print a single integer \u2014 the maximal amount of wires that can be cut so that each device is powered.", "sample_inputs": ["3\n6\n4 1 1 4 2\n6 5 3\n4\n1 1 1\n3 4 2", "4\n6\n4 4 1 1 1\n3 2 6 5\n6\n6 6 1 1 1\n5 4 3 2", "5\n14\n1 1 11 2 14 14 13 7 12 2 5 6 1\n9 8 3 10 4\n16\n1 1 9 9 2 5 10 1 14 3 7 11 6 12 2\n8 16 13 4 15"], "sample_outputs": ["5", "6", "17"], "notes": "NoteFor the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red): The second and the third examples can be seen below: "}, "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, a = nextInt\n val ps = 0 +: nextInts(a - 1).map(_ - 1)\n val xs = nextInts(n).map(_ - 1)\n val b = nextInt\n val qs = 0 +: nextInts(b - 1).map(_ - 1)\n val ys = nextInts(n).map(_ - 1)\n\n val pChildrenBuilders = Array.fill(a)(new mutable.ArrayBuilder.ofInt)\n for (i <- 1 until ps.length) {\n pChildrenBuilders(ps(i)) += i\n }\n val pChildren = pChildrenBuilders.map(_.result())\n\n val qChildrenBuilders = Array.fill(b)(new mutable.ArrayBuilder.ofInt)\n for (i <- 1 until qs.length) {\n qChildrenBuilders(qs(i)) += i\n }\n val qChildren = qChildrenBuilders.map(_.result())\n\n val pl = Array.fill(a)(n)\n val pr, pSize = Array.fill(a)(0)\n\n val ql = Array.fill(b)(n)\n val qr, qSize = Array.fill(b)(0)\n\n for (i <- xs.indices) {\n pl(xs(i)) = i\n pr(xs(i)) = i\n }\n\n for (i <- ys.indices) {\n ql(ys(i)) = i\n qr(ys(i)) = i\n }\n\n def dfs1p(u: Int): Int = {\n for (v <- pChildren(u)) {\n pSize(u) += dfs1p(v)\n if (pl(v) < pl(u)) pl(u) = pl(v)\n if (pr(v) > pr(u)) pr(u) = pr(v)\n }\n pSize(u) + 1\n }\n\n def dfs1q(u: Int): Int = {\n for (v <- qChildren(u)) {\n qSize(u) += dfs1q(v)\n if (ql(v) < ql(u)) ql(u) = ql(v)\n if (qr(v) > qr(u)) qr(u) = qr(v)\n }\n qSize(u) + 1\n }\n\n dfs1p(0)\n dfs1q(0)\n\n val dp = Array.fill(n)(0)\n\n for (r <- 0 until n) {\n var p = xs(r)\n var depth = 0\n while (pr(p) == r && p != 0) {\n depth += 1\n val score = pSize(p) + (if (pl(p) == 0) 0 else dp(pl(p) - 1)) + 1\n dp(r) = Math.max(dp(r), score)\n p = ps(p)\n }\n\n var q = ys(r)\n depth = 0\n while (qr(q) == r && q != 0) {\n depth += 1\n val score = qSize(q) + (if (ql(q) == 0) 0 else dp(ql(q) - 1)) + 1\n dp(r) = Math.max(dp(r), score)\n q = qs(q)\n }\n }\n \n out.println(dp.last)\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, a = nextInt\n val ps = 0 +: nextInts(a - 1).map(_ - 1)\n val xs = nextInts(n).map(_ - 1)\n val b = nextInt\n val qs = 0 +: nextInts(b - 1).map(_ - 1)\n val ys = nextInts(n).map(_ - 1)\n\n val pChildrenBuilders = Array.fill(a)(new mutable.ArrayBuilder.ofInt)\n for (i <- 1 until ps.length) {\n pChildrenBuilders(ps(i)) += i\n }\n val pChildren = pChildrenBuilders.map(_.result())\n\n val qChildrenBuilders = Array.fill(b)(new mutable.ArrayBuilder.ofInt)\n for (i <- 1 until qs.length) {\n qChildrenBuilders(qs(i)) += i\n }\n val qChildren = qChildrenBuilders.map(_.result())\n\n val pl = Array.fill(a)(n)\n val pr = Array.fill(a)(0)\n\n val ql = Array.fill(b)(n)\n val qr = Array.fill(b)(0)\n\n for (i <- xs.indices) {\n pl(xs(i)) = i\n pr(xs(i)) = i\n }\n\n for (i <- ys.indices) {\n ql(ys(i)) = i\n qr(ys(i)) = i\n }\n\n def dfs1p(u: Int): Unit = {\n for (v <- pChildren(u)) {\n dfs1p(v)\n if (pl(v) < pl(u)) pl(u) = pl(v)\n if (pr(v) > pr(u)) pr(u) = pr(v)\n }\n }\n\n def dfs1q(u: Int): Unit = {\n for (v <- qChildren(u)) {\n dfs1q(v)\n if (ql(v) < ql(u)) ql(u) = ql(v)\n if (qr(v) > qr(u)) qr(u) = qr(v)\n }\n }\n\n dfs1p(0)\n dfs1q(0)\n\n val dpp, dpq = Array.fill(n, n + 1)(0)\n\n for (r <- 0 until n) {\n for (l <- 0 to r) {\n val dq = if (l > 0) dpq(l - 1).max else 0\n val dp = if (l > 0) dpp(l - 1).max else 0\n var p = xs(r)\n var depth = 0\n while (pr(p) == r && pl(p) >= l && p != 0) {\n depth += 1\n println(\"---\")\n val score = depth + (if (r == 0) 0 else dpp(r - 1)(l)) + dq\n dpp(r)(l) = Math.max(dpp(r)(l), score)\n// if (score > bestP) bestP = score\n p = ps(p)\n }\n\n var q = ys(r)\n depth = 0\n while (qr(q) == r && ql(q) >= l && q != 0) {\n depth += 1\n val score = depth + (if (r == 0) 0 else dpq(r - 1)(l)) + dp\n dpq(r)(l) = Math.max(dpq(r)(l), score)\n // if (score > bestP) bestP = score\n q = qs(q)\n }\n }\n }\n\n\n\n out.println(dpq.last.max max dpp.last.max)\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": "7fe380a1848eae621c734cc9a3e463e0"} {"nl": {"description": "You are given a special jigsaw puzzle consisting of $$$n\\cdot m$$$ identical pieces. Every piece has three tabs and one blank, as pictured below. The jigsaw puzzle is considered solved if the following conditions hold: The pieces are arranged into a grid with $$$n$$$ rows and $$$m$$$ columns. For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece. Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.", "input_spec": "The test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n,m \\le 10^5$$$).", "output_spec": "For each test case output a single line containing \"YES\" if it is possible to solve the jigsaw puzzle, or \"NO\" otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n1 3\n100000 100000\n2 2"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteFor the first test case, this is an example solution: For the second test case, we can show that no solution exists.For the third test case, this is an example solution: "}, "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": "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"}, {"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"} {"nl": {"description": "Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of numbers in the sequence. The second line contains n space-separated integer numbers \u2014 elements of the sequence. These numbers don't exceed 100 in absolute value.", "output_spec": "If the given sequence has the second order statistics, output this order statistics, otherwise output NO.", "sample_inputs": ["4\n1 2 2 -4", "5\n1 2 3 1 1"], "sample_outputs": ["1", "2"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:Suppose we want to analyze the segment of $$$n$$$ consecutive days. We have measured the temperatures during these $$$n$$$ days; the temperature during $$$i$$$-th day equals $$$a_i$$$.We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $$$x$$$ to day $$$y$$$, we calculate it as $$$\\frac{\\sum \\limits_{i = x}^{y} a_i}{y - x + 1}$$$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. For example, if analyzing the measures $$$[3, 4, 1, 2]$$$ and $$$k = 3$$$, we are interested in segments $$$[3, 4, 1]$$$, $$$[4, 1, 2]$$$ and $$$[3, 4, 1, 2]$$$ (we want to find the maximum value of average temperature over these segments).You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 5000$$$) \u2014 the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 5000$$$) \u2014 the temperature measures during given $$$n$$$ days.", "output_spec": "Print one real number \u2014 the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. Your answer will be considered correct if the following condition holds: $$$|res - res_0| < 10^{-6}$$$, where $$$res$$$ is your answer, and $$$res_0$$$ is the answer given by the jury's solution.", "sample_inputs": ["4 3\n3 4 1 2"], "sample_outputs": ["2.666666666666667"], "notes": null}, "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": "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} "}, {"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"} {"nl": {"description": "There is a country with $$$n$$$ citizens. The $$$i$$$-th of them initially has $$$a_{i}$$$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $$$x$$$ are paid accordingly so that after the payout they have exactly $$$x$$$ money. In this case the citizens don't send a receipt.You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^{5}$$$)\u00a0\u2014 the numer of citizens. The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \\le a_{i} \\le 10^{9}$$$)\u00a0\u2014 the initial balances of citizens. The next line contains a single integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^{5}$$$)\u00a0\u2014 the number of events. Each of the next $$$q$$$ lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x ($$$1 \\le p \\le n$$$, $$$0 \\le x \\le 10^{9}$$$), or 2 x ($$$0 \\le x \\le 10^{9}$$$). In the first case we have a receipt that the balance of the $$$p$$$-th person becomes equal to $$$x$$$. In the second case we have a payoff with parameter $$$x$$$.", "output_spec": "Print $$$n$$$ integers\u00a0\u2014 the balances of all citizens after all events.", "sample_inputs": ["4\n1 2 3 4\n3\n2 3\n1 2 2\n2 1", "5\n3 50 2 1 10\n3\n1 2 0\n2 8\n1 3 20"], "sample_outputs": ["3 2 3 4", "8 8 20 8 10"], "notes": "NoteIn the first example the balances change as follows: 1 2 3 4 $$$\\rightarrow$$$ 3 3 3 4 $$$\\rightarrow$$$ 3 2 3 4 $$$\\rightarrow$$$ 3 2 3 4In the second example the balances change as follows: 3 50 2 1 10 $$$\\rightarrow$$$ 3 0 2 1 10 $$$\\rightarrow$$$ 8 8 8 8 10 $$$\\rightarrow$$$ 8 8 20 8 10"}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val Q = ni()\n val receit = Array.ofDim[(Int, Int)](N) // \u6700\u5f8c\u306e\u30ec\u30b7\u30fc\u30c8 (\u6642\u9593,\u91d1\u984d)\n val payout = Array.ofDim[Int](Q)\n REP(N) { i =>\n receit(i) = (0, A(i))\n }\n REP(Q) { i =>\n val t = ni()\n t match {\n case 1 =>\n val p, x = ni()\n receit(p - 1) = (i, x)\n\n case 2 =>\n val x = ni()\n payout(i) = x\n }\n }\n\n REP_r(Q - 1) { i =>\n payout(i) = max(payout(i), payout(i + 1))\n }\n\n debug(receit.mkString(\" \"))\n debug(payout)\n\n REP(N) { i =>\n val j = receit(i)._1\n val r = receit(i)._2\n out.print(s\"${max(payout(j), r)} \")\n }\n out.println()\n }\n}"}], "negative_code": [], "src_uid": "7b788c660fb8ca703af0030f4c84ce96"} {"nl": {"description": "Little penguin Polo has an n\u2009\u00d7\u2009m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.", "input_spec": "The first line contains three integers n, m and d (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009104) \u2014 the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009104).", "output_spec": "In a single line print a single integer \u2014 the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print \"-1\" (without the quotes).", "sample_inputs": ["2 2 2\n2 4\n6 8", "1 2 7\n6 7"], "sample_outputs": ["4", "-1"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Bizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of fence planks. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the minimum number of strokes needed to paint the whole fence.", "sample_inputs": ["5\n2 2 1 2 1", "2\n2 2", "1\n5"], "sample_outputs": ["3", "2", "1"], "notes": "NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There are n cows playing poker at a table. For the current betting phase, each player's status is either \"ALLIN\", \"IN\", or \"FOLDED\", and does not change throughout the phase. To increase the suspense, a player whose current status is not \"FOLDED\" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either \"ALLIN\" or \"FOLDED\". The player's own status may be either \"ALLIN\" or \"IN\".Find the number of cows that can currently show their hands without affecting any betting decisions.", "input_spec": "The first line contains a single integer, n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains n characters, each either \"A\", \"I\", or \"F\". The i-th character is \"A\" if the i-th player's status is \"ALLIN\", \"I\" if the i-th player's status is \"IN\", or \"F\" if the i-th player's status is \"FOLDED\".", "output_spec": "The first line should contain a single integer denoting the number of players that can currently show their hands.", "sample_inputs": ["6\nAFFAAA", "3\nAFI"], "sample_outputs": ["4", "1"], "notes": "NoteIn the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand."}, "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()\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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x\u2009+\u2009y\u2009=\u2009n). The sizes of teams differ in no more than one (|x\u2009-\u2009y|\u2009\u2264\u20091). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.", "input_spec": "The first line contains the only integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009104), the i-th number represents the i-th boy's playing skills. ", "output_spec": "On the first line print an integer x \u2014 the number of boys playing for the first team. On the second line print x integers \u2014 the individual numbers of boys playing for the first team. On the third line print an integer y \u2014 the number of boys playing for the second team, on the fourth line print y integers \u2014 the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x\u2009+\u2009y\u2009=\u2009n, |x\u2009-\u2009y|\u2009\u2264\u20091, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.", "sample_inputs": ["3\n1 2 1", "5\n2 3 3 1 1"], "sample_outputs": ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"], "notes": "NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2\u2009-\u20091|\u2009=\u20091\u2009\u2264\u20091) is fulfilled, the third limitation on the difference in skills ((2\u2009+\u20091)\u2009-\u2009(1)\u2009=\u20092\u2009\u2264\u20092) is fulfilled."}, "positive_code": [{"source_code": "import scala.io.StdIn\nimport scala.util.Sorting\n\n/**\n * @author chengyi\n */\nobject DivisionIntoTeams {\n \n def check(line:String, a:List[Int], b:List[Int]):Boolean={\n val input = line.split(\" \").map { x => x.toInt }.toArray\n val asum:Long = (a.map{ x => input(x) }).sum\n val bsum:Long = (b.map{ x => input(x) }).sum\n \n return Math.abs(a.length-b.length)<=1 && (a.length+b.length==input.length) && Math.abs(asum-bsum) <= input.max\n }\n \n def split(line:String):(List[Int], List[Int])={\n val input = line.split(\" \").map { x => x.toInt }.toArray\n var inmap = input.zipWithIndex\n \n inmap = inmap.sortBy(_._1)\n \n var i = 0\n var a:List[Int] = List()\n var b:List[Int] = List()\n var aSum:Long = 0;\n var bSum:Long = 0;\n while (iinmap(i+1)._1){\n minIdx = inmap(i+1)._2\n maxIdx = inmap(i)._2\n }else{\n minIdx = inmap(i)._2\n maxIdx = inmap(i+1)._2\n }\n \n if (aSum < bSum){\n bSum = bSum + input(minIdx)\n b = b.+:(minIdx)\n aSum = aSum + input(maxIdx)\n a = a.+:(maxIdx)\n }else{\n bSum = bSum + input(maxIdx)\n b = b.+:(maxIdx)\n aSum = aSum + input(minIdx)\n a = a.+:(minIdx)\n }\n \n \n i = i + 2\n }\n \n if (i == input.length-1){\n val idx = inmap(i)._2\n if (aSum < bSum){\n aSum = aSum + input(idx)\n a = a.+:(idx)\n }else{\n bSum = bSum + input(idx)\n b = b.+:(idx)\n }\n }else{\n \n }\n \n (a,b)\n }\n \n def main(args:Array[String]){\n val n = StdIn.readLine().toInt\n val line = StdIn.readLine()\n val (a, b) = split(line)\n println(a.length)\n println(a.map { x => x+1 }.mkString(\" \"))\n println(b.length)\n println(b.map { x => x+1 }mkString(\" \"))\n }\n \n}"}], "negative_code": [{"source_code": "import scala.io.StdIn\nimport scala.util.Sorting\n\n/**\n * @author chengyi\n */\nobject DivisionIntoTeams {\n \n def split(line:String):(List[Int], List[Int])={\n val input = line.split(\" \").map { x => x.toInt }.toArray\n Sorting.quickSort(input)\n \n //println(\"input:\" + input.toList)\n \n var i = 0\n var a:List[Int] = List()\n var b:List[Int] = List()\n var aSum:Int = 0;\n var bSum:Int = 0;\n while (iinput(i+1)){\n minIdx = i+1\n maxIdx = i\n }else{\n minIdx = i\n maxIdx = i+1\n }\n \n if (aSum < bSum){\n bSum = bSum + input(minIdx)\n b = b.+:(minIdx)\n aSum = aSum + input(maxIdx)\n a = a.+:(maxIdx)\n }else{\n bSum = bSum + input(maxIdx)\n b = b.+:(maxIdx)\n aSum = aSum + input(minIdx)\n a = a.+:(minIdx)\n }\n \n i = i + 2\n }\n \n if (i == input.length-1){\n if (aSum < bSum){\n aSum = aSum + input(input.length-1)\n a = a.+:(input.length-1)\n }else{\n bSum = bSum + input(input.length-1)\n b = b.+:(input.length-1)\n }\n }else{\n \n }\n \n (a,b)\n }\n \n def main(args:Array[String]){\n val n = StdIn.readLine().toInt\n val line = StdIn.readLine()\n val (a, b) = split(line)\n println(a.length)\n println(a.map { x => x+1 }.mkString(\" \"))\n println(b.length)\n println(b.map { x => x+1 }mkString(\" \"))\n }\n \n}"}], "src_uid": "0937a7e2f912fc094cc4275fd47cd457"} {"nl": {"description": "Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0\u2009<\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an) teeth, and the j-th star on the rear wheel axle has bj (0\u2009<\u2009b1\u2009<\u2009b2\u2009<\u2009...\u2009<\u2009bm) teeth. Any pair (i,\u2009j) (1\u2009\u2264\u2009i\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009j\u2009\u2264\u2009m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i,\u2009j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i,\u2009j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all \"integer\" gears (i,\u2009j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction denotes division in real numbers, that is, no rounding is performed.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of stars on the bicycle's pedal axle. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) in the order of strict increasing. The third input line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u200950) \u2014 the number of stars on the rear wheel axle. The fourth line contains m integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i,\u2009j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.", "output_spec": "Print the number of \"integer\" gears with the maximum ratio among all \"integer\" gears.", "sample_inputs": ["2\n4 5\n3\n12 13 15", "4\n1 2 3 4\n5\n10 11 12 13 14"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample the maximum \"integer\" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1\u2009=\u20094,\u2009b1\u2009=\u200912, and for the other a2\u2009=\u20095,\u2009b3\u2009=\u200915."}, "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 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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "102667eaa3aee012fef70f4192464674"} {"nl": {"description": "DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s\u2009=\u2009s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get? ", "input_spec": "The first line contains a single string s\u00a0(1\u2009\u2264\u2009|s|\u2009\u2264\u2009103). The second line contains a single integer k\u00a0(0\u2009\u2264\u2009k\u2009\u2264\u2009103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.", "output_spec": "Print a single integer \u2014 the largest possible value of the resulting string DZY could get.", "sample_inputs": ["abc\n3\n1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"], "sample_outputs": ["41"], "notes": "NoteIn the test sample DZY can obtain \"abcbbc\", value\u2009=\u20091\u00b71\u2009+\u20092\u00b72\u2009+\u20093\u00b72\u2009+\u20094\u00b72\u2009+\u20095\u00b72\u2009+\u20096\u00b72\u2009=\u200941."}, "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 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}"}, {"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": "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"}, {"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"}], "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"} {"nl": {"description": "Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.", "input_spec": "The single line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the sum of digits of the required lucky number.", "output_spec": "Print on the single line the result \u2014 the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.", "sample_inputs": ["11", "10"], "sample_outputs": ["47", "-1"], "notes": null}, "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 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}"}, {"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.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": "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"} {"nl": {"description": "$$$n$$$ students are taking an exam. The highest possible score at this exam is $$$m$$$. Let $$$a_{i}$$$ be the score of the $$$i$$$-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers $$$0 \\leq a_{i} \\leq m$$$ The average score of the class doesn't change. You are student $$$1$$$ and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 200$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n \\leq 10^{3}$$$, $$$1 \\leq m \\leq 10^{5}$$$) \u00a0\u2014 the number of students and the highest possible score respectively. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$ 0 \\leq a_{i} \\leq m$$$) \u00a0\u2014 scores of the students.", "output_spec": "For each testcase, output one integer \u00a0\u2014 the highest possible score you can assign to yourself such that both conditions are satisfied._", "sample_inputs": ["2\n4 10\n1 2 3 4\n4 5\n1 2 3 4"], "sample_outputs": ["10\n5"], "notes": "NoteIn the first case, $$$a = [1,2,3,4] $$$, with average of $$$2.5$$$. You can change array $$$a$$$ to $$$[10,0,0,0]$$$. Average remains $$$2.5$$$, and all conditions are satisfied.In the second case, $$$0 \\leq a_{i} \\leq 5$$$. You can change $$$a$$$ to $$$[5,1,1,3]$$$. You cannot increase $$$a_{1}$$$ further as it will violate condition $$$0\\le a_i\\le m$$$."}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "7c2a61de728e6767b25e58c74497bbae"} {"nl": {"description": "You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: \"You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.\". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 10^9$$$) \u2014 the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.", "output_spec": "Print exactly $$$n$$$ integers $$$t_1, t_2, \\dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.", "sample_inputs": ["3 5\n3 7 9", "4 20\n10 9 19 2", "1 100\n99"], "sample_outputs": ["0 2 1", "0 0 1 1", "0"], "notes": "NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day."}, "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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}], "negative_code": [], "src_uid": "a2085c2d21b2dbe4cc27a15fa4a1ec4f"} {"nl": {"description": "Cowboy Vlad has a birthday today! There are $$$n$$$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from $$$1$$$ to $$$n$$$ in a circle order, that is, for every $$$i$$$ child with number $$$i$$$ will stand next to the child with number $$$i+1$$$, also the child with number $$$1$$$ stands next to the child with number $$$n$$$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the number of the children who came to the cowboy Vlad's birthday. The second line contains integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) denoting heights of every child.", "output_spec": "Print exactly $$$n$$$ integers\u00a0\u2014 heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them.", "sample_inputs": ["5\n2 1 1 3 2", "3\n30 10 20"], "sample_outputs": ["1 2 3 2 1", "10 20 30"], "notes": "NoteIn the first example, the discomfort of the circle is equal to $$$1$$$, since the corresponding absolute differences are $$$1$$$, $$$1$$$, $$$1$$$ and $$$0$$$. Note, that sequences $$$[2, 3, 2, 1, 1]$$$ and $$$[3, 2, 1, 1, 2]$$$ form the same circles and differ only by the selection of the starting point.In the second example, the discomfort of the circle is equal to $$$20$$$, since the absolute difference of $$$10$$$ and $$$30$$$ is equal to $$$20$$$."}, "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\n val ix = ArrayBuffer[Int]()\n REP(N) { i =>\n if (i % 2 == 0) ix += i\n }\n\n REP_r(N) { i =>\n if (i % 2 == 1) ix += i\n }\n\n// debug(ix.mkString(\" \"))\n out.println(ix.map(A).mkString(\" \"))\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\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": [], "src_uid": "205b2332c176b758e843473e8d357475"} {"nl": {"description": "Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u,\u2009v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm: Root the tree at node 1. Count the number of nodes at an even depth. Let it be evenCnt. Count the number of nodes at an odd depth. Let it be oddCnt. The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.", "input_spec": "The only line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of nodes in the desired trees.", "output_spec": "The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output \"-1\" (without quotes) for that section only. If the answer for a section exists, it should contain n\u2009-\u20091 lines, each containing 2 space-separated integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them.", "sample_inputs": ["2", "8"], "sample_outputs": ["-1\n1 2", "1 2\n1 3\n2 4\n2 5\n3 6\n4 7\n4 8\n1 2\n1 3\n2 4\n2 5\n2 6\n3 7\n6 8"], "notes": "NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed \u2009-\u20091 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this: In the second tree, the algorithm will find an answer with 3 nodes which is correct: "}, "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val n = readInt\n\n if (n < 6) {\n println(-1)\n } else {\n println(tree(n - 2))\n println(s\"2 ${n - 1}\\n2 $n\")\n }\n\n println(tree(n))\n }\n \n lazy val ones: Stream[Int] = 1 #:: ones\n lazy val N: Stream[Int] = 1 #:: N.map(_ + 1)\n \n def tree(n: Int) =\n ones.zip(N.tail).take(n - 1).map {\n case (x, y) => s\"$x $y\"\n }.mkString(\"\\n\")\n}"}], "negative_code": [], "src_uid": "b1959af75dfdf8281e70ae66375caa14"} {"nl": {"description": "You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.", "input_spec": "The first line contains two integers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u20093000, 1\u2009\u2264\u2009m\u2009\u2264\u20093000) \u2014 the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1,\u2009c2,\u2009...,\u2009cn \u2014 the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1,\u2009a2,\u2009... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.", "output_spec": "Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.", "sample_inputs": ["4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest", "5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll"], "sample_outputs": ["codeforces round letter round", "hbnyiyc joll joll un joll"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y\u2009=\u2009ki\u00b7x\u2009+\u2009bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1\u2009<\u2009x2. In other words, is it true that there are 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n and x',\u2009y', such that: y'\u2009=\u2009ki\u2009*\u2009x'\u2009+\u2009bi, that is, point (x',\u2009y') belongs to the line number i; y'\u2009=\u2009kj\u2009*\u2009x'\u2009+\u2009bj, that is, point (x',\u2009y') belongs to the line number j; x1\u2009<\u2009x'\u2009<\u2009x2, that is, point (x',\u2009y') lies inside the strip bounded by x1\u2009<\u2009x2. You can't leave Anton in trouble, can you? Write a program that solves the given task.", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of lines in the task given to Anton. The second line contains integers x1 and x2 (\u2009-\u20091\u2009000\u2009000\u2009\u2264\u2009x1\u2009<\u2009x2\u2009\u2264\u20091\u2009000\u2009000) defining the strip inside which you need to find a point of intersection of at least two lines. The following n lines contain integers ki, bi (\u2009-\u20091\u2009000\u2009000\u2009\u2264\u2009ki,\u2009bi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i\u2009\u2260\u2009j it is true that either ki\u2009\u2260\u2009kj, or bi\u2009\u2260\u2009bj.", "output_spec": "Print \"Yes\" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print \"No\" (without quotes).", "sample_inputs": ["4\n1 2\n1 2\n1 0\n0 1\n0 2", "2\n1 3\n1 0\n-1 3", "2\n1 3\n1 0\n0 2", "2\n1 3\n1 0\n0 3"], "sample_outputs": ["NO", "YES", "YES", "NO"], "notes": "NoteIn the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it. "}, "positive_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.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"}, {"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 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"}, {"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"}], "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"} {"nl": {"description": "You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings \"abacaba\", \"aa\" and \"z\" are palindromes and strings \"bba\", \"xd\" are not.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).", "output_spec": "Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.", "sample_inputs": ["3\naa\nabacaba\nxdd"], "sample_outputs": ["-1\nabaacba\nxdd"], "notes": "NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: \"ababaca\", \"abcabaa\", \"baacaba\".In the third query we can do nothing to obtain a good string."}, "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": "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"}, {"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"} {"nl": {"description": "A flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1\u2009\u2265\u20090) and r2(r2\u2009\u2265\u20090), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12\u2009+\u2009r22 is minimum possible. Find this minimum value.", "input_spec": "The first line of the input contains integers n, x1, y1, x2, y2 (1\u2009\u2264\u2009n\u2009\u2264\u20092000, \u2009-\u2009107\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009107)\u00a0\u2014 the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi (\u2009-\u2009107\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009107)\u00a0\u2014 the coordinates of the i-th flower. It is guaranteed that all n\u2009+\u20092 points in the input are distinct.", "output_spec": "Print the minimum possible value r12\u2009+\u2009r22. Note, that in this problem optimal answer is always integer.", "sample_inputs": ["2 -1 0 5 3\n0 2\n5 2", "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4"], "sample_outputs": ["6", "33"], "notes": "NoteThe first sample is (r12\u2009=\u20095, r22\u2009=\u20091): The second sample is (r12\u2009=\u20091, r22\u2009=\u200932): "}, "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 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"}, {"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"} {"nl": {"description": "Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i\u2009+\u20091 for all i from 1 to k\u2009-\u20091. Now he wonders how many different ways this can happen. ", "input_spec": "The first line of input will have one integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1\u2009\u2264\u2009ci\u2009\u2264\u20091000). The total number of balls doesn't exceed 1000.", "output_spec": "A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1\u2009000\u2009000\u2009007. ", "sample_inputs": ["3\n2\n2\n1", "4\n1\n2\n3\n4"], "sample_outputs": ["3", "1680"], "notes": "NoteIn the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 31 1 2 2 32 1 1 2 3"}, "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": "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"}, {"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"} {"nl": {"description": "Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times: $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$), $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$), $$$a := a \\ | \\ b$$$ (replace $$$a$$$ with the bitwise OR of $$$a$$$ and $$$b$$$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The only line for each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a < b \\le 10^6$$$). It is guaranteed that the sum of $$$b$$$ over all test cases does not exceed $$$10^6$$$.", "output_spec": "For each test case print one integer \u2014 the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.", "sample_inputs": ["5\n1 3\n5 8\n2 5\n3 19\n56678 164422"], "sample_outputs": ["1\n3\n2\n1\n23329"], "notes": "NoteIn the first test case, it is optimal to apply the third operation.In the second test case, it is optimal to apply the first operation three times.In the third test case, it is optimal to apply the second operation and then the third operation."}, "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(a, b) = readInts()\n val answers = a.to(2 * b).map{ desiredA =>\n (desiredA - a) + ((desiredA | b) - b) +\n (if (desiredA != (desiredA | b)) 1 else 0)\n }\n\n val answer2 = {\n val increasingBStep = b.until(2 * b).find { desiredB =>\n (desiredB | a) == desiredB\n }.get - b + 1\n val increasingAStep = b - a\n Math.min(increasingBStep, increasingAStep)\n }\n\n println(Math.min(answers.min, answer2))\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 Array(a, b) = readInts()\n val answer = {\n val increasingBStep = b.until(2 * b).find { desiredB =>\n (desiredB | a) == desiredB\n }.get - b + 1\n val increasingAStep = b - a\n Math.min(increasingBStep, increasingAStep)\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"}], "src_uid": "eed751c881767ecd978a728d980da594"} {"nl": {"description": "A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence $$$s$$$ and an integer number $$$k$$$. Your task is to find a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$.It is guaranteed that such sequence always exists.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le k \\le n \\le 2 \\cdot 10^5$$$, both $$$n$$$ and $$$k$$$ are even) \u2014 the length of $$$s$$$ and the length of the sequence you are asked to find. The second line is a string $$$s$$$ \u2014 regular bracket sequence of length $$$n$$$.", "output_spec": "Print a single string \u2014 a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$. It is guaranteed that such sequence always exists.", "sample_inputs": ["6 4\n()(())", "8 8\n(()(()))"], "sample_outputs": ["()()", "(()(()))"], "notes": null}, "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\u306b\u5bfe\u3057\u3066+1index\n val last = Array.fill[Int](N / 2 + 1)(-1)\n last(0) = 0\n val pair = Array.ofDim[Int](N) // '('\u306e\u3064\u3044\u306b\u306a\u308b')'\u304c\u3069\u3053\u306b\u3042\u308b\u304b\n // \u30eb\u30fc\u30d7\u3059\u308b\u306e\u306fstack\u306eindex\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\u306eindex\u304b\u3089S\u306eindex\u306b\u3059\u308b\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 // \u5bfe\u306b\u306a\u308b\u304b\u3063\u3053\u3092\u5fc5\u8981\u5206\u6d88\u3059\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": "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"}, {"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\u3068\u306findex\u304c1\u305a\u308c\u3066\u308b\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 \u5de6\u306e0\n * @param r \u53f3\u306e0\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\u4e0a\u30670-0 == \u5de6\u306eindex+1\u304b\u3089\u306f\u3058\u3081\u3066\u53f3\u306eindex\u307e\u3067\u3067\u3061\u3087\u3046\u3069\u30b9\u30bf\u30c3\u30af\u304c0\u306b\u306a\u308b\n // stack-1\u3067\u3061\u3087\u3046\u3069S\u306eindex\u3068\u540c\u3058\u306b\u306a\u308b\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"} {"nl": {"description": "There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete\u00a0\u2014 the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\\max(A) - \\min(B)|$$$ is as small as possible, where $$$\\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is: first team: $$$A = [1, 2, 4]$$$, second team: $$$B = [3, 6]$$$. In this case, the value $$$|\\max(A) - \\min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\\max(A) - \\min(B)|$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains positive integer $$$n$$$ ($$$2 \\le n \\le 50$$$)\u00a0\u2014 number of athletes. The second line contains $$$n$$$ positive integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$1 \\le s_i \\le 1000$$$), where $$$s_i$$$\u00a0\u2014 is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum value of $$$|\\max(A) - \\min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.", "sample_inputs": ["5\n5\n3 1 2 6 4\n6\n2 1 3 2 4 3\n4\n7 9 3 1\n2\n1 1000\n3\n100 150 200"], "sample_outputs": ["1\n0\n2\n999\n50"], "notes": "NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "The robot is located on a checkered rectangular board of size $$$n \\times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns\u00a0\u2014 from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \\times 3$$$, if the robot starts a sequence of actions $$$s=$$$\"RRDLUU\" (\"right\", \"right\", \"down\", \"left\", \"up\", \"up\") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^6$$$)\u00a0\u2014 the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U'\u00a0\u2014 the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.", "output_spec": "Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \\leq r \\leq n$$$) and $$$c$$$ ($$$1 \\leq c \\leq m$$$), separated by a space\u00a0\u2014 the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.", "sample_inputs": ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"], "sample_outputs": ["1 1\n1 2\n2 1\n3 2"], "notes": null}, "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 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 m = readInt()\n val s = readString()\n var x = 0\n var y = 0\n var minx = 0\n var maxx = 0\n var miny = 0\n var maxy = 0\n var ind = 0\n while (maxx-minx < m && maxy-miny < n && ind < s.length) {\n if (s(ind) == 'L')\n x -= 1\n if (s(ind) == 'R')\n x += 1\n if (s(ind) == 'U')\n y -= 1\n if (s(ind) == 'D')\n y += 1\n minx = min(minx, x)\n maxx = max(maxx, x)\n miny = min(miny, y)\n maxy = max(maxy, y)\n ind += 1\n }\n if (maxx-minx == m || maxy-miny == n) {\n if (s(ind-1) == 'L')\n minx += 1\n if (s(ind-1) == 'R')\n maxx -= 1\n if (s(ind-1) == 'U')\n miny += 1\n if (s(ind-1) == 'D')\n maxy -= 1\n }\n writer.print(1 - miny + \" \")\n writer.println(1 - minx)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "585bb4a040144da39ed240366193e705"} {"nl": {"description": "Gottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of $$$n$$$ non-negative integers $$$a_1, \\ldots, a_n$$$. You are allowed to perform the following operation: choose two distinct indices $$$1 \\leq i, j \\leq n$$$. If before the operation $$$a_i = x$$$, $$$a_j = y$$$, then after the operation $$$a_i = x~\\mathsf{AND}~y$$$, $$$a_j = x~\\mathsf{OR}~y$$$, where $$$\\mathsf{AND}$$$ and $$$\\mathsf{OR}$$$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute $$$\\sum_{i=1}^n a_i^2$$$\u00a0\u2014 the sum of squares of all $$$a_i$$$. What is the largest sum of squares you can achieve?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, \\ldots, a_n$$$ ($$$0 \\leq a_i < 2^{20}$$$).", "output_spec": "Print a single integer\u00a0\u2014 the largest possible sum of squares that can be achieved after several (possibly zero) operations.", "sample_inputs": ["1\n123", "3\n1 3 5", "2\n349525 699050"], "sample_outputs": ["15129", "51", "1099509530625"], "notes": "NoteIn the first sample no operation can be made, thus the answer is $$$123^2$$$.In the second sample we can obtain the collection $$$1, 1, 7$$$, and $$$1^2 + 1^2 + 7^2 = 51$$$.If $$$x$$$ and $$$y$$$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $$$x~\\mathsf{AND}~y$$$ is set to $$$1$$$ if and only if both corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. Similarly, each bit of $$$x~\\mathsf{OR}~y$$$ is set to $$$1$$$ if and only if at least one of the corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. For example, $$$x = 3$$$ and $$$y = 5$$$ are represented as $$$011_2$$$ and $$$101_2$$$ (highest bit first). Then, $$$x~\\mathsf{AND}~y = 001_2 = 1$$$, and $$$x~\\mathsf{OR}~y = 111_2 = 7$$$."}, "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = nextInts(n)\n val bits = Array.fill(30)(0)\n\n for (_a <- as) {\n var a = _a\n var pos = 0\n while (a > 0) {\n if ((a & 1) != 0) {\n bits(pos) += 1\n }\n a >>= 1\n pos += 1\n }\n }\n\n var res = BigInt(0)\n var done = false\n while (!done) {\n val non0 = bits.filter(_ > 0)\n if (non0.nonEmpty) {\n val min = non0.min\n var num = 0L\n for (i <- bits.indices) {\n if (bits(i) > 0) {\n bits(i) -= min\n num += 1L << i\n }\n }\n res += num * num * min\n } else {\n done = true\n }\n }\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": [], "src_uid": "56fbdca75b69bf41d2a45a1dfe81d022"} {"nl": {"description": "Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet \u2014 it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw \u2014 it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1\u2009<\u2009v\u2009<\u2009n), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. ", "input_spec": "The first line of input contains two space-separated integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, n\u2009-\u20091\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi, 1\u2009\u2264\u2009ci\u2009\u2264\u2009104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists.", "output_spec": "Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is ai\u2009\u2192\u2009bi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them.", "sample_inputs": ["3 3\n3 2 10\n1 2 10\n3 1 5", "4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5"], "sample_outputs": ["1\n0\n1", "0\n0\n1\n1\n0"], "notes": "NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: ."}, "positive_code": [{"source_code": "import collection.mutable.ArrayBuffer\nimport collection.mutable.Queue\n\nobject test6 extends App {\n class Edge(val b:Int, val c:Int, val d:Int, val i:Int){}\n\n val Array(n,m)=readLine.split(\" \").map(_.toInt)\n val vertices=new Array[ArrayBuffer[Edge]](n)\n for(i<-0 until n) vertices(i)=new ArrayBuffer[Edge]\n val flow=new Array[Int](n)\n val ans=new Array[Int](m)\n val v=new Array[Boolean](n)\n \n for(i<- 0 until m){\n val Array(a,b,c)=readLine.split(\" \").map(_.toInt)\n vertices(a-1)+=new Edge(b-1,c,0,i)\n vertices(b-1)+=new Edge(a-1,c,1,i)\n flow(a-1)+=c\n flow(b-1)+=c\n }\n for(i<-1 until n-1) flow(i)/=2\n \n val queue=new Queue[Int]\n queue.enqueue(0)\n v(0)=true\n while(queue.nonEmpty){\n val next=queue.dequeue\n vertices(next).foreach(edge=>{\n if(!v(edge.b)){\n ans(edge.i)=edge.d\n flow(edge.b)-=edge.c\n if(flow(edge.b)==0 && edge.b!=n-1) {v(edge.b)=true;queue.enqueue(edge.b)}\n }\n })\n }\n \n println(ans.mkString(\"\\n\"))\n} \n\n\n"}], "negative_code": [], "src_uid": "f065e8c469a5a71a9ef602b6d8bfc9e2"} {"nl": {"description": "The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$=\"arrayhead\" and $$$t_i$$$=\"arya\" $$$5$$$ letters have to be bought (\"arrayhead\"). For example, for $$$s$$$=\"arrayhead\" and $$$t_i$$$=\"harry\" $$$6$$$ letters have to be bought (\"arrayhead\"). For example, for $$$s$$$=\"arrayhead\" and $$$t_i$$$=\"ray\" $$$5$$$ letters have to be bought (\"arrayhead\"). For example, for $$$s$$$=\"arrayhead\" and $$$t_i$$$=\"r\" $$$2$$$ letters have to be bought (\"arrayhead\"). For example, for $$$s$$$=\"arrayhead\" and $$$t_i$$$=\"areahydra\" all $$$9$$$ letters have to be bought (\"arrayhead\"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \\le m \\le 5 \\cdot 10^4$$$) \u2014 the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \\le |t_i| \\le 2 \\cdot 10^5$$$) \u2014 the name of the $$$i$$$-th friend. It is guaranteed that $$$\\sum \\limits_{i=1}^m |t_i| \\le 2 \\cdot 10^5$$$.", "output_spec": "For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.", "sample_inputs": ["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"], "sample_outputs": ["5\n6\n5\n2\n9"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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": "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"}, {"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"} {"nl": {"description": "Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset!", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009k\u2009\u2264\u20094)\u00a0\u2014 the number of problems and the number of experienced teams. Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.", "output_spec": "Print \"YES\" (quotes for clarity), if it is possible to make an interesting problemset, and \"NO\" otherwise. You can print each character either upper- or lowercase (\"YeS\" and \"yes\" are valid when the answer is \"YES\").", "sample_inputs": ["5 3\n1 0 1\n1 1 0\n1 0 0\n1 0 0\n1 0 0", "3 2\n1 0\n1 1\n0 1"], "sample_outputs": ["NO", "YES"], "notes": "NoteIn the first example you can't make any interesting problemset, because the first team knows all problems.In the second example you can choose the first and the third problems."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.HashSet\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n var inputLine = scala.io.StdIn.readLine().split(\" \")\n var tasksNumber:Int = inputLine(0).toInt\n var teamsNum:Int = inputLine(1).toInt\n\n var set: mutable.HashSet[List[Int]] = new mutable.HashSet[List[Int]]()\n\n def input():Boolean = {\n var res:Boolean = false\n 0 until tasksNumber foreach (i => {\n var newTask: List[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n if (smartSort(newTask, set)) {\n res = true;\n }\n })\n res\n }\n\n def smartSort(in: List[Int], set: mutable.HashSet[List[Int]]):Boolean = {\n if(!set.contains(in)) {\n var precheck = true\n in.foreach(i => if(i != 0) precheck = false)\n if(precheck) return true\n \n var requiredIndeces = in.indices.filter(i => in(i) == 1).toList\n\n set.toStream.foreach(e => {\n var res:Boolean = true\n requiredIndeces.foreach(i => if(e(i) != 0) res = false)\n if(res) return true\n })\n set += in\n }\n false\n }\n\n if(input()) println(\"YES\") else println(\"NO\")\n}\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.HashSet\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n var inputLine = scala.io.StdIn.readLine().split(\" \")\n var tasksNumber:Int = inputLine(0).toInt\n var teamsNum:Int = inputLine(1).toInt\n\n var set: mutable.HashSet[List[Int]] = new mutable.HashSet[List[Int]]()\n\n def input():Boolean = {\n var res:Boolean = false\n 0 until tasksNumber foreach (i => {\n var newTask: List[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n if (smartSort(newTask, set)) {\n res = true;\n }\n })\n res\n }\n\n def smartSort(in: List[Int], set: mutable.HashSet[List[Int]]):Boolean = {\n if(!set.contains(in)) {\n var requiredIndeces = in.indices.filter(i => in(i) == 1).toList\n\n set.toStream.foreach(e => {\n var res:Boolean = true\n requiredIndeces.foreach(i => if(e(i) != 0) res = false)\n if(res) return true\n })\n set += in\n }\n false\n }\n\n if(input()) println(\"YES\") else println(\"NO\")\n}\n\n"}, {"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.HashSet\nimport scala.collection.mutable.ListBuffer\n\nobject Main extends App {\n var inputLine = scala.io.StdIn.readLine().split(\" \")\n var tasksNumber:Int = inputLine(0).toInt\n var teamsNum:Int = inputLine(1).toInt\n\n var set: mutable.HashSet[List[Int]] = new mutable.HashSet[List[Int]]()\n\n def input():Boolean = {\n var res:Boolean = false\n 0 until tasksNumber foreach (i => {\n var newTask: List[Int] = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n if (smartSort(newTask, set)) {\n res = true;\n }\n })\n res\n }\n\n def smartSort(in: List[Int], set: mutable.HashSet[List[Int]]):Boolean = {\n if(!set.contains(in)) {\n var requiredIndeces = in.indices.filter(i => in(i) == 0).toList\n\n set.toStream.foreach(e => {\n var res:Boolean = true\n requiredIndeces.foreach(i => if(e(i) != 1) res = false)\n if(res) return true\n })\n set += in\n }\n false\n }\n\n if(input()) println(\"YES\") else println(\"NO\")\n}\n\n"}], "src_uid": "0928e12caeb71d631a26912c5606b568"} {"nl": {"description": "You are given $$$n$$$ arrays $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; each array consists of exactly $$$m$$$ integers. We denote the $$$y$$$-th element of the $$$x$$$-th array as $$$a_{x, y}$$$.You have to choose two arrays $$$a_i$$$ and $$$a_j$$$ ($$$1 \\le i, j \\le n$$$, it is possible that $$$i = j$$$). After that, you will obtain a new array $$$b$$$ consisting of $$$m$$$ integers, such that for every $$$k \\in [1, m]$$$ $$$b_k = \\max(a_{i, k}, a_{j, k})$$$.Your goal is to choose $$$i$$$ and $$$j$$$ so that the value of $$$\\min \\limits_{k = 1}^{m} b_k$$$ is maximum possible.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 3 \\cdot 10^5$$$, $$$1 \\le m \\le 8$$$) \u2014 the number of arrays and the number of elements in each array, respectively. Then $$$n$$$ lines follow, the $$$x$$$-th line contains the array $$$a_x$$$ represented by $$$m$$$ integers $$$a_{x, 1}$$$, $$$a_{x, 2}$$$, ..., $$$a_{x, m}$$$ ($$$0 \\le a_{x, y} \\le 10^9$$$).", "output_spec": "Print two integers $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$, it is possible that $$$i = j$$$) \u2014 the indices of the two arrays you have to choose so that the value of $$$\\min \\limits_{k = 1}^{m} b_k$$$ is maximum possible. If there are multiple answers, print any of them.", "sample_inputs": ["6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0"], "sample_outputs": ["1 5"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of digits on the display. The second line contains n digits\u00a0\u2014 the initial state of the display.", "output_spec": "Print a single line containing n digits\u00a0\u2014 the desired state of the display containing the smallest possible number.", "sample_inputs": ["3\n579", "4\n2014"], "sample_outputs": ["024", "0142"], "notes": null}, "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 = 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}"}, {"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 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}"}, {"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}"}], "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"} {"nl": {"description": "Now you get Baby Ehab's first words: \"Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \\ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$.\" Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$.", "input_spec": "The only line contains the integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$).", "output_spec": "The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any.", "sample_inputs": ["5", "8"], "sample_outputs": ["3\n1 2 3", "4\n1 3 5 7"], "notes": "NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$."}, "positive_code": [{"source_code": "object Solver {\r\n import InOut._\r\n def main(args: Array[String]): Unit = {\r\n @annotation.tailrec\r\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\r\n \r\n val n = nextInt\r\n val coprime = for (i <- 1 until n if gcd(i, n) == 1) yield i\r\n val prod = coprime.foldLeft(1: Long)(_ * _ % n)\r\n val ans = if (prod == 1) coprime else {\r\n val pos = coprime indexOf prod\r\n assert(pos != -1)\r\n coprime.take(pos) ++ coprime.takeRight(coprime.length - pos - 1)\r\n }\r\n out.println(ans length)\r\n out.println(ans mkString \" \")\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}"}], "negative_code": [{"source_code": "object Solver {\r\n import InOut._\r\n def main(args: Array[String]): Unit = {\r\n @annotation.tailrec\r\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\r\n \r\n val n = nextInt\r\n val coprime = for (i <- 1 until n if gcd(i, n) == 1) yield i\r\n val prod = coprime.foldLeft(1)(_ * _ % n)\r\n val ans = if (prod == 1) coprime else {\r\n val pos = coprime indexOf prod\r\n coprime.take(pos) ++ coprime.takeRight(coprime.length - pos - 1)\r\n }\r\n out.println(ans length)\r\n out.println(ans mkString \" \")\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}"}], "src_uid": "d55afdb4a83aebdfce5a62e4ec934adb"} {"nl": {"description": "There are $$$n$$$ models in the shop numbered from $$$1$$$ to $$$n$$$, with sizes $$$s_1, s_2, \\ldots, s_n$$$.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $$$i_j$$$ and $$$i_{j+1}$$$ (note that $$$i_j < i_{j+1}$$$, because Orac arranged them properly), $$$i_{j+1}$$$ is divisible by $$$i_j$$$ and $$$s_{i_j} < s_{i_{j+1}}$$$.For example, for $$$6$$$ models with sizes $$$\\{3, 6, 7, 7, 7, 7\\}$$$, he can buy models with indices $$$1$$$, $$$2$$$, and $$$6$$$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.", "input_spec": "The first line contains one integer $$$t\\ (1 \\le t\\le 100)$$$: the number of queries. Each query contains two lines. The first line contains one integer $$$n\\ (1\\le n\\le 100\\,000)$$$: the number of models in the shop, and the second line contains $$$n$$$ integers $$$s_1,\\dots,s_n\\ (1\\le s_i\\le 10^9)$$$: the sizes of models. It is guaranteed that the total sum of $$$n$$$ is at most $$$100\\,000$$$.", "output_spec": "Print $$$t$$$ lines, the $$$i$$$-th of them should contain the maximum number of models that Orac can buy for the $$$i$$$-th query.", "sample_inputs": ["4\n4\n5 3 4 6\n7\n1 4 2 3 6 4 9\n5\n5 4 3 2 1\n1\n9"], "sample_outputs": ["2\n3\n1\n1"], "notes": "NoteIn the first query, for example, Orac can buy models with indices $$$2$$$ and $$$4$$$, the arrangement will be beautiful because $$$4$$$ is divisible by $$$2$$$ and $$$6$$$ is more than $$$3$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $$$1$$$, $$$3$$$, and $$$6$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants: if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag; if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column; if $$$i < n$$$ and $$$|h_i - h_{i+1}| \\le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.", "input_spec": "Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$0 \\le m \\le 10^6$$$, $$$0 \\le k \\le 10^6$$$) \u2014 the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $$$k$$$ described in the statement. The second line of each test case contains $$$n$$$ integers. The $$$i$$$-th integer is $$$h_i$$$ ($$$0 \\le h_i \\le 10^6$$$), the initial height of the $$$i$$$-th column.", "output_spec": "For each test case, print \"YES\" if it is possible to win the game. Otherwise, print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["5\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"], "sample_outputs": ["YES\nNO\nYES\nNO\nYES"], "notes": "NoteIn the first case, Gildong can take one block from the $$$1$$$-st column, move to the $$$2$$$-nd column, put the block on the $$$2$$$-nd column, then move to the $$$3$$$-rd column.In the second case, Gildong has to put the block in his bag on the $$$1$$$-st column to get to the $$$2$$$-nd column. But it is impossible to get to the $$$3$$$-rd column because $$$|h_2 - h_3| = 3 > k$$$ and there is no way to decrease the gap.In the fifth case, the character is already on the $$$n$$$-th column from the start so the game is won instantly."}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \\ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if: $$$i = j$$$, that is, they are at the same index. $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times: choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \\ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \\ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.", "input_spec": "The first line of the input contains a single integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^5)$$$\u00a0\u2014 the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \\le a_i \\le n)$$$ \u2014 the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \\le b_i \\le n)$$$ \u2014 the elements of the second permutation.", "output_spec": "Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.", "sample_inputs": ["5\n1 2 3 4 5\n2 3 4 5 1", "5\n5 4 3 2 1\n1 2 3 4 5", "4\n1 3 2 4\n4 2 3 1"], "sample_outputs": ["5", "1", "2"], "notes": "NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\\{1, 2, 3, 4, 5\\}$$$ and $$$\\{1, 2, 3, 4, 5\\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\\{1, 3, 2, 4\\}$$$ and $$$\\{2, 3, 1, 4\\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$."}, "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 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"}, {"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"}, {"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 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}"}], "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"} {"nl": {"description": "On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. ", "input_spec": "The first line of the input contains five positive integers n, l, v1, v2 and k (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000, 1\u2009\u2264\u2009l\u2009\u2264\u2009109, 1\u2009\u2264\u2009v1\u2009<\u2009v2\u2009\u2264\u2009109, 1\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. ", "output_spec": "Print the real number\u00a0\u2014 the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10\u2009-\u20096.", "sample_inputs": ["5 10 1 2 5", "3 6 1 2 1"], "sample_outputs": ["5.0000000000", "4.7142857143"], "notes": "NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10\u2009/\u20092\u2009=\u20095."}, "positive_code": [{"source_code": "//package d\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, l, _v1, _v2, k) = readInts(5)\n val v1 = _v1.toDouble\n val v2 = _v2.toDouble\n\n if (v1 >= v2) {\n println(l / v1)\n } else {\n\n def can(timeLimit: Double): Boolean = {\n\n var time = 0d\n var walking = n\n var walkingPos = 0d\n\n while (walking > k) {\n\n walking -= k\n\n //val driveTo1 = Math.min(l, l - v1 * (timeLimit - time))\n //val drivingTime = (driveTo1 - walkingPos) / v2\n val drivingTime = Math.max(0, l - walkingPos - v1 * (timeLimit - time)) / (v2 - v1)\n val driveTo1 = walkingPos + drivingTime * v2\n time += drivingTime\n walkingPos += v1 * drivingTime\n\n //val driveTo2 = Math.min(l, l - v1 * (timeLimit - time))\n val returnTime = (driveTo1 - walkingPos) / (v1 + v2)\n time += returnTime\n walkingPos += v1 * returnTime\n //println(walking, time, drivingTime, returnTime)\n }\n\n //time += Math.max((l - walkingPos) / v2, timeLimit - time)\n time += (l - walkingPos) / v2\n//println(time, timeLimit)\n time <= timeLimit\n }\n\n @annotation.tailrec\n def binSearchD(lo: Double, hi: Double, depth: Int): Double = {\n val mid = (lo + hi) / 2\n //println(lo, hi)\n if (depth > 60) mid\n else {\n if (!can(mid)) binSearchD(mid, hi, depth + 1)\n else binSearchD(lo, mid, depth + 1)\n }\n }\n\n val res = binSearchD(l / v2, l / v1, 0)\n\n //can(4.5d)\n\n println(res)\n }\n}\n"}], "negative_code": [], "src_uid": "620a9baa531f0c614cc103e70cfca6fd"} {"nl": {"description": "Karafs is some kind of vegetable in shape of an 1\u2009\u00d7\u2009h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si\u2009=\u2009A\u2009+\u2009(i\u2009-\u20091)\u2009\u00d7\u2009B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l\u2009\u2264\u2009r and sequence sl,\u2009sl\u2009+\u20091,\u2009...,\u2009sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.", "input_spec": "The first line of input contains three integers A, B and n (1\u2009\u2264\u2009A,\u2009B\u2009\u2264\u2009106, 1\u2009\u2264\u2009n\u2009\u2264\u2009105). Next n lines contain information about queries. i-th line contains integers l,\u2009t,\u2009m (1\u2009\u2264\u2009l,\u2009t,\u2009m\u2009\u2264\u2009106) for i-th query.", "output_spec": "For each query, print its answer in a single line.", "sample_inputs": ["2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8", "1 5 2\n1 5 10\n2 7 4"], "sample_outputs": ["4\n-1\n8\n-1", "1\n2"], "notes": null}, "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(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"}, {"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"} {"nl": {"description": "Ridhiman challenged Ashish to find the maximum valued subsequence of an array $$$a$$$ of size $$$n$$$ consisting of positive integers. The value of a non-empty subsequence of $$$k$$$ elements of $$$a$$$ is defined as $$$\\sum 2^i$$$ over all integers $$$i \\ge 0$$$ such that at least $$$\\max(1, k - 2)$$$ elements of the subsequence have the $$$i$$$-th bit set in their binary representation (value $$$x$$$ has the $$$i$$$-th bit set in its binary representation if $$$\\lfloor \\frac{x}{2^i} \\rfloor \\mod 2$$$ is equal to $$$1$$$). Recall that $$$b$$$ is a subsequence of $$$a$$$, if $$$b$$$ can be obtained by deleting some(possibly zero) elements from $$$a$$$.Help Ashish find the maximum value he can get by choosing some subsequence of $$$a$$$.", "input_spec": "The first line of the input consists of a single integer $$$n$$$ $$$(1 \\le n \\le 500)$$$\u00a0\u2014 the size of $$$a$$$. The next line consists of $$$n$$$ space-separated integers\u00a0\u2014 the elements of the array $$$(1 \\le a_i \\le 10^{18})$$$.", "output_spec": "Print a single integer\u00a0\u2014 the maximum value Ashish can get by choosing some subsequence of $$$a$$$.", "sample_inputs": ["3\n2 1 3", "3\n3 1 4", "1\n1", "4\n7 7 1 1"], "sample_outputs": ["3", "7", "1", "7"], "notes": "NoteFor the first test case, Ashish can pick the subsequence $$$\\{{2, 3}\\}$$$ of size $$$2$$$. The binary representation of $$$2$$$ is 10 and that of $$$3$$$ is 11. Since $$$\\max(k - 2, 1)$$$ is equal to $$$1$$$, the value of the subsequence is $$$2^0 + 2^1$$$ (both $$$2$$$ and $$$3$$$ have $$$1$$$-st bit set in their binary representation and $$$3$$$ has $$$0$$$-th bit set in its binary representation). Note that he could also pick the subsequence $$$\\{{3\\}}$$$ or $$$\\{{2, 1, 3\\}}$$$.For the second test case, Ashish can pick the subsequence $$$\\{{3, 4\\}}$$$ with value $$$7$$$.For the third test case, Ashish can pick the subsequence $$$\\{{1\\}}$$$ with value $$$1$$$.For the fourth test case, Ashish can pick the subsequence $$$\\{{7, 7\\}}$$$ with value $$$7$$$."}, "positive_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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ \u2014 these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10000$$$) \u2014 the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 150000$$$) \u2014 the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.", "output_spec": "Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.", "sample_inputs": ["5\n6\n3 9 4 6 7 5\n1\n1000000\n2\n2 1\n10\n31 41 59 26 53 58 97 93 23 84\n7\n3 2 1 2 3 4 5"], "sample_outputs": ["3\n0\n1\n8\n2"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "The map of Berland is a rectangle of the size n\u2009\u00d7\u2009m, which consists of cells of size 1\u2009\u00d7\u20091. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k. ", "input_spec": "The first line of the input contains three integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950, 0\u2009\u2264\u2009k\u2009\u2264\u200950)\u00a0\u2014 the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each \u2014 the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.", "output_spec": "In the first line print the minimum number of cells which should be transformed from water to land. In the next n lines print m symbols \u2014 the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them. It is guaranteed that the answer exists on the given data.", "sample_inputs": ["5 4 1\n****\n*..*\n****\n**.*\n..**", "3 3 0\n***\n*.*\n***"], "sample_outputs": ["1\n****\n*..*\n****\n****\n..**", "1\n***\n***\n***"], "notes": "NoteIn the first example there are only two lakes \u2014 the first consists of the cells (2,\u20092) and (2,\u20093), the second consists of the cell (4,\u20093). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean. "}, "positive_code": [{"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 map = in.take(n).map(_.toCharArray.map(_.toString)).toArray\n var lakes = List.empty[(Int, String)]\n var bays = Set.empty[String]\n var id = 0\n\n def process(i: Int, j: Int, color: String): Int = {\n if (i == -1 || j == -1 || i == n || j == m) {\n bays += color\n 0\n }\n else if (map(i)(j) == \".\") {\n map(i)(j) = color\n process(i - 1, j, color) +\n process(i + 1, j, color) +\n process(i, j - 1, color) +\n process(i, j + 1, color) + 1\n } else 0\n }\n\n (0 until n).foreach { i =>\n (0 until m).foreach { j =>\n if (map(i)(j) == \".\") {\n val size = process(i, j, id.toString)\n if (!bays.contains(id.toString))\n lakes ::= (size, id.toString)\n id += 1\n }\n }\n }\n\n val dropLakes = lakes.sorted.reverse.drop(k)\n val count = dropLakes.map(_._1).sum\n val dropLakesId = dropLakes.map(_._2).toSet\n\n\n (0 until n).foreach { i =>\n (0 until m).foreach { j =>\n if (map(i)(j) != \"*\") {\n if (dropLakesId.contains(map(i)(j)))\n map(i)(j) = \"*\"\n else\n map(i)(j) = \".\"\n }\n }\n }\n println(count)\n println(map.map(_.mkString).mkString(\"\\n\"))\n\n}"}], "negative_code": [], "src_uid": "e514d949e7837c603a9ee032f83b90d2"} {"nl": {"description": "The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.", "input_spec": "The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.", "output_spec": "In the single line print the number that is written without leading zeroes in the binary notation \u2014 the answer to the problem.", "sample_inputs": ["101", "110010"], "sample_outputs": ["11", "11010"], "notes": "NoteIn the first sample the best strategy is to delete the second digit. That results in number 112\u2009=\u2009310.In the second sample the best strategy is to delete the third or fourth digits \u2014 that results in number 110102\u2009=\u20092610."}, "positive_code": [{"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}"}, {"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": "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}"}, {"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}"}], "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"} {"nl": {"description": "A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example: If x\u2009=\u20096 and the crossword is 111011, then its encoding is an array {3,\u20092}; If x\u2009=\u20098 and the crossword is 01101010, then its encoding is an array {2,\u20091,\u20091}; If x\u2009=\u20095 and the crossword is 11111, then its encoding is an array {5}; If x\u2009=\u20095 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!", "input_spec": "The first line contains two integer numbers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009100000, 1\u2009\u2264\u2009x\u2009\u2264\u2009109) \u2014 the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u200910000) \u2014 the encoding.", "output_spec": "Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.", "sample_inputs": ["2 4\n1 3", "3 10\n3 3 2", "2 10\n1 3"], "sample_outputs": ["NO", "YES", "NO"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val Array(n, x) = readLine split ' ' map(_.toLong)\n val a = readLine split ' ' map(_.toLong)\n if (x == (a sum) + (n - 1))\n println(\"YES\")\n else\n println(\"NO\")\n}"}], "negative_code": [], "src_uid": "080a3458eaea4903da7fa4cf531beba2"} {"nl": {"description": "Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.The teacher gave Andrew an array of n numbers a1, ..., an. After that he asked Andrew for each k from 1 to n\u2009-\u20091 to build a k-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.Andrew looked up on the Wikipedia that a k-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to n, then the children of element v are elements with indices k(v\u2009-\u20091)\u2009+\u20092, ..., kv\u2009+\u20091 (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any k-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote p(v) as the number of the parent of the element with the number v. Let's say that for a non-root element v the property of the heap is violated if av\u2009<\u2009ap(v).Help Andrew cope with the task!", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains n space-separated integers a1, ..., an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "in a single line print n\u2009-\u20091 integers, separate the consecutive numbers with a single space \u2014 the number of elements for which the property of the k-ary heap is violated, for k\u2009=\u20091, 2, ..., n\u2009-\u20091.", "sample_inputs": ["5\n1 5 4 3 2", "6\n2 2 2 2 2 2"], "sample_outputs": ["3 2 1 0", "0 0 0 0 0"], "notes": "NotePictures with the heaps for the first sample are given below; elements for which the property of the heap is violated are marked with red. In the second sample all elements are equal, so the property holds for all pairs."}, "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 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"}, {"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"} {"nl": {"description": "There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.", "input_spec": "The first line contains two positive space-separated integers, n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106), which represent the population of each city in Westeros.", "output_spec": "Print string \"Daenerys\" (without the quotes), if Daenerys wins and \"Stannis\" (without the quotes), if Stannis wins.", "sample_inputs": ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"], "sample_outputs": ["Stannis", "Daenerys", "Stannis"], "notes": "NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins."}, "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, k) = readInts(2)\n val as = readInts(n)\n \n val moves = n - k\n val bMoves = (n - k) / 2\n val aMoves = n - k - bMoves\n \n val odd = as.count(_ % 2 == 1)\n val even = n - odd\n \n val winner = if (odd <= bMoves) 0\n else if (even <= bMoves) k % 2\n else if (n == k) odd % 2\n else moves % 2\n\n println(if (winner == 0) \"Daenerys\" else \"Stannis\")\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 as = readInts(n)\n \n val moves = n - k\n val bMoves = (n - k) / 2\n val aMoves = n - k - bMoves\n \n val odd = as.count(_ % 2 == 1)\n val even = n - odd\n \n val winner = if (odd <= bMoves) 0\n else if (even <= aMoves && k % 2 == 1) 1\n else if (n == k) odd % 2\n else moves % 2\n\n println(if (winner == 0) \"Daenerys\" else \"Stannis\")\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 as = readInts(n)\n \n val moves = n - k\n val bMoves = (n - k) / 2\n val aMoves = n - k - bMoves\n \n val odd = as.count(_ % 2 == 1)\n val even = n - odd\n \n val winner = if (odd <= bMoves) 0\n else if (even <= aMoves) k % 2\n else if (n == k) odd % 2\n else moves % 2\n\n println(if (winner == 0) \"Daenerys\" else \"Stannis\")\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 as = readInts(n)\n \n val bMoves = (n - k) / 2\n val aMoves = n - k - bMoves\n \n val odd = as.count(_ % 2 == 1)\n val even = n - odd\n \n val winner = if (odd <= bMoves) 0\n else if (even <= aMoves && k % 2 == 1) 1\n else if (n == k) odd % 2\n else 1\n\n println(if (winner == 0) \"Daenerys\" else \"Stannis\")\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 as = readInts(n)\n \n val bMoves = (n - k) / 2\n val aMoves = n - k - bMoves\n \n val odd = as.count(_ % 2 == 1)\n val even = n - odd\n \n val winner = if (odd <= bMoves) 0\n else if (even <= aMoves && k % 2 == 1) 1\n else 1\n\n println(if (winner == 0) \"Daenerys\" else \"Stannis\")\n}\n"}], "src_uid": "67e51db4d96b9f7996aea73cbdba3584"} {"nl": {"description": "This is an interactive problem.Bob lives in a square grid of size $$$n \\times n$$$, with rows numbered $$$1$$$ through $$$n$$$ from top to bottom, and columns numbered $$$1$$$ through $$$n$$$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $$$n$$$.Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed.You can ask at most $$$4 \\cdot n$$$ queries of form \"? $$$r_1$$$ $$$c_1$$$ $$$r_2$$$ $$$c_2$$$\" ($$$1 \\le r_1 \\le r_2 \\le n$$$, $$$1 \\le c_1 \\le c_2 \\le n$$$). The answer will be \"YES\" if Bob can get from a cell $$$(r_1, c_1)$$$ to a cell $$$(r_2, c_2)$$$, and \"NO\" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is \"NO\" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $$$n - 1$$$, i.e. the following condition must be satisfied: $$$(r_2 - r_1) + (c_2 - c_1) \\ge n - 1$$$.It's guaranteed that Bob can get from the top-left corner $$$(1, 1)$$$ to the bottom-right corner $$$(n, n)$$$ and your task is to find a way to do it. You should print the answer in form \"! S\" where $$$S$$$ is a string of length $$$2 \\cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $$$1$$$, the right move increases the second coordinate by $$$1$$$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.", "input_spec": "The only line of the input contains an integer $$$n$$$ ($$$2 \\le n \\le 500$$$) \u2014 the size of the grid.", "output_spec": "When you are ready to print the answer, print a single line containing \"! S\" where where $$$S$$$ is a string of length $$$2 \\cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell $$$(1, 1)$$$ to the cell $$$(n, n)$$$ passing only through allowed cells.", "sample_inputs": ["4\n\u00a0\nYES\n\u00a0\nNO\n\u00a0\nYES\n\u00a0\nYES"], "sample_outputs": ["? 1 1 4 4\n\u00a0\n? 1 2 4 3\n\u00a0\n? 4 1 4 4\n\u00a0\n? 1 4 4 4\n\u00a0\n! RDRRDD"], "notes": "NoteThe first example is shown on the picture below. To hack, use the following input format:The first line should contain a single integer $$$n$$$ ($$$2 \\le n \\le 500$$$)\u00a0\u2014 the size of the grid.Each of the next $$$n$$$ lines should contain a string of $$$n$$$ characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell.For example, the following text encodes the example shown above:4..#.#...###....."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n\n def step(from: Int): String = {\n var i, j = from\n val trace = ArrayBuffer[Char]()\n\n def query(query: String): Boolean = {\n println(query)\n ns() match {\n case \"BAD\" =>\n System.exit(0)\n false\n\n case \"YES\" => true\n case \"NO\" => false\n }\n }\n def queryToN(): Boolean = {\n query(s\"? $i ${j+1} $N $N\") // \u53f3\u512a\u5148\n }\n def queryTo1(): Boolean = {\n query(s\"? 1 1 ${i-1} $j\") // \u4e0a\u512a\u5148\n }\n\n while (trace.length < N - 1) {\n if (from == 1) {\n if (queryToN()) { // \u53f3\n j += 1\n trace += 'R'\n } else {\n i += 1\n trace += 'D'\n }\n } else {\n if (queryTo1()) { // \u4e0a\n i -= 1\n trace += 'D'\n } else {\n j -= 1\n trace += 'R'\n }\n }\n }\n\n trace.mkString\n }\n\n val ans = step(1) + step(N).reverse\n println(s\"! $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 }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n var i, j = 1\n val trace = ArrayBuffer[Char]()\n\n def mkQuery(r: Int, c: Int) = {\n if (r - 1 + c - 1 >= N - 1) s\"? 1 1 $r $c\"\n else s\"? $r $c $N $N\"\n }\n\n def queryRight(): Boolean = {\n println(mkQuery(i, j + 1))\n ns() match {\n case \"BAD\" =>\n System.exit(0)\n false\n\n case \"YES\" => true\n case \"NO\" => false\n }\n }\n\n while (i < N && j < N) {\n if (queryRight()) {\n trace += 'R'\n j += 1\n } else {\n trace += 'D'\n i += 1\n }\n }\n\n val (lastD, lastCnt) = if (i == N) ('R', N - j) else ('D', N - i)\n rep(lastCnt)(_ => trace += lastD)\n\n println(s\"! ${trace.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 val N = ni()\n var i, j = 1\n val trace = ArrayBuffer[Char]()\n\n def mkQuery(r: Int, c: Int) = {\n if (r - 1 + c - 1 >= N - 1) s\"? 1 1 $r $c\"\n else s\"? $r $c $N $N\"\n }\n\n def queryRight(): Boolean = {\n println(mkQuery(i, j + 1))\n ns() match {\n case \"BAD\" =>\n System.exit(0)\n false\n\n case \"YES\" => true\n case \"NO\" => false\n }\n }\n\n while (i < N && j < N) {\n if (queryRight()) {\n trace += 'R'\n j += 1\n } else {\n trace += 'D'\n i += 1\n }\n }\n\n var lastD = if (i == N) 'R' else 'D'\n rep(N - j)(_ => trace += lastD)\n\n out.println(s\"! ${trace.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": "fe8734346e123981279747ac26d5a35b"} {"nl": {"description": "In this problem you will have to help Berland army with organizing their command delivery system.There are $$$n$$$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $$$a$$$ is the direct superior of officer $$$b$$$, then we also can say that officer $$$b$$$ is a direct subordinate of officer $$$a$$$.Officer $$$x$$$ is considered to be a subordinate (direct or indirect) of officer $$$y$$$ if one of the following conditions holds: officer $$$y$$$ is the direct superior of officer $$$x$$$; the direct superior of officer $$$x$$$ is a subordinate of officer $$$y$$$. For example, on the picture below the subordinates of the officer $$$3$$$ are: $$$5, 6, 7, 8, 9$$$.The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.Formally, let's represent Berland army as a tree consisting of $$$n$$$ vertices, in which vertex $$$u$$$ corresponds to officer $$$u$$$. The parent of vertex $$$u$$$ corresponds to the direct superior of officer $$$u$$$. The root (which has index $$$1$$$) corresponds to the commander of the army.Berland War Ministry has ordered you to give answers on $$$q$$$ queries, the $$$i$$$-th query is given as $$$(u_i, k_i)$$$, where $$$u_i$$$ is some officer, and $$$k_i$$$ is a positive integer.To process the $$$i$$$-th query imagine how a command from $$$u_i$$$ spreads to the subordinates of $$$u_i$$$. Typical DFS (depth first search) algorithm is used here.Suppose the current officer is $$$a$$$ and he spreads a command. Officer $$$a$$$ chooses $$$b$$$ \u2014 one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $$$a$$$ chooses the one having minimal index. Officer $$$a$$$ gives a command to officer $$$b$$$. Afterwards, $$$b$$$ uses exactly the same algorithm to spread the command to its subtree. After $$$b$$$ finishes spreading the command, officer $$$a$$$ chooses the next direct subordinate again (using the same strategy). When officer $$$a$$$ cannot choose any direct subordinate who still hasn't received this command, officer $$$a$$$ finishes spreading the command.Let's look at the following example: If officer $$$1$$$ spreads a command, officers receive it in the following order: $$$[1, 2, 3, 5 ,6, 8, 7, 9, 4]$$$.If officer $$$3$$$ spreads a command, officers receive it in the following order: $$$[3, 5, 6, 8, 7, 9]$$$.If officer $$$7$$$ spreads a command, officers receive it in the following order: $$$[7, 9]$$$.If officer $$$9$$$ spreads a command, officers receive it in the following order: $$$[9]$$$.To answer the $$$i$$$-th query $$$(u_i, k_i)$$$, construct a sequence which describes the order in which officers will receive the command if the $$$u_i$$$-th officer spreads it. Return the $$$k_i$$$-th element of the constructed list or -1 if there are fewer than $$$k_i$$$ elements in it.You should process queries independently. A query doesn't affect the following queries.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\le n \\le 2 \\cdot 10^5, 1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of officers in Berland army and the number of queries. The second line of the input contains $$$n - 1$$$ integers $$$p_2, p_3, \\dots, p_n$$$ ($$$1 \\le p_i < i$$$), where $$$p_i$$$ is the index of the direct superior of the officer having the index $$$i$$$. The commander has index $$$1$$$ and doesn't have any superiors. The next $$$q$$$ lines describe the queries. The $$$i$$$-th query is given as a pair ($$$u_i, k_i$$$) ($$$1 \\le u_i, k_i \\le n$$$), where $$$u_i$$$ is the index of the officer which starts spreading a command, and $$$k_i$$$ is the index of the required officer in the command spreading sequence.", "output_spec": "Print $$$q$$$ numbers, where the $$$i$$$-th number is the officer at the position $$$k_i$$$ in the list which describes the order in which officers will receive the command if it starts spreading from officer $$$u_i$$$. Print \"-1\" if the number of officers which receive the command is less than $$$k_i$$$. You should process queries independently. They do not affect each other.", "sample_inputs": ["9 6\n1 1 1 3 5 3 5 7\n3 1\n1 5\n3 4\n7 3\n1 8\n1 9"], "sample_outputs": ["3\n6\n8\n-1\n9\n4"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph\u00a0\u2014 something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.", "input_spec": "The first line of the input contains two integers n and m ()\u00a0\u2014 the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1\u2009\u2264\u2009aj\u2009\u2264\u2009109,\u2009bj\u2009=\u2009{0,\u20091}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n\u2009-\u20091 number {bj} are equal to one and exactly m\u2009-\u2009n\u2009+\u20091 of them are equal to zero.", "output_spec": "If Vladislav has made a mistake and such graph doesn't exist, print \u2009-\u20091. Otherwise print m lines. On the j-th line print a pair of vertices (uj,\u2009vj) (1\u2009\u2264\u2009uj,\u2009vj\u2009\u2264\u2009n,\u2009uj\u2009\u2260\u2009vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj\u2009=\u20091 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.", "sample_inputs": ["4 5\n2 1\n3 1\n4 0\n1 1\n5 0", "3 3\n1 0\n2 1\n3 1"], "sample_outputs": ["2 4\n1 4\n3 4\n3 1\n3 2", "-1"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^4$$$)\u00a0\u2014 the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case of input data, output \"YES\" (without quotes), if the array may be not sorted in non-decreasing order, output \"NO\" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).", "sample_inputs": ["3\n3\n2 2 1\n4\n3 1 2 1\n5\n1 2 2 4 4"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$."}, "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 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"}, {"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"} {"nl": {"description": "\"Hey, it's homework time\" \u2014 thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1,\u2009a2,\u2009...,\u2009an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).", "input_spec": "The first line of the input data contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20095000,\u20091\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "Print the only number \u2014 the minimum number of changes needed to get the permutation.", "sample_inputs": ["3\n3 1 2", "2\n2 2", "5\n5 3 3 3 1"], "sample_outputs": ["0", "1", "2"], "notes": "NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2."}, "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 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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$, each of length $$$n$$$ and consisting of lowercase Latin alphabets. You want to make $$$s$$$ equal to $$$t$$$. You can perform the following operation on $$$s$$$ any number of times to achieve it\u00a0\u2014 Choose any substring of $$$s$$$ and rotate it clockwise once, that is, if the selected substring is $$$s[l,l+1...r]$$$, then it becomes $$$s[r,l,l + 1 ... r - 1]$$$. All the remaining characters of $$$s$$$ stay in their position. For example, on rotating the substring $$$[2,4]$$$ , string \"abcde\" becomes \"adbce\". A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find the minimum number of operations required to convert $$$s$$$ to $$$t$$$, or determine that it's impossible.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1\\leq t \\leq 2000)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\\leq n \\leq 2000)$$$\u00a0\u2014 the length of the strings. The second and the third lines contain strings $$$s$$$ and $$$t$$$ respectively. The sum of $$$n$$$ over all the test cases does not exceed $$$2000$$$.", "output_spec": "For each test case, output the minimum number of operations to convert $$$s$$$ to $$$t$$$. If it is not possible to convert $$$s$$$ to $$$t$$$, output $$$-1$$$ instead.", "sample_inputs": ["6\n1\na\na\n2\nab\nba\n3\nabc\ncab\n3\nabc\ncba\n4\nabab\nbaba\n4\nabcc\naabc"], "sample_outputs": ["0\n1\n1\n2\n1\n-1"], "notes": "NoteFor the $$$1$$$-st test case, since $$$s$$$ and $$$t$$$ are equal, you don't need to apply any operation.For the $$$2$$$-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.For the $$$3$$$-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.For the $$$4$$$-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length $$$2$$$ beginning at the second character to convert it to cba.For the $$$5$$$-th test case, you only need to apply one operation on the entire string abab to convert it to baba.For the $$$6$$$-th test case, it is not possible to convert string $$$s$$$ to $$$t$$$."}, "positive_code": [{"source_code": "//package codeforces.contests._1363\n\n/*\nhttps://codeforces.com/contest/1363/problem/F\n */\nobject RotatingSubstring {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n val s, t = '0' + io.StdIn.readLine()\n\n val (freqS, freqT) = {\n val fS, fT = new Array[Int](26)\n (1 to n).foreach { k =>\n fS(s(k) - 'a') += 1\n fT(t(k) - 'a') += 1\n }\n (fS, fT)\n }\n\n val frequenciesMatch = (0 until 26).forall(i => freqS(i) == freqT(i))\n\n println {\n if (frequenciesMatch) {\n val dp = Array.ofDim[Int](n + 1, n + 1)\n val fS = freqS.clone()\n (1 to n).foreach { i =>\n val fT = freqT.clone()\n fS(s(i) - 'a') -= 1\n\n (1 to n).foreach { j =>\n fT(t(j) - 'a') -= 1\n\n dp(i)(j) = if (s(i) == t(j)) dp(i - 1)(j - 1) else {\n (dp(i - 1)(j) + 1) min {\n val x = t(j) - 'a'\n if (fS(x) > fT(x)) dp(i)(j - 1) else Int.MaxValue\n }\n }\n }\n }\n\n dp(n)(n)\n } else -1\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "7ad14848b3b9f075477fbf0c5f648c77"} {"nl": {"description": "Sasha and Dima want to buy two $$$n$$$-tier cakes. Each cake should consist of $$$n$$$ different tiers: from the size of $$$1$$$ to the size of $$$n$$$. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are $$$2 \\cdot n$$$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $$$i$$$-th house you can buy a tier of the size $$$a_i$$$ ($$$1 \\le a_i \\le n$$$).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $$$1$$$, then $$$2$$$, then $$$3$$$ and so on up to $$$n$$$.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $$$1$$$.", "input_spec": "The first line of the input contains an integer number $$$n$$$ \u2014 the number of tiers in each cake ($$$1 \\le n \\le 10^5$$$). The second line contains $$$2 \\cdot n$$$ integers $$$a_1, a_2, \\dots, a_{2n}$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is equal to the size of the tier, which can be bought in the $$$i$$$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $$$1$$$ to $$$n$$$ occurs in $$$a$$$ exactly two times.", "output_spec": "Print one number \u00a0\u2014 the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $$$n$$$ tiers in ascending order of their sizes.", "sample_inputs": ["3\n1 1 2 2 3 3", "2\n2 1 1 2", "4\n4 1 3 2 2 3 1 4"], "sample_outputs": ["9", "5", "17"], "notes": "NoteIn the first example, the possible optimal sequence of actions is: Sasha buys a tier of size $$$1$$$ near the $$$1$$$-st house ($$$a_1=1$$$); Dima goes to the house $$$2$$$; Dima buys a tier of size $$$1$$$ near the $$$2$$$-nd house ($$$a_2=1$$$); Sasha goes to the house $$$4$$$; Sasha buys a tier of size $$$2$$$ near the $$$4$$$-th house ($$$a_4=2$$$); Sasha goes to the house $$$5$$$; Sasha buys a tier of size $$$3$$$ near the $$$5$$$-th house ($$$a_5=3$$$); Dima goes to the house $$$3$$$; Dima buys a tier of size $$$2$$$ near the $$$3$$$-rd house ($$$a_3=2$$$); Dima goes to the house $$$6$$$; Dima buys a tier of size $$$3$$$ near the $$$6$$$-th house ($$$a_6=3$$$). So, Sasha goes the distance $$$3+1=4$$$, and Dima goes the distance $$$1+1+3=5$$$. In total, they cover a distance of $$$4+5=9$$$. You can make sure that with any other sequence of actions they will walk no less distance."}, "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 // \u8caa\u6b32\u306b\u5de6\u53f3\u306b\u5206\u5272\u3059\u308b\u306e\u304c\u6700\u9069\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\u3092\u9806\u756a\u306b\u8fbf\u3063\u305f\u3068\u304d\u306e\u8ddd\u96e2\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"}, {"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"}], "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"} {"nl": {"description": "Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 1000$$$) \u2014 the number of queries. The following $$$q$$$ lines contain queries, one per line. Each query is given as two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^{16}$$$) \u2014 the number of pages in the book and required divisor, respectively.", "output_spec": "For each query print the answer for it \u2014 the sum of digits written down by Polycarp.", "sample_inputs": ["7\n1 1\n10 1\n100 3\n1024 14\n998244353 1337\n123 144\n1234312817382646 13"], "sample_outputs": ["1\n45\n153\n294\n3359835\n0\n427262129093995"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contest1213\n\nobject BookReading {\n\n val lastDigitToSeq: Map[Int, Seq[Int]] = Map(\n 0 -> Seq(0),\n 1 -> Seq(1, 2, 3, 4, 5, 6, 7, 8, 9, 0),\n 2 -> Seq(2, 4, 6, 8, 0),\n 3 -> Seq(3, 6, 9, 2, 5, 8, 1, 4, 7, 0),\n 4 -> Seq(4, 8, 2, 6, 0),\n 5 -> Seq(5, 0),\n 6 -> Seq(6, 2, 8, 4, 0),\n 7 -> Seq(7, 4, 1, 8, 5, 2, 9, 6, 3, 0),\n 8 -> Seq(8, 6, 4, 2, 0),\n 9 -> Seq(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)\n )\n\n def main(args: Array[String]): Unit = {\n println {\n (1 to io.StdIn.readInt())\n .foldLeft(List.empty[Long]) {\n case (ls, _) =>\n val Array(n, m) = io.StdIn.readLine.split(\" \").map(_.toLong)\n\n val lastDigit = (m % 10).toInt\n val seq = lastDigitToSeq(lastDigit)\n val (freq: Int, sum: Int) = (seq.length, seq.sum)\n\n val count: Long = n / m\n\n ( + sum * (count / freq) + seq.take((count % freq).toInt).sum) :: ls\n }\n .reverse\n .mkString(\"\\n\")\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "9964bfdcfdd041b839ce120019e8220f"} {"nl": {"description": "Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring \"..\" (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string \".\". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009300\u2009000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1\u2009\u2264\u2009xi\u2009\u2264\u2009n, ci \u2014 a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.", "output_spec": "Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.", "sample_inputs": ["10 3\n.b..bz....\n1 h\n3 c\n9 f", "4 4\n.cc.\n2 .\n3 .\n2 a\n1 a"], "sample_outputs": ["4\n3\n1", "1\n3\n1\n1"], "notes": "NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is \".b..bz....\". after the first query f(hb..bz....) = 4\u00a0\u00a0\u00a0\u00a0(\"hb[..]bz....\" \u2009\u2192\u2009 \"hb.bz[..]..\" \u2009\u2192\u2009 \"hb.bz[..].\" \u2009\u2192\u2009 \"hb.bz[..]\" \u2009\u2192\u2009 \"hb.bz.\") after the second query f(hb\u0441.bz....) = 3\u00a0\u00a0\u00a0\u00a0(\"hb\u0441.bz[..]..\" \u2009\u2192\u2009 \"hb\u0441.bz[..].\" \u2009\u2192\u2009 \"hb\u0441.bz[..]\" \u2009\u2192\u2009 \"hb\u0441.bz.\") after the third query f(hb\u0441.bz..f.) = 1\u00a0\u00a0\u00a0\u00a0(\"hb\u0441.bz[..]f.\" \u2009\u2192\u2009 \"hb\u0441.bz.f.\")Note to the second sample test.The original string is \".cc.\". after the first query: f(..c.) = 1\u00a0\u00a0\u00a0\u00a0(\"[..]c.\" \u2009\u2192\u2009 \".c.\") after the second query: f(....) = 3\u00a0\u00a0\u00a0\u00a0(\"[..]..\" \u2009\u2192\u2009 \"[..].\" \u2009\u2192\u2009 \"[..]\" \u2009\u2192\u2009 \".\") after the third query: f(.a..) = 1\u00a0\u00a0\u00a0\u00a0(\".a[..]\" \u2009\u2192\u2009 \".a.\") after the fourth query: f(aa..) = 1\u00a0\u00a0\u00a0\u00a0(\"aa[..]\" \u2009\u2192\u2009 \"aa.\")"}, "positive_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 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 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"}, {"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": "\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}"}], "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"} {"nl": {"description": "Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.", "input_spec": "The single line contains four integers x,\u2009y,\u2009a,\u2009b (1\u2009\u2264\u2009a\u2009\u2264\u2009x\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009b\u2009\u2264\u2009y\u2009\u2264\u2009100). The numbers on the line are separated by a space.", "output_spec": "In the first line print integer n \u2014 the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di \u2014 the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci,\u2009di) in the strictly increasing order. Let us remind you that the pair of numbers (p1,\u2009q1) is less than the pair of numbers (p2,\u2009q2), if p1\u2009<\u2009p2, or p1\u2009=\u2009p2 and also q1\u2009<\u2009q2.", "sample_inputs": ["3 2 1 1", "2 4 2 2"], "sample_outputs": ["3\n2 1\n3 1\n3 2", "0"], "notes": null}, "positive_code": [{"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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Janusz is a businessman. He owns a company \"Januszex\", which produces games for teenagers. Last hit of Januszex was a cool one-person game \"Make it one\". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?", "input_spec": "The first line contains an only integer $$$n$$$ ($$$1 \\le n \\le 300\\,000$$$)\u00a0\u2014 the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 300\\,000$$$).", "output_spec": "If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer\u00a0\u2014 the size of the smallest subset with gcd equal to $$$1$$$.", "sample_inputs": ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"], "sample_outputs": ["3", "-1", "3"], "notes": "NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. "}, "positive_code": [{"source_code": "//package codeforces\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util.StringTokenizer\n\n/*\n\nhttps://codeforces.com/contest/1043/problem/F\n\n */\nobject MakeItOne {\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 val st = new StringTokenizer(br.readLine())\n st.nextToken.toInt\n }\n\n def power(x: Long, y: Long): Long = {\n if (x == 0) 0\n else {\n var ans: Long = 1\n var temp: Long = x\n\n var i = y\n while (i > 0) {\n if ((i & 1) == 1) {\n ans = (ans * temp) % MOD\n }\n temp = (temp * temp) % MOD\n i = i / 2\n }\n\n ans\n }\n }\n\n val maxCount = 300001\n val MOD = 1000000009\n\n val factorialOf: Array[Long] = new Array[Long](maxCount)\n factorialOf(0) = 1\n for (i <- 1 until maxCount) factorialOf(i) = (i * factorialOf(i - 1)) % MOD\n\n val inverseModFactorialOf: Array[Long] = new Array[Long](maxCount)\n inverseModFactorialOf(maxCount - 1) = power(factorialOf(maxCount - 1), MOD - 2)\n\n for (i <- maxCount - 1 to 1 by -1) inverseModFactorialOf(i - 1) = (i * inverseModFactorialOf(i)) % MOD\n\n def nCr(n: Int, r: Int): Long = {\n if (r < 0 || n < r) 0\n else ((factorialOf(n) * inverseModFactorialOf(r) % MOD) * inverseModFactorialOf(n - r)) % MOD\n }\n\n def sub(x: Long, y: Long): Long = {\n x - y + (if (x >= y) 0 else MOD)\n }\n\n def main(args: Array[String]): Unit = {\n val n = readInt()\n val arr = readIntArray(n)\n\n val isPresent = new Array[Boolean](maxCount)\n arr.foreach(i => isPresent(i) = true)\n\n val countOfElementsThatDivide = new Array[Int](maxCount)\n for {\n i <- 1 until maxCount\n j <- i until maxCount by i if isPresent(j)\n } countOfElementsThatDivide(i) += 1\n\n val dp = Array.ofDim[Long](8, maxCount)\n\n\n for {\n i <- 1 to 7\n j <- maxCount - 1 to 1 by -1\n } {\n dp(i)(j) = nCr(countOfElementsThatDivide(j), i)\n var k = 2\n while (k * j < maxCount) {\n dp(i)(j) = sub(dp(i)(j), dp(i)(k * j))\n k += 1\n }\n\n if (dp(i)(1) > 0) {\n println(i)\n System.exit(0)\n }\n }\n\n println(-1)\n }\n}\n"}], "negative_code": [], "src_uid": "3baa00206d3bf03ce02a414747e2a633"} {"nl": {"description": "Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are $$$n_1$$$ different types of first courses Ivan can buy (the $$$i$$$-th of them costs $$$a_i$$$ coins), $$$n_2$$$ different types of second courses (the $$$i$$$-th of them costs $$$b_i$$$ coins), $$$n_3$$$ different types of drinks (the $$$i$$$-th of them costs $$$c_i$$$ coins) and $$$n_4$$$ different types of desserts (the $$$i$$$-th of them costs $$$d_i$$$ coins).Some dishes don't go well with each other. There are $$$m_1$$$ pairs of first courses and second courses that don't go well with each other, $$$m_2$$$ pairs of second courses and drinks, and $$$m_3$$$ pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!", "input_spec": "The first line contains four integers $$$n_1$$$, $$$n_2$$$, $$$n_3$$$ and $$$n_4$$$ ($$$1 \\le n_i \\le 150000$$$) \u2014 the number of types of first courses, second courses, drinks and desserts, respectively. Then four lines follow. The first line contains $$$n_1$$$ integers $$$a_1, a_2, \\dots, a_{n_1}$$$ ($$$1 \\le a_i \\le 10^8$$$), where $$$a_i$$$ is the cost of the $$$i$$$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($$$1 \\le b_i, c_i, d_i \\le 10^8$$$). The next line contains one integer $$$m_1$$$ ($$$0 \\le m_1 \\le 200000$$$)\u00a0\u2014 the number of pairs of first and second courses that don't go well with each other. Each of the next $$$m_1$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i \\le n_1$$$; $$$1 \\le y_i \\le n_2$$$) denoting that the first course number $$$x_i$$$ doesn't go well with the second course number $$$y_i$$$. All these pairs are different. The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($$$0 \\le m_2, m_3 \\le 200000$$$).", "output_spec": "If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $$$-1$$$. Otherwise, print one integer\u00a0\u2014 the minimum total cost of the dinner.", "sample_inputs": ["4 3 2 1\n1 2 3 4\n5 6 7\n8 9\n10\n2\n1 2\n1 1\n2\n3 1\n3 2\n1\n1 1", "1 1 1 1\n1\n1\n1\n1\n1\n1 1\n0\n0"], "sample_outputs": ["26", "-1"], "notes": "NoteThe best option in the first example is to take the first course $$$2$$$, the second course $$$1$$$, the drink $$$2$$$ and the dessert $$$1$$$.In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner."}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n case class Course(id: Int, cost: Int)\n\n val nA, nB, nC, nD = nextInt\n val as0 = nextInts(nA)\n val bs0 = nextInts(nB)\n val cs0 = nextInts(nC)\n val ds0 = nextInts(nD)\n\n val m1 = nextInt\n val badAB = Array.fill(nA)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 0 until m1) {\n val x, y = nextInt\n badAB(x - 1) += y - 1\n }\n val badABs = badAB.map(_.result().toSet)\n\n val m2 = nextInt\n val badBC = Array.fill(nB)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 0 until m2) {\n val x, y = nextInt\n badBC(x - 1) += y - 1\n }\n val badBCs = badBC.map(_.result().toSet)\n\n val m3 = nextInt\n val badCD = Array.fill(nC)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 0 until m3) {\n val x, y = nextInt\n badCD(x - 1) += y - 1\n }\n val badCDs = badCD.map(_.result().toSet)\n\n val as = (0 until nA).iterator.map(i => Course(i, as0(i))).toArray.sortBy(_.cost)\n\n for (i <- bs0.indices) {\n var j = 0\n while (j < as.length && badABs(as(j).id)(i)) {\n j += 1\n }\n if (j < as.length) {\n bs0(i) += as(j).cost\n } else {\n bs0(i) = -1\n }\n }\n\n val bs = (0 until nB).iterator.filter(i => bs0(i) > 0).map(i => Course(i, bs0(i))).toArray.sortBy(_.cost)\n\n for (i <- cs0.indices) {\n var j = 0\n while (j < bs.length && badBCs(bs(j).id)(i)) {\n j += 1\n }\n if (j < bs.length) {\n cs0(i) += bs(j).cost\n } else {\n cs0(i) = -1\n }\n }\n\n val cs = (0 until nC).iterator.filter(i => cs0(i) > 0).map(i => Course(i, cs0(i))).toArray.sortBy(_.cost)\n\n for (i <- ds0.indices) {\n var j = 0\n while (j < cs.length && badCDs(cs(j).id)(i)) {\n j += 1\n }\n if (j < cs.length) {\n ds0(i) += cs(j).cost\n } else {\n ds0(i) = -1\n }\n }\n\n val goodD = ds0.filterNot(_ == -1)\n val res = if (goodD.isEmpty) -1 else goodD.min\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": [], "src_uid": "ed0765719bfc3903701c0c14b7ad15c7"} {"nl": {"description": "An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of cars in the train. The second line contains n integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n, pi\u2009\u2260\u2009pj if i\u2009\u2260\u2009j)\u00a0\u2014 the sequence of the numbers of the cars in the train.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of actions needed to sort the railway cars.", "sample_inputs": ["5\n4 1 2 5 3", "4\n4 1 3 2"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train."}, "positive_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 = 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}"}, {"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": "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}"}], "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"} {"nl": {"description": "Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows. The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \\le k \\le 10^9$$$) which location must be found.", "output_spec": "For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \\ge 1$$$) separated by spaces \u2014 the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.", "sample_inputs": ["7\n11\n14\n5\n4\n1\n2\n1000000000"], "sample_outputs": ["2 4\n4 3\n1 3\n2 1\n1 1\n1 2\n31623 14130"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "f8335c59cd05988c8053f138c4df06aa"} {"nl": {"description": "AquaMoon has two binary sequences $$$a$$$ and $$$b$$$, which contain only $$$0$$$ and $$$1$$$. AquaMoon can perform the following two operations any number of times ($$$a_1$$$ is the first element of $$$a$$$, $$$a_2$$$ is the second element of $$$a$$$, and so on): Operation 1: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\\operatorname{min}(a_1,a_2)$$$, and remove the first element of $$$a$$$. Operation 2: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\\operatorname{max}(a_1,a_2)$$$, and remove the first element of $$$a$$$.Note that after a removal of the first element of $$$a$$$, the former $$$a_2$$$ becomes the first element of $$$a$$$, the former $$$a_3$$$ becomes the second element of $$$a$$$ and so on, and the length of $$$a$$$ reduces by one.Determine if AquaMoon can make $$$a$$$ equal to $$$b$$$ by using these operations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 2\\,000$$$) \u2014 the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \\leq n,m \\leq 50$$$, $$$m \\leq n$$$) \u2014 the lengths of $$$a$$$ and $$$b$$$ respectively. The second line of each test case contains a string $$$a$$$ of length $$$n$$$, consisting only $$$0$$$ and $$$1$$$. The third line of each test case contains a string $$$b$$$ of length $$$m$$$, consisting only $$$0$$$ and $$$1$$$.", "output_spec": "For each test case, output \"YES\" if AquaMoon can change $$$a$$$ to $$$b$$$ by using these options; otherwise, output \"NO\". You may print each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\" will all be recognized as a positive answer).", "sample_inputs": ["10\n\n6 2\n\n001001\n\n11\n\n6 2\n\n110111\n\n01\n\n6 2\n\n000001\n\n11\n\n6 2\n\n111111\n\n01\n\n8 5\n\n10000101\n\n11010\n\n7 4\n\n1010001\n\n1001\n\n8 6\n\n01010010\n\n010010\n\n8 4\n\n01010101\n\n1001\n\n8 4\n\n10101010\n\n0110\n\n7 5\n\n1011100\n\n11100"], "sample_outputs": ["YES\nYES\nNO\nNO\nNO\nYES\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case, you can use Operation 2 four times to make $$$a$$$ equals to $$$b$$$.In the second test case, you can use Operation 1 four times to make $$$a$$$ equals to $$$b$$$.In the third test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fourth test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fifth test case, you can use Operation 2 three times to make $$$a$$$ become $$$10101$$$, so the first element of $$$a$$$ equals to the first element of $$$b$$$, but it can be proved that no matter how to operate, the second to the fifth elements of $$$a$$$ can't be the same as $$$b$$$."}, "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 var c = true\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l1 = tokenizer.nextToken().toInt\r\n val l2 = tokenizer.nextToken().toInt\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val a = tokenizer.nextToken()\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val b = tokenizer.nextToken()\r\n for (i <- 1 until b.length()) {\r\n if (a(l1-l2 + i) != b(i)) {\r\n c = false\r\n }\r\n }\r\n var bb = false\r\n for (i <- 0 to l1-l2) {\r\n if (b.head == a(i)) {\r\n bb = true\r\n }\r\n }\r\n if (!bb) {\r\n c = false\r\n }\r\n if (c){\r\n println(\"YES\")\r\n }\r\n else {\r\n println(\"NO\")\r\n }\r\n }\r\n }\r\n}"}], "negative_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 var c = true\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l1 = tokenizer.nextToken().toInt\r\n val l2 = tokenizer.nextToken().toInt\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val a = tokenizer.nextToken()\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val b = tokenizer.nextToken()\r\n for (i <- 1 until b.length()) {\r\n if (a(l1-l2 + i) != b(i)) {\r\n c = false\r\n }\r\n }\r\n var bb = false\r\n if (l1==l2){\r\n bb=true\r\n }\r\n for (i <- 0 until l1-l2) {\r\n if (b.head == a(i)) {\r\n bb = true\r\n }\r\n }\r\n if (!bb) {\r\n c = false\r\n }\r\n if (c){\r\n println(\"YES\")\r\n }\r\n else {\r\n println(\"NO\")\r\n }\r\n }\r\n }\r\n}"}, {"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 var c = true\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l1 = tokenizer.nextToken().toInt\r\n val l2 = tokenizer.nextToken().toInt\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val a = tokenizer.nextToken()\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val b = tokenizer.nextToken()\r\n for (i <- 1 until b.length()) {\r\n if (a(l1-l2 + i) != b(i)) {\r\n c = false\r\n }\r\n }\r\n var bb = false\r\n for (i <- 0 until l1-l2) {\r\n if (b.head == a(i)) {\r\n bb = true\r\n }\r\n }\r\n if (!bb) {\r\n c = false\r\n }\r\n if (c){\r\n println(\"YES\")\r\n }\r\n else {\r\n println(\"NO\")\r\n }\r\n }\r\n }\r\n}"}], "src_uid": "83050a8a4c7b64004681bdadb630292e"} {"nl": {"description": "You are given a picture consisting of $$$n$$$ rows and $$$m$$$ columns. Rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom, columns are numbered from $$$1$$$ to $$$m$$$ from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $$$x$$$ and $$$y$$$, where $$$1 \\le x \\le n$$$ and $$$1 \\le y \\le m$$$, such that all cells in row $$$x$$$ and all cells in column $$$y$$$ are painted black.For examples, each of these pictures contain crosses: The fourth picture contains 4 crosses: at $$$(1, 3)$$$, $$$(1, 5)$$$, $$$(3, 3)$$$ and $$$(3, 5)$$$.Following images don't contain crosses: You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?You are also asked to answer multiple independent queries.", "input_spec": "The first line contains an integer $$$q$$$ ($$$1 \\le q \\le 5 \\cdot 10^4$$$) \u2014 the number of queries. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 5 \\cdot 10^4$$$, $$$n \\cdot m \\le 4 \\cdot 10^5$$$) \u2014 the number of rows and the number of columns in the picture. Each of the next $$$n$$$ lines contains $$$m$$$ characters \u2014 '.' if the cell is painted white and '*' if the cell is painted black. It is guaranteed that $$$\\sum n \\le 5 \\cdot 10^4$$$ and $$$\\sum n \\cdot m \\le 4 \\cdot 10^5$$$.", "output_spec": "Print $$$q$$$ lines, the $$$i$$$-th line should contain a single integer \u2014 the answer to the $$$i$$$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.", "sample_inputs": ["9\n5 5\n..*..\n..*..\n*****\n..*..\n..*..\n3 4\n****\n.*..\n.*..\n4 3\n***\n*..\n*..\n*..\n5 5\n*****\n*.*.*\n*****\n..*.*\n..***\n1 4\n****\n5 5\n.....\n..*..\n.***.\n..*..\n.....\n5 3\n...\n.*.\n.*.\n***\n.*.\n3 3\n.*.\n*.*\n.*.\n4 4\n*.**\n....\n*.**\n*.**"], "sample_outputs": ["0\n0\n0\n0\n0\n4\n1\n1\n2"], "notes": "NoteThe example contains all the pictures from above in the same order.The first 5 pictures already contain a cross, thus you don't have to paint anything.You can paint $$$(1, 3)$$$, $$$(3, 1)$$$, $$$(5, 3)$$$ and $$$(3, 5)$$$ on the $$$6$$$-th picture to get a cross in $$$(3, 3)$$$. That'll take you $$$4$$$ minutes.You can paint $$$(1, 2)$$$ on the $$$7$$$-th picture to get a cross in $$$(4, 2)$$$.You can paint $$$(2, 2)$$$ on the $$$8$$$-th picture to get a cross in $$$(2, 2)$$$. You can, for example, paint $$$(1, 3)$$$, $$$(3, 1)$$$ and $$$(3, 3)$$$ to get a cross in $$$(3, 3)$$$ but that will take you $$$3$$$ minutes instead of $$$1$$$.There are 9 possible crosses you can get in minimum time on the $$$9$$$-th picture. One of them is in $$$(1, 1)$$$: paint $$$(1, 2)$$$ and $$$(2, 1)$$$."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val g = nm_c(n, m)\n val rowCnt = Array.ofDim[Int](n)\n val colCnt = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n if (g(i)(j) == '.') {\n rowCnt(i) += 1\n colCnt(j) += 1\n }\n }\n }\n var ans = n + m\n REP(n) { i =>\n REP(m) { j =>\n val v = rowCnt(i) + colCnt(j) - (if (g(i)(j) == '.') 1 else 0)\n ans = min(ans, v)\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(\"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val n, m = ni()\n val g = nm_c(n, m)\n val rowCnt = Array.ofDim[Int](n)\n val colCnt = Array.ofDim[Int](m)\n REP(n) { i =>\n REP(m) { j =>\n if (g(i)(j) == '.') {\n rowCnt(i) += 1\n colCnt(j) += 1\n }\n }\n }\n var ans = max(n, m)\n REP(n) { i =>\n REP(m) { j =>\n val v = rowCnt(i) + colCnt(j) - (if (g(i)(j) == '.') 1 else 0)\n ans = min(ans, v)\n }\n }\n out.println(ans)\n }\n }\n}"}], "src_uid": "a1b6a2f4659169e0e818bbdee6d36e76"} {"nl": {"description": "You are a programmer and you have a New Year Tree (not the traditional fur tree, though) \u2014 a tree of four vertices: one vertex of degree three (has number 1), connected with three leaves (their numbers are from 2 to 4).On the New Year, programmers usually have fun. You decided to have fun as well by adding vertices to the tree. One adding operation looks as follows: First we choose some leaf of the tree with number v. Let's mark the number of vertices on the tree at this moment by variable n, then two vertexes are added to the tree, their numbers are n\u2009+\u20091 and n\u2009+\u20092, also you get new edges, one between vertices v and n\u2009+\u20091 and one between vertices v and n\u2009+\u20092. Your task is not just to model the process of adding vertices to the tree, but after each adding operation print the diameter of the current tree. Come on, let's solve the New Year problem!", "input_spec": "The first line contains integer q (1\u2009\u2264\u2009q\u2009\u2264\u20095\u00b7105) \u2014 the number of operations. Each of the next q lines contains integer vi (1\u2009\u2264\u2009vi\u2009\u2264\u2009n) \u2014 the operation of adding leaves to vertex vi. Variable n represents the number of vertices in the current tree. It is guaranteed that all given operations are correct.", "output_spec": "Print q integers \u2014 the diameter of the current tree after each operation.", "sample_inputs": ["5\n2\n3\n4\n8\n5"], "sample_outputs": ["3\n4\n4\n5\n6"], "notes": null}, "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) 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\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}"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "2cbaa9bb315d1791b54f3e0fbd1cf140"} {"nl": {"description": "The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point \u2014 the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi\u2009=\u2009sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters\u00a0\u2014 power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of computers and the number of sockets. The second line contains n integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009109)\u00a0\u2014 the powers of the computers. The third line contains m integers s1,\u2009s2,\u2009...,\u2009sm (1\u2009\u2264\u2009si\u2009\u2264\u2009109)\u00a0\u2014 the power of the sockets. ", "output_spec": "In the first line print two numbers c and u\u00a0\u2014 the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1,\u2009a2,\u2009...,\u2009am (0\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1,\u2009b2,\u2009...,\u2009bn (0\u2009\u2264\u2009bi\u2009\u2264\u2009m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj\u2009=\u20090 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.", "sample_inputs": ["2 2\n1 1\n2 2", "2 1\n2 100\n99"], "sample_outputs": ["2 2\n1 1\n1 2", "1 6\n6\n1 0"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject Solution extends App {\n val in = io.Source.stdin.getLines()\n val Array(n, m) = in.next().split(' ').map(_.toInt)\n val p = in.next().split(' ').map(_.toInt)\n\n var pMap = mutable.Map.empty[Int, List[Int]]\n\n val s = in.next().split(' ').map(_.toInt)\n val sIndex = Array.ofDim[Int](m)\n (0 until m).foreach {i => sIndex(i) = i}\n \n (0 until n).foreach { i =>\n if (pMap.contains(p(i)))\n pMap(p(i)) ::= i\n else\n pMap(p(i)) = List(i)\n }\n\n val pUsed = Array.ofDim[Int](n)\n val sCount = Array.ofDim[Int](m)\n var step = 0\n var length = m\n\n while(length != 0) {\n var nLength = 0\n var i = 0\n while (i < length) {\n val power = s(i)\n val index = sIndex(i)\n if (pMap.contains(power)) {\n val (x :: xs) = pMap(power)\n sCount(index) = step\n pUsed(x) = index + 1\n if (xs.isEmpty)\n pMap -= power\n else\n pMap += power -> xs\n } else if (power != 1) {\n s(nLength) = (power + 1) / 2\n sIndex(nLength) = index\n nLength += 1\n }\n i += 1\n }\n length = nLength\n step += 1\n }\n\n val c = pUsed.count(_ != 0)\n val u = sCount.sum\n println(s\"$c $u\")\n println(sCount.mkString(\" \"))\n println(pUsed.mkString(\" \"))\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 p = in.next().split(' ').map(_.toInt)\n val s = in.next().split(' ').map(_.toInt)\n var sorted = s.zipWithIndex.sorted\n var pMap = p.zipWithIndex.groupBy(_._1).map(i => i._1 -> i._2.map(_._2))\n var pIndexMap = pMap.map(i => i._1 -> (i._2.length - 1))\n val pUsed = Array.ofDim[Int](n)\n val sCount = Array.ofDim[Int](m)\n var c = 0\n var u = 0\n\n sorted.foreach {\n case (power, index) =>\n var nPower = power\n var i = 0\n while(pIndexMap.getOrElse(nPower, -1) == -1 && nPower != 1) {\n nPower = (nPower + 1) / 2\n i += 1\n }\n val offset = pIndexMap.getOrElse(nPower, -1)\n if (offset != -1) {\n val list = pMap(nPower)\n val plug = list(offset)\n pUsed(plug) = index + 1\n u += 1\n c += index + 1\n sCount(index) = i\n pIndexMap += nPower -> (offset - 1)\n }\n }\n\n// val c = pUsed.count(_ != 0)\n// val u = sCount.sum\n println(s\"$c $u\")\n println(sCount.mkString(\" \"))\n println(pUsed.mkString(\" \"))\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 p = in.next().split(' ').map(_.toInt)\n val s = in.next().split(' ').map(_.toInt)\n var sorted = s.zipWithIndex.sorted\n var pMap = p.zipWithIndex.groupBy(_._1).map(i => i._1 -> i._2.map(_._2))\n var pIndexMap = pMap.map(i => i._1 -> (i._2.length - 1))\n val pUsed = Array.ofDim[Int](n)\n val sCount = Array.ofDim[Int](m)\n var c = 0\n var u = 0\n\n sorted.foreach {\n case (power, index) =>\n var nPower = power\n var i = 0\n while(pIndexMap.getOrElse(nPower, -1) == -1 && nPower != 1) {\n nPower = (nPower + 1) / 2\n i += 1\n }\n val offset = pIndexMap.getOrElse(nPower, -1)\n if (offset != -1) {\n val list = pMap(nPower)\n val plug = list(offset)\n pUsed(plug) = index + 1\n u += index + 1\n c += 1\n sCount(index) = i\n pIndexMap += nPower -> (offset - 1)\n }\n }\n\n println(s\"$c $u\")\n println(sCount.mkString(\" \"))\n println(pUsed.mkString(\" \"))\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 p = in.next().split(' ').map(_.toInt)\n val s = in.next().split(' ').map(_.toInt)\n var sorted = s.zipWithIndex.sorted\n var pMap = p.zipWithIndex.groupBy(_._1).map(i => i._1 -> i._2.map(_._2))\n var pIndexMap = pMap.map(i => i._1 -> 0)\n val pUsed = Array.ofDim[Int](n)\n val sCount = Array.ofDim[Int](m)\n var step = 0\n\n sorted.foreach {\n case (power, index) =>\n var nPower = power\n var i = 0\n while(!pMap.contains(nPower) && nPower != 1) {\n nPower = (nPower + 1) / 2\n i += 1\n }\n if (pMap.contains(nPower)) {\n val list = pMap(nPower)\n val offset = pIndexMap(nPower)\n val plug = list(offset)\n pUsed(plug) = index + 1\n sCount(index) = i\n if (list.length - 1 == offset)\n pMap -= nPower\n else\n pIndexMap += nPower -> (offset + 1)\n }\n }\n\n val c = pUsed.count(_ != -1)\n val u = sCount.sum\n println(s\"$c $u\")\n println(sCount.mkString(\" \"))\n println(pUsed.mkString(\" \"))\n}"}], "src_uid": "0a687ec4e1411750e33cc3670a614574"} {"nl": {"description": "Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1,\u2009...,\u2009ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.", "input_spec": "The first line contains 5 space-separated integers: n, k, p, x and y (1\u2009\u2264\u2009n\u2009\u2264\u2009999, n is odd, 0\u2009\u2264\u2009k\u2009<\u2009n, 1\u2009\u2264\u2009p\u2009\u2264\u20091000, n\u2009\u2264\u2009x\u2009\u2264\u2009n\u00b7p, 1\u2009\u2264\u2009y\u2009\u2264\u2009p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009p)\u00a0\u2014 the marks that Vova got for the tests he has already written.", "output_spec": "If Vova cannot achieve the desired result, print \"-1\". Otherwise, print n\u2009-\u2009k space-separated integers\u00a0\u2014 the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.", "sample_inputs": ["5 3 5 18 4\n3 5 4", "5 3 5 16 4\n5 5 5"], "sample_outputs": ["4 1", "-1"], "notes": "NoteThe median of sequence a1,\u00a0...,\u00a0an where n is odd (in this problem n is always odd) is the element staying on (n\u2009+\u20091)\u2009/\u20092 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: \"4\u00a02\", \"2\u00a04\", \"5\u00a01\", \"1\u00a05\", \"4\u00a01\", \"1\u00a04\" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is \"-1\"."}, "positive_code": [{"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}"}, {"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"}, {"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 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}"}], "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"} {"nl": {"description": "A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b\u2009<\u2009a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c\u2009>\u2009a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.", "input_spec": "The first line of input contains three space-separated integers, a, b and c (1\u2009\u2264\u2009b\u2009<\u2009a\u2009<\u2009c\u2009\u2264\u2009109), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), denoting the number of banknotes. The next line of input contains n space-separated integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.", "output_spec": "Output a single integer: the maximum number of banknotes Oleg can take.", "sample_inputs": ["5 3 7\n8\n4 7 5 5 3 6 2 8", "6 5 7\n5\n1 5 7 92 3"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject B 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 a = int()\n val b = int()\n val c = int()\n\n def filter(x: Int) = (x > b) && (x < c)\n\n read()\n val n = int()\n\n read()\n val ans = (1 to n).map(_ => int()).count(filter)\n println(ans)\n\n}\n"}], "negative_code": [], "src_uid": "aceadc8eadf6d5efd7c5a9fbc0396423"} {"nl": {"description": "Welcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $$$a$$$ dollars and Ronnie has bet $$$b$$$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $$$gcd(a,b)$$$, where $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. To make the race more exciting, you can perform two types of operations: Increase both $$$a$$$ and $$$b$$$ by $$$1$$$. Decrease both $$$a$$$ and $$$b$$$ by $$$1$$$. This operation can only be performed if both $$$a$$$ and $$$b$$$ are greater than $$$0$$$. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that $$$gcd(x,0)=x$$$ for any $$$x \\ge 0$$$.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 5\\cdot 10^3$$$) \u2014 the number of test cases. The first and the only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0\\leq a, b\\leq 10^{18}$$$).", "output_spec": "For each test case, print a single line containing two integers. If the fans can get infinite excitement, print 0 0. Otherwise, the first integer must be the maximum excitement the fans can get, and the second integer must be the minimum number of moves required to achieve that excitement.", "sample_inputs": ["4\n8 5\n1 2\n4 4\n3 9"], "sample_outputs": ["3 1\n1 0\n0 0\n6 3"], "notes": "NoteFor the first test case, you can apply the first operation $$$1$$$ time to get $$$a=9$$$ and $$$b=6$$$. It can be shown that $$$3$$$ is the maximum excitement possible.For the second test case, no matter how many operations you apply, the fans will always have an excitement equal to $$$1$$$. Since the initial excitement is also $$$1$$$, you don't need to apply any operation.For the third case, the fans can get infinite excitement by applying the first operation an infinite amount of times.For the fourth test case, you can apply the second operation $$$3$$$ times to get $$$a=0$$$ and $$$b=6$$$. Since, $$$gcd(0,6)=6$$$, the fans will get an excitement of $$$6$$$."}, "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)\r\n else a\r\n\r\n println(s\"$e $m\")\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(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"} {"nl": {"description": "At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1],\u2009a[2],\u2009...,\u2009a[n]. Then he should perform a sequence of m operations. An operation can be one of the following: Print operation l,\u2009r. Picks should write down the value of . Modulo operation l,\u2009r,\u2009x. Picks should perform assignment a[i]\u2009=\u2009a[i]\u00a0mod\u00a0x for each i (l\u2009\u2264\u2009i\u2009\u2264\u2009r). Set operation k,\u2009x. Picks should set the value of a[k] to x (in other words perform an assignment a[k]\u2009=\u2009x). Can you help Picks to perform the whole sequence of operations?", "input_spec": "The first line of input contains two integer: n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line contains n integers, separated by space: a[1],\u2009a[2],\u2009...,\u2009a[n]\u00a0(1\u2009\u2264\u2009a[i]\u2009\u2264\u2009109) \u2014 initial value of array elements. Each of the next m lines begins with a number type . If type\u2009=\u20091, there will be two integers more in the line: l,\u2009r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), which correspond the operation 1. If type\u2009=\u20092, there will be three integers more in the line: l,\u2009r,\u2009x\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009x\u2009\u2264\u2009109), which correspond the operation 2. If type\u2009=\u20093, there will be two integers more in the line: k,\u2009x\u00a0(1\u2009\u2264\u2009k\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009x\u2009\u2264\u2009109), which correspond the operation 3. ", "output_spec": "For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.", "sample_inputs": ["5 5\n1 2 3 4 5\n2 3 5 4\n3 3 5\n1 2 5\n2 1 3 3\n1 1 3", "10 10\n6 9 6 7 6 1 10 10 9 5\n1 3 9\n2 7 10 9\n2 5 10 8\n1 4 7\n3 3 7\n2 7 9 9\n1 2 4\n1 6 6\n1 5 9\n3 1 10"], "sample_outputs": ["8\n5", "49\n15\n23\n1\n9"], "notes": "NoteConsider the first testcase: At first, a\u2009=\u2009{1,\u20092,\u20093,\u20094,\u20095}. After operation 1, a\u2009=\u2009{1,\u20092,\u20093,\u20090,\u20091}. After operation 2, a\u2009=\u2009{1,\u20092,\u20095,\u20090,\u20091}. At operation 3, 2\u2009+\u20095\u2009+\u20090\u2009+\u20091\u2009=\u20098. After operation 4, a\u2009=\u2009{1,\u20092,\u20092,\u20090,\u20091}. At operation 5, 1\u2009+\u20092\u2009+\u20092\u2009=\u20095. "}, "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 C250D1D(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 C250D1D(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 val a = na(n)\n\n val t = new SegmentTree(n, a)\n t.build(1, 0, n-1)\n REP(m) { _ =>\n ni() match {\n case 1 =>\n out.println(t.get(1, 0, n-1, ni() - 1, ni() - 1))\n case 2 =>\n t.updateRange(1, 0, n-1, ni() - 1, ni() -1, ni())\n// t.print()\n case 3 =>\n t.updatePoint(1, 0, n-1, ni() - 1, ni())\n// t.print()\n }\n }\n }\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val sum = Array.ofDim[Long](4 * n)\n private val max = Array.ofDim[Int](4 * n)\n\n def merge(v: Int): Unit = {\n sum(v) = sum(v << 1) + sum(v << 1 | 1)\n max(v) = Math.max(max(v << 1), max(v << 1 | 1))\n }\n\n def print(): Unit = {\n out.println(a.mkString(\",\"))\n }\n\n def print_1(): Unit = {\n out.println(max.mkString(\",\"))\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n sum(v) = a(tl)\n max(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n build(v << 1, tl, tm)\n build(v << 1 | 1, tm + 1, tr)\n merge(v)\n }\n }\n\n def updateRange(v: Int, tl: Int, tr: Int, l: Int, r: Int, x: Int): Unit = {\n if(l > r) {}\n else if(l == tl && r == tr && max(v) < x) {}\n else if(tl == tr) {\n a(tl) = a(tl) % x\n sum(v) = a(tl)\n max(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n updateRange(v << 1, tl, tm, l, Math.min(r, tm), x)\n updateRange(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, x)\n merge(v)\n }\n }\n\n def updatePoint(v: Int, tl: Int, tr: Int, pos: Int, x: Int): Unit = {\n if(tl == tr) {\n a(tl) = x\n sum(v) = a(tl)\n max(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n if(pos <= tm) {\n updatePoint(v << 1, tl, tm, pos, x)\n } else {\n updatePoint(v << 1 | 1, tm + 1, tr, pos, x)\n }\n merge(v)\n }\n }\n\n def get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Long = {\n if(l > r) 0L\n else if(l == tl && r == tr) sum(v)\n else {\n val tm = tl + (tr - tl) / 2\n get(v << 1, tl, tm, l, Math.min(r, tm)) +\n get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r)\n }\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 C250D1D(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 C250D1D(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 val a = na(n)\n\n val t = new SegmentTree(n, a)\n t.build(1, 0, n-1)\n REP(m) { _ =>\n ni() match {\n case 1 =>\n out.println(t.get(1, 0, n-1, ni() - 1, ni() - 1))\n case 2 =>\n t.updateRange(1, 0, n-1, ni() - 1, ni() -1, ni())\n// t.print()\n case 3 =>\n t.updatePoint(1, 0, n-1, ni() - 1, ni())\n// t.print()\n }\n }\n }\n\n private class SegmentTree(n: Int, a: Array[Int]) {\n private val sum = Array.ofDim[Int](4 * n)\n private val max = Array.ofDim[Int](4 * n)\n\n def merge(v: Int): Unit = {\n sum(v) = sum(v << 1) + sum(v << 1 | 1)\n max(v) = Math.max(max(v << 1), max(v << 1 | 1))\n }\n\n def print(): Unit = {\n out.println(a.mkString(\",\"))\n }\n\n def print_1(): Unit = {\n out.println(max.mkString(\",\"))\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n sum(v) = a(tl)\n max(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n build(v << 1, tl, tm)\n build(v << 1 | 1, tm + 1, tr)\n merge(v)\n }\n }\n\n def updateRange(v: Int, tl: Int, tr: Int, l: Int, r: Int, x: Int): Unit = {\n if(l > r) {}\n else if(l == tl && r == tr && max(v) < x) {}\n else if(tl == tr) {\n a(tl) = a(tl) % x\n sum(v) = a(tl)\n max(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n updateRange(v << 1, tl, tm, l, Math.min(r, tm), x)\n updateRange(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, x)\n merge(v)\n }\n }\n\n def updatePoint(v: Int, tl: Int, tr: Int, pos: Int, x: Int): Unit = {\n if(tl == tr) {\n a(tl) = x\n sum(v) = a(tl)\n max(v) = a(tl)\n } else {\n val tm = tl + (tr - tl) / 2\n if(pos <= tm) {\n updatePoint(v << 1, tl, tm, pos, x)\n } else {\n updatePoint(v << 1 | 1, tm + 1, tr, pos, x)\n }\n merge(v)\n }\n }\n\n def get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Long = {\n if(l > r) 0L\n else if(l == tl && r == tr) sum(v).toLong\n else {\n val tm = tl + (tr - tl) / 2\n get(v << 1, tl, tm, l, Math.min(r, tm)) +\n get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r)\n }\n }\n }\n}\n"}], "src_uid": "69bfbd43579d74b921c08214cd5c9484"} {"nl": {"description": "One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$, where $$$a_{i} \\neq 0$$$, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order. select two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i,j \\le n$$$) such that $$$a_i$$$ and $$$a_j$$$ have different signs. In other words, one must be positive and one must be negative. swap the signs of $$$a_{i}$$$ and $$$a_{j}$$$. For example if you select $$$a_i=3$$$ and $$$a_j=-2$$$, then they will change to $$$a_i=-3$$$ and $$$a_j=2$$$. Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^{5}$$$) \u2014 the length of the array $$$a$$$. The next line contain $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_{i} \\le 10^9$$$, $$$a_{i} \\neq 0$$$) separated by spaces describing elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print \"YES\" if the array can be sorted in the non-decreasing order, otherwise print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n\n7\n\n7 3 2 -11 -13 -17 -23\n\n6\n\n4 10 25 47 71 96\n\n6\n\n71 -35 7 -4 -11 -25\n\n6\n\n-45 9 -48 -67 -55 7"], "sample_outputs": ["NO\nYES\nYES\nNO"], "notes": "NoteIn the first test case, there is no way to make the array sorted using the operation any number of times.In the second test case, the array is already sorted.In the third test case, we can swap the sign of the $$$1$$$-st element with the sign of the $$$5$$$-th element, and the sign of the $$$3$$$-rd element with the sign of the $$$6$$$-th element, this way the array will be sorted.In the fourth test case, there is no way to make the array sorted using the operation any number of times."}, "positive_code": [{"source_code": "object Task1 extends App {\r\n\r\n import scala.io.StdIn\r\n\r\n def readLine: String = StdIn.readLine()\r\n\r\n def readNum: Int = StdIn.readLine().toInt\r\n\r\n def isSorted(array: Array[Int]): Boolean = {\r\n var sorted = true\r\n var pos = 0\r\n\r\n while (sorted && pos < array.length - 1) {\r\n if (array(pos) > array(pos + 1)) {\r\n sorted = false\r\n }\r\n pos += 1\r\n }\r\n\r\n sorted\r\n }\r\n\r\n val testCases = readNum\r\n\r\n for (_ <- 0 until testCases) {\r\n readLine\r\n val inputNumbers = readLine.split(\" \").map(_.toInt)\r\n\r\n var leftPos = 0\r\n var rightPos = inputNumbers.length - 1\r\n\r\n\r\n while (leftPos != rightPos) {\r\n while (leftPos != rightPos && inputNumbers(leftPos) < 0) {\r\n leftPos += 1\r\n }\r\n\r\n while (leftPos != rightPos && inputNumbers(rightPos) > 0) {\r\n rightPos -= 1\r\n }\r\n\r\n inputNumbers(leftPos) = -inputNumbers(leftPos)\r\n inputNumbers(rightPos) = -inputNumbers(rightPos)\r\n }\r\n\r\n if (isSorted(inputNumbers)) {\r\n println(\"YES\")\r\n } else {\r\n println(\"NO\")\r\n }\r\n\r\n }\r\n\r\n}"}], "negative_code": [], "src_uid": "430f34fe715b8dcbcadf3b2c3e1e0381"} {"nl": {"description": "The bear has a string s\u2009=\u2009s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i,\u2009j (1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009|s|), that string x(i,\u2009j)\u2009=\u2009sisi\u2009+\u20091... sj contains at least one string \"bear\" as a substring.String x(i,\u2009j) contains string \"bear\", if there is such index k (i\u2009\u2264\u2009k\u2009\u2264\u2009j\u2009-\u20093), that sk\u2009=\u2009b, sk\u2009+\u20091\u2009=\u2009e, sk\u2009+\u20092\u2009=\u2009a, sk\u2009+\u20093\u2009=\u2009r.Help the bear cope with the given problem.", "input_spec": "The first line contains a non-empty string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20095000). It is guaranteed that the string only consists of lowercase English letters.", "output_spec": "Print a single number \u2014 the answer to the problem.", "sample_inputs": ["bearbtear", "bearaabearc"], "sample_outputs": ["6", "20"], "notes": "NoteIn the first sample, the following pairs (i,\u2009j) match: (1,\u20094),\u2009(1,\u20095),\u2009(1,\u20096),\u2009(1,\u20097),\u2009(1,\u20098),\u2009(1,\u20099).In the second sample, the following pairs (i,\u2009j) match: (1,\u2009\u20094),\u2009(1,\u2009\u20095),\u2009(1,\u2009\u20096),\u2009(1,\u2009\u20097),\u2009(1,\u2009\u20098),\u2009(1,\u2009\u20099),\u2009(1,\u2009\u200910),\u2009(1,\u2009\u200911),\u2009(2,\u2009\u200910),\u2009(2,\u2009\u200911),\u2009(3,\u2009\u200910),\u2009(3,\u2009\u200911),\u2009(4,\u2009\u200910),\u2009(4,\u2009\u200911),\u2009(5,\u2009\u200910),\u2009(5,\u2009\u200911),\u2009(6,\u2009\u200910),\u2009(6,\u2009\u200911),\u2009(7,\u2009\u200910),\u2009(7,\u2009\u200911)."}, "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}"}, {"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"}], "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"} {"nl": {"description": "You are given a sorted array $$$a_1, a_2, \\dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \\ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\\sum\\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 3 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$ 1 \\le a_i \\le 10^9$$$, $$$a_i \\ge a_{i-1}$$$). ", "output_spec": "Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. ", "sample_inputs": ["6 3\n4 8 15 16 23 42", "4 4\n1 3 3 7", "8 1\n1 1 2 3 5 8 13 21"], "sample_outputs": ["12", "0", "20"], "notes": "NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$. "}, "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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "negative_code": [], "src_uid": "2895624e708159bc2a6f3e91140a6c45"} {"nl": {"description": "There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \\le j \\le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows: In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms. The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \\le n \\le 500$$$)\u00a0\u2014 the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.", "output_spec": "For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.", "sample_inputs": ["3\n\n1\n\n2\n\n3"], "sample_outputs": ["1 \n1 \n1 1 \n1 \n1 1 \n1 0 1"], "notes": "NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$. The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance."}, "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * @author zhuxi\r\n * @since 2022/9/28 10:36\r\n * @note\r\n * 1734B. Bright, Nice, Brilliant | \u96be\u5ea6\uff1a800\r\n */\r\nobject Solution1734B {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n val sb = new StringBuilder\r\n for (_ <- 0 until t) {\r\n val n = StdIn.readInt()\r\n sb.clear()\r\n sb.append(\"1\")\r\n println(sb)\r\n if(n > 1) {\r\n sb.append(\" 1\")\r\n println(sb)\r\n }\r\n for (i <- 2 until n) {\r\n sb.delete(sb.length - 2, sb.length)\r\n sb.append(\" 0 1\")\r\n println(sb)\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:36\r\n * @note\r\n * 1734B. Bright, Nice, Brilliant | \u96be\u5ea6\uff1a800\r\n */\r\nobject Solution1734B {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n val sb = new StringBuilder\r\n for (_ <- 0 until t) {\r\n val n = StdIn.readInt()\r\n sb.clear()\r\n sb.append(\"1\")\r\n println(sb)\r\n if(n > 1) {\r\n sb.append(\" 1\")\r\n println(sb)\r\n }\r\n for (i <- 1 until n) {\r\n sb.delete(sb.length - 2, sb.length)\r\n sb.append(\" 0 1\")\r\n println(sb)\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * @author zhuxi\r\n * @since 2022/9/28 10:36\r\n * @note\r\n * 1734B. Bright, Nice, Brilliant | \u96be\u5ea6\uff1a800\r\n */\r\nobject Solution1734B {\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n for (_ <- 0 until t) {\r\n val n = StdIn.readInt()\r\n for (j <- 0 until n) {\r\n if (j == 0 || j == n - 1) print(\"1\") else print(\"0\")\r\n }\r\n println()\r\n }\r\n }\r\n}"}], "src_uid": "4a473e34f2be18a19c306d80d4693199"} {"nl": {"description": "Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \\le x_1, x_2, x_3 \\le n$$$, $$$0 \\le y_1, y_2, y_3 \\le m$$$ and the area of the triangle formed by these points is equal to $$$\\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.", "input_spec": "The single line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1\\le n, m \\le 10^9$$$, $$$2 \\le k \\le 10^9$$$).", "output_spec": "If there are no such points, print \"NO\". Otherwise print \"YES\" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ \u2014 coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).", "sample_inputs": ["4 3 3", "4 4 7"], "sample_outputs": ["YES\n1 0\n2 3\n4 1", "NO"], "notes": "NoteIn the first example area of the triangle should be equal to $$$\\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below: In the second example there is no triangle with area $$$\\frac{nm}{k} = \\frac{16}{7}$$$."}, "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 = nl()\n\n val p = gcd(N * M, K)\n if (K / p > 2) {\n out.println(\"NO\")\n return ()\n }\n\n val pn = gcd(N, p)\n val pm = p / pn\n val n0 = N / pn\n val m0 = M / pm\n\n val (x, y) = if (K / p == 2) {\n (n0, m0)\n } else {\n if (2 * n0 <= N) (2 * n0, m0) else (n0, 2 * m0)\n }\n\n out.println(\"YES\")\n out.println(\"0 0\")\n out.println(s\"$x 0\")\n out.println(s\"0 $y\")\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n def gcd(as: Array[Long]): Long = {\n var res = as(0)\n rep(as.length - 1, 1) { i =>\n res = gcd(res, as(i))\n }\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): 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"}], "negative_code": [], "src_uid": "5c026adda2ae3d7b707d5054bd84db3f"} {"nl": {"description": "The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.", "input_spec": "The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \\le k, x \\le n \\le 200$$$) \u2014 the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.", "output_spec": "Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer \u2014 the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.", "sample_inputs": ["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"], "sample_outputs": ["18", "-1", "100"], "notes": null}, "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, 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\u306a\u3093\u304b\u3067K\u306e\u500b\u6570\u3092\u7dad\u6301\u3057\u3064\u3064\u533a\u9593\u306e\u6700\u5927\u3092\u63a2\u3059\u6642\u306b\u4f7f\u3046\n * DP\u4e0a\u3067\uff11\u500b\u524d\u306e\u72b6\u614b\u304b\u3089\u3068\u308b\u306a\u3069\u3059\u308b\u3068\u304d\u306fmax(i-1)\u306e\u3088\u3046\u306b\u305d\u306e\u6642\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u3061\u3083\u3093\u3068\u6e21\u3055\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u306e\u306b\u6ce8\u610f\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 // \u6761\u4ef6\u9006\u3055\u307e\u306b\u3059\u308b\u3068\u6700\u5c0f\u306b\u306a\u308b\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 }\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\u306a\u3093\u304b\u3067K\u306e\u500b\u6570\u3092\u7dad\u6301\u3057\u3064\u3064\u533a\u9593\u306e\u6700\u5927\u3092\u63a2\u3059\u6642\u306b\u4f7f\u3046\n * DP\u4e0a\u3067\uff11\u500b\u524d\u306e\u72b6\u614b\u304b\u3089\u3068\u308b\u306a\u3069\u3059\u308b\u3068\u304d\u306fmax(i-1)\u306e\u3088\u3046\u306b\u305d\u306e\u6642\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u3061\u3083\u3093\u3068\u6e21\u3055\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u306e\u306b\u6ce8\u610f\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 // \u6761\u4ef6\u9006\u3055\u307e\u306b\u3059\u308b\u3068\u6700\u5c0f\u306b\u306a\u308b\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\u306a\u3093\u304b\u3067K\u306e\u500b\u6570\u3092\u7dad\u6301\u3057\u3064\u3064\u533a\u9593\u306e\u6700\u5927\u3092\u63a2\u3059\u6642\u306b\u4f7f\u3046\n * DP\u4e0a\u3067\uff11\u500b\u524d\u306e\u72b6\u614b\u304b\u3089\u3068\u308b\u306a\u3069\u3059\u308b\u3068\u304d\u306fmax(i-1)\u306e\u3088\u3046\u306b\u305d\u306e\u6642\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u3061\u3083\u3093\u3068\u6e21\u3055\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u306e\u306b\u6ce8\u610f\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 // \u6761\u4ef6\u9006\u3055\u307e\u306b\u3059\u308b\u3068\u6700\u5c0f\u306b\u306a\u308b\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": "\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\u306a\u3093\u304b\u3067K\u306e\u500b\u6570\u3092\u7dad\u6301\u3057\u3064\u3064\u533a\u9593\u306e\u6700\u5927\u3092\u63a2\u3059\u6642\u306b\u4f7f\u3046\n * DP\u4e0a\u3067\uff11\u500b\u524d\u306e\u72b6\u614b\u304b\u3089\u3068\u308b\u306a\u3069\u3059\u308b\u3068\u304d\u306fmax(i-1)\u306e\u3088\u3046\u306b\u305d\u306e\u6642\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u3061\u3083\u3093\u3068\u6e21\u3055\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u306e\u306b\u6ce8\u610f\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 // \u6761\u4ef6\u9006\u3055\u307e\u306b\u3059\u308b\u3068\u6700\u5c0f\u306b\u306a\u308b\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}"}, {"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}"}], "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\u306a\u3093\u304b\u3067K\u306e\u500b\u6570\u3092\u7dad\u6301\u3057\u3064\u3064\u533a\u9593\u306e\u6700\u5927\u3092\u63a2\u3059\u6642\u306b\u4f7f\u3046\n * DP\u4e0a\u3067\uff11\u500b\u524d\u306e\u72b6\u614b\u304b\u3089\u3068\u308b\u306a\u3069\u3059\u308b\u3068\u304d\u306fmax(i-1)\u306e\u3088\u3046\u306b\u305d\u306e\u6642\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u3061\u3083\u3093\u3068\u6e21\u3055\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u306e\u306b\u6ce8\u610f\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 // \u6761\u4ef6\u9006\u3055\u307e\u306b\u3059\u308b\u3068\u6700\u5c0f\u306b\u306a\u308b\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"} {"nl": {"description": "You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that: $$$b$$$ is a regular bracket sequence; if for some $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \\le n \\le 50$$$.", "output_spec": "For each testcase print \"YES\" if there exists such a string $$$b$$$ that: $$$b$$$ is a regular bracket sequence; if for some $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. Otherwise, print \"NO\". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["4\nAABBAC\nCACA\nBBBBAC\nABCA"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first testcase one of the possible strings $$$b$$$ is \"(())()\".In the second testcase one of the possible strings $$$b$$$ is \"()()\"."}, "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 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"}, {"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"} {"nl": {"description": "Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category: \"noob\" \u2014 if more than 50% of players have better results; \"random\" \u2014 if his result is not worse than the result that 50% of players have, but more than 20% of players have better results; \"average\" \u2014 if his result is not worse than the result that 80% of players have, but more than 10% of players have better results; \"hardcore\" \u2014 if his result is not worse than the result that 90% of players have, but more than 1% of players have better results; \"pro\" \u2014 if his result is not worse than the result that 99% of players have. When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.", "input_spec": "The first line contains the only integer number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.", "output_spec": "Print on the first line the number m \u2014 the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: \"noob\", \"random\", \"average\", \"hardcore\" or \"pro\" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.", "sample_inputs": ["5\nvasya 100\nvasya 200\nartem 100\nkolya 200\nigor 250", "3\nvasya 200\nkolya 1000\nvasya 1000"], "sample_outputs": ["4\nartem noob\nigor pro\nkolya random\nvasya random", "2\nkolya pro\nvasya pro"], "notes": "NoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category \"noob\". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category \"random\". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category \"pro\".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category \"pro\"."}, "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 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"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "0430fa56ec7f97efaf9d37096f72bcf8"} {"nl": {"description": "Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.", "input_spec": "The first line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009109). The second line contains integer n (1\u2009\u2264\u2009n\u2009<\u200910100000). There are no leading zeros in n. It's guaranteed that this situation is possible.", "output_spec": "Print the minimum number of digits in which the initial number and n can differ.", "sample_inputs": ["3\n11", "3\n99"], "sample_outputs": ["1", "0"], "notes": "NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to 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(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"}, {"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 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}"}], "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"} {"nl": {"description": "Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading \u2014 he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.", "input_spec": "The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 \u0438 s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.", "output_spec": "If Vasya can write the given anonymous letter, print YES, otherwise print NO", "sample_inputs": ["Instead of dogging Your footsteps it disappears but you dont notice anything\nwhere is your dog", "Instead of dogging Your footsteps it disappears but you dont notice anything\nYour dog is upstears", "Instead of dogging your footsteps it disappears but you dont notice anything\nYour dog is upstears", "abcdefg hijk\nk j i h g f e d c b a"], "sample_outputs": ["NO", "YES", "NO", "YES"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string $$$s$$$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met: each letter of the string is either painted in exactly one color (red or green) or isn't painted; each two letters which are painted in the same color are different; the number of letters painted in red is equal to the number of letters painted in green; the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E.\u2009g. consider a string $$$s$$$ equal to \"kzaaa\". One of the wonderful colorings of the string is shown in the figure. The example of a wonderful coloring of the string \"kzaaa\". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $$$k$$$ \u2014 the number of red (or green, these numbers are equal) letters in a wonderful coloring.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one non-empty string $$$s$$$ which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed $$$50$$$.", "output_spec": "For each test case, output a separate line containing one non-negative integer $$$k$$$ \u2014 the number of letters which will be painted in red in a wonderful coloring.", "sample_inputs": ["5\nkzaaa\ncodeforces\narchive\ny\nxxxxxx"], "sample_outputs": ["2\n5\n3\n0\n1"], "notes": "NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing $$$3$$$ or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters \"c\", \"o\", \"e\" in red and the second ones in green. Let's paint the letters \"d\", \"f\" in red and \"r\", \"s\" in green. So every letter will be painted in red or green, hence the answer better than $$$5$$$ doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red."}, "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"}, {"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"}], "negative_code": [], "src_uid": "a6b760941ab8be2c32c6dc66c623ea0e"} {"nl": {"description": "Eugene likes working with arrays. And today he needs your help in solving one challenging task.An array $$$c$$$ is a subarray of an array $$$b$$$ if $$$c$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $$$[-1, 2, -3]$$$ is good, as all arrays $$$[-1]$$$, $$$[-1, 2]$$$, $$$[-1, 2, -3]$$$, $$$[2]$$$, $$$[2, -3]$$$, $$$[-3]$$$ have nonzero sums of elements. However, array $$$[-1, 2, -1, -3]$$$ isn't good, as his subarray $$$[-1, 2, -1]$$$ has sum of elements equal to $$$0$$$.Help Eugene to calculate the number of nonempty good subarrays of a given array $$$a$$$.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\times 10^5$$$) \u00a0\u2014 the length of array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$) \u00a0\u2014 the elements of $$$a$$$. ", "output_spec": "Output a single integer \u00a0\u2014 the number of good subarrays of $$$a$$$.", "sample_inputs": ["3\n1 2 -3", "3\n41 -41 41"], "sample_outputs": ["5", "3"], "notes": "NoteIn the first sample, the following subarrays are good: $$$[1]$$$, $$$[1, 2]$$$, $$$[2]$$$, $$$[2, -3]$$$, $$$[-3]$$$. However, the subarray $$$[1, 2, -3]$$$ isn't good, as its subarray $$$[1, 2, -3]$$$ has sum of elements equal to $$$0$$$.In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray $$$[41, -41, 41]$$$ isn't good, as its subarray $$$[41, -41]$$$ has sum of elements equal to $$$0$$$."}, "positive_code": [{"source_code": "object C extends App {\n implicit class SetOps[A](val set: Set[A]) extends AnyVal {\n def fillWhile(xs: List[A]): (List[A], Set[A]) = xs match {\n case Nil => (Nil, set)\n case x :: rs =>\n if (set.contains(x)) (xs, set) else (set + x).fillWhile(rs)\n }\n }\n\n private def howGood(as: List[Int]): Long = {\n\n @scala.annotation.tailrec\n def go(ps: List[Long],\n qs: List[Long],\n s: Set[Long] = Set(0L),\n acc: Long = 0L): Long = ps match {\n case Nil => acc\n case x :: xs =>\n val (nqs, ns) = s.fillWhile(qs)\n go(xs, nqs, ns - x, acc + ns.size - 1)\n }\n\n val ps = as.scanLeft(0L)(_ + _)\n\n go(ps, ps.tail)\n }\n\n val n = scala.io.StdIn.readInt()\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n println(howGood(as))\n}"}], "negative_code": [], "src_uid": "61fb771f915b551a9bcce90c74e0ef64"} {"nl": {"description": "A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold: ai\u2009\u2265\u2009ai\u2009-\u20091 for all even i, ai\u2009\u2264\u2009ai\u2009-\u20091 for all odd i\u2009>\u20091. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn\u2019t z-sorted.Can you make the array z-sorted?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of elements in the array a. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of the array a.", "output_spec": "If it's possible to make the array a z-sorted print n space separated integers ai \u2014 the elements after z-sort. Otherwise print the only word \"Impossible\".", "sample_inputs": ["4\n1 2 2 1", "5\n1 3 2 2 5"], "sample_outputs": ["1 2 1 2", "1 5 2 3 2"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "2401d34db475853661d6e1e1cb5a8216"} {"nl": {"description": "Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u2009n\u2009-\u2009k\u2009+\u20091,\u2009b\u2009-\u2009a\u2009\u2265\u2009k) and sign all laws with numbers lying in the segments [a;\u00a0a\u2009+\u2009k\u2009-\u20091] and [b;\u00a0b\u2009+\u2009k\u2009-\u20091] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 0\u2009<\u20092k\u2009\u2264\u2009n) \u2014 the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1,\u2009x2,\u2009...,\u2009xn \u2014 the absurdity of each law (1\u2009\u2264\u2009xi\u2009\u2264\u2009109).", "output_spec": "Print two integers a, b \u2014 the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a;\u00a0a\u2009+\u2009k\u2009-\u20091] and [b;\u00a0b\u2009+\u2009k\u2009-\u20091]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.", "sample_inputs": ["5 2\n3 6 1 1 6", "6 2\n1 1 1 1 1 1"], "sample_outputs": ["1 4", "1 3"], "notes": "NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3\u2009+\u20096\u2009+\u20091\u2009+\u20096\u2009=\u200916.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u20094."}, "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(_.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"}, {"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 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}"}], "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"} {"nl": {"description": "You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row \"00110\" one cell to the right, we get a row \"00011\", but if we shift a row \"00110\" one cell to the left, we get a row \"01100\".Determine the minimum number of moves needed to make some table column consist only of numbers 1.", "input_spec": "The first line contains two space-separated integers: n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of rows in the table and m (1\u2009\u2264\u2009m\u2009\u2264\u2009104)\u00a0\u2014 the number of columns in the table. Then n lines follow, each of them contains m characters \"0\" or \"1\": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides \"0\" and \"1\".", "output_spec": "Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.", "sample_inputs": ["3 6\n101010\n000100\n100000", "2 3\n111\n000"], "sample_outputs": ["3", "-1"], "notes": "NoteIn the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.In the second sample one can't shift the rows to get a column containing only 1s."}, "positive_code": [{"source_code": "import scala.io.StdIn._\nimport scala.language.postfixOps\nimport scala.math.min\n\nobject TaskC extends App {\n val MaxValue = 1e9 toInt\n val MinValue = -MaxValue\n val n :: m :: Nil = readLine.split(\" \").map(_.toInt).toList\n\n val table = 1 to n map (_ => readLine.split(\"\").map(_.toInt)) toArray\n\n val ones = Array.fill(n)(Array.fill(m)(MaxValue))\n\n for(i <- 0 until n){\n val first = table(i).indexOf(1)\n val last = table(i).lastIndexOf(1)\n\n var lastTraversed = MinValue\n for(j <- 0 until m) {\n if (table(i)(j) == 0) {\n ones(i)(j) = min(j - lastTraversed, j + m - last)\n } else {\n ones(i)(j) = 0\n lastTraversed = j\n }\n }\n\n lastTraversed = MaxValue\n for (j <- 0 until m reverse) {\n if (table(i)(j) == 0) {\n ones(i)(j) = min(ones(i)(j), min(lastTraversed - j, m - j + first))\n } else {\n lastTraversed = j\n }\n }\n }\n\n println(if (table.forall(_.contains(1))) countMoves else -1)\n\n def countMoves = 0 until m map(j => 0 until n map(i => ones(i)(j)) sum) min\n}\n"}], "negative_code": [], "src_uid": "a491be7d5883d594c3e907a22be607c9"} {"nl": {"description": "Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i.\u00a0e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the number of numbers on the board. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$).", "output_spec": "Print one number that will be left on the board.", "sample_inputs": ["3\n2 1 3", "3\n2 2 2"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample, the first player erases $$$3$$$ and the second erases $$$1$$$. $$$2$$$ is left on the board.In the second sample, $$$2$$$ is left on the board regardless of the actions of the players."}, "positive_code": [{"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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": " \"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you.\" Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\\&$$$ $$$a_j \\ge a_i \\oplus a_j$$$, where $$$\\&$$$ denotes the bitwise AND operation, and $$$\\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For every test case print one non-negative integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"], "sample_outputs": ["1\n3\n2\n0\n0"], "notes": "NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\\&$$$ $$$7 = 4$$$, and $$$4 \\oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1\u2009/\u20094, and the problem's maximum point value is equal to 1500.If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x\u2009/\u2009250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000\u00b7(1\u2009-\u200940\u2009/\u2009250)\u2009=\u20091680 points for this problem.There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.Unfortunately, Vasya is a cheater. He has registered 109\u2009+\u20097 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009120)\u00a0\u2014 the number of round participants, including Vasya and Petya. Each of the next n lines contains five integers ai,\u20091,\u2009ai,\u20092...,\u2009ai,\u20095 (\u2009-\u20091\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u2009119)\u00a0\u2014 the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j. It is guaranteed that each participant has made at least one successful submission. Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order.", "output_spec": "Output a single integer\u00a0\u2014 the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal.", "sample_inputs": ["2\n5 15 40 70 115\n50 45 40 30 15", "3\n55 80 10 -1 -1\n15 -1 79 60 -1\n42 -1 13 -1 -1", "5\n119 119 119 119 119\n0 0 0 0 -1\n20 65 12 73 77\n78 112 22 23 11\n1 78 60 111 62", "4\n-1 20 40 77 119\n30 10 73 50 107\n21 29 -1 64 98\n117 65 -1 -1 -1"], "sample_outputs": ["2", "3", "27", "-1"], "notes": "NoteIn the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980\u2009+\u2009940\u2009+\u2009420\u2009+\u2009360\u2009+\u2009270\u2009=\u20092970 points, while Petya will score just 800\u2009+\u2009820\u2009+\u2009420\u2009+\u2009440\u2009+\u2009470\u2009=\u20092950 points.In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points.In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one."}, "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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 countSolved = Array.fill(5)(0)\n\n val as = Array.fill(n) {\n val aas = readInts(5)\n for (i <- 0 until 5) if (aas(i) >= 0) countSolved(i) += 1\n aas\n }\n\n var res = Long.MaxValue\n\n val levelScore = Array(3000, 2500, 2000, 1500, 1000, 500).reverse\n\n val problemLevel = Array.fill(5)(0)\n\n def vasyaWins(): Boolean = {\n var vasyaScore, petyaScore = 0L\n for (i <- 0 until 5) {\n val score = levelScore(problemLevel(i))\n if (as(0)(i) >= 0) vasyaScore += score - score * as(0)(i) / 250\n if (as(1)(i) >= 0) petyaScore += score - score * as(1)(i) / 250\n }\n vasyaScore > petyaScore\n }\n\n def can(budget: Long): Boolean = {\n var ok = true\n var minBudget = 0\n for (i <- 0 until 5) {\n val level = problemLevel(i)\n if (countSolved(i) > 0 && as(0)(i) != -1) {\n val l1 = 1 << level\n val bb = if (l1 == 1) 0 else l1 * countSolved(i) - n\n if (bb > minBudget) minBudget = bb\n if (!(countSolved(i) * (1 << level) <= n + budget &&\n (countSolved(i) + budget) * (2 << level) > n + budget)) ok = false\n }\n }\n for (i <- 0 until 5) {\n val level = problemLevel(i)\n if (countSolved(i) > 0 && as(0)(i) == -1) {\n if (!(countSolved(i) * (1 << level) <= n + budget &&\n countSolved(i) * (2 << level) > n + minBudget)) ok = false\n }\n }\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(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n def combinations(problem: Int): Unit = {\n if (problem == 5) {\n if (vasyaWins()) {\n val r = binSearch(0, 1000000007)\n if (r < res) res = r\n }\n } else {\n for (level <- 0 until 6) {\n problemLevel(problem) = level\n combinations(problem + 1)\n }\n }\n }\n\n combinations(0)\n\n if (res > 1000000007) res = -1\n\n println(res)\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) = readInts(1)\n\n val countSolved = Array.fill(5)(0)\n\n val as = Array.fill(n) {\n val aas = readInts(5)\n for (i <- 0 until 5) if (aas(i) >= 0) countSolved(i) += 1\n aas\n }\n\n var res = Long.MaxValue\n\n val levelScore = Array(3000, 2500, 2000, 1500, 1000, 500).reverse\n\n val problemLevel = Array.fill(5)(0)\n\n def vasyaWins(): Boolean = {\n var vasyaScore, petyaScore = 0L\n for (i <- 0 until 5) {\n val score = levelScore(problemLevel(i))\n if (as(0)(i) >= 0) vasyaScore += score - score * as(0)(i) / 250\n if (as(1)(i) >= 0) petyaScore += score - score * as(1)(i) / 250\n }\n vasyaScore > petyaScore\n }\n\n def can(budget: Long): Boolean = {\n var ok = true\n var minBudget = 0\n for (i <- 0 until 5) {\n val level = problemLevel(i)\n if (countSolved(i) > 0 && as(0)(i) != -1) {\n val l1 = 1 << level\n val bb = if (l1 == 1) 0 else l1 * countSolved(i) - n //(n - countSolved(i) * l1) / (l1 - 1)\n if (bb > minBudget) minBudget = bb\n if (!(countSolved(i) * (1 << level) <= n + budget &&\n (countSolved(i) + budget) * (2 << level) > n + budget)) ok = false\n }\n }\n for (i <- 0 until 5) {\n val level = problemLevel(i)\n if (countSolved(i) > 0 && as(0)(i) == -1) {\n if (!(countSolved(i) * (1 << level) <= n + budget &&\n countSolved(i) * (2 << level) > n + minBudget)) ok = false\n }\n }\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(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n def combinations(problem: Int): Unit = {\n if (problem == 5) {\n if (vasyaWins()) {\n val r = binSearch(0, 1000000007)\n if (r < res) res = r\n }\n } else {\n for (level <- 0 until 6) {\n problemLevel(problem) = level\n combinations(problem + 1)\n }\n }\n }\n\n combinations(0)\n\n if (res == Long.MaxValue) res = -1\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(n) = readInts(1)\n\n val countSolved = Array.fill(5)(0)\n\n val as = Array.fill(n) {\n val aas = readInts(5)\n for (i <- 0 until 5) if (aas(i) >= 0) countSolved(i) += 1\n aas\n }\n\n var res = Long.MaxValue\n\n val levelScore = Array(3000, 2500, 2000, 1500, 1000, 500).reverse\n\n val problemLevel = Array.fill(5)(0)\n\n def vasyaWins(): Boolean = {\n var vasyaScore, petyaScore = 0L\n for (i <- 0 until 5) {\n val score = levelScore(problemLevel(i))\n if (as(0)(i) >= 0) vasyaScore += score - score * as(0)(i) / 250\n if (as(1)(i) >= 0) petyaScore += score - score * as(1)(i) / 250\n }\n vasyaScore > petyaScore\n }\n\n def can(budget: Long): Boolean = {\n var ok = true\n var minBudget = 0\n for (i <- 0 until 5) {\n val level = problemLevel(i)\n if (countSolved(i) > 0 && as(0)(i) != -1) {\n val l1 = 1 << level\n val bb = if (l1 == 1) 0 else l1 * countSolved(i) - n //(n - countSolved(i) * l1) / (l1 - 1)\n if (bb > minBudget) minBudget = bb\n if (!(countSolved(i) * (1 << level) <= n + budget &&\n (countSolved(i) + budget) * (2 << level) > n + budget)) ok = false\n // println(i, level, levelScore(level), countSolved(i), ok, bb)\n }\n }\n for (i <- 0 until 5) {\n val level = problemLevel(i)\n if (countSolved(i) > 0 && as(0)(i) == -1) {\n if (!(countSolved(i) * (1 << level) <= n + budget &&\n countSolved(i) * (2 << level) > n + minBudget)) ok = false\n //println(i, level, levelScore(level), countSolved(i), ok)\n }\n }\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(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n def combinations(problem: Int): Unit = {\n if (problem == 5) {\n// println(problemLevel.mkString(\" \"))\n if (vasyaWins()) {\n val r = binSearch(0, Int.MaxValue)\n //if (problemLevel.toSeq == Seq(0, 2, 0, 0, 0)) println(r)\n if (r < res) {\n res = r\n// println(r, res)\n// println(problemLevel.mkString(\" \"))\n// println(problemLevel.map(levelScore).mkString(\" \"))\n }\n }\n } else {\n for (level <- 0 until 6) {\n problemLevel(problem) = level\n combinations(problem + 1)\n }\n }\n }\n//problemLevel(0) = 0\n// problemLevel(1) = 2\n// problemLevel(2) = 0\n// problemLevel(3) = 1\n// problemLevel(4) = 0\n// problemLevel(0) = 0\n// problemLevel(1) = 2\n// problemLevel(2) = 1\n// problemLevel(3) = 2\n// problemLevel(4) = 5\n// println(vasyaWins())\n// println(can(3))\n// println(can(3000))\n //println(binSearch(0, Int.MaxValue))\n\n combinations(0)\n\n if (res == Long.MaxValue) res = -1\n\n println(res)\n}\n"}], "src_uid": "bb68a49399e501739782601795609105"} {"nl": {"description": "Mainak has two positive integers $$$n$$$ and $$$m$$$.Mainak finds a sequence $$$a_1, a_2, \\ldots, a_n$$$ of $$$n$$$ positive integers interesting, if for all integers $$$i$$$ ($$$1 \\le i \\le n$$$), the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$ is $$$0$$$. Formally if $$$p_i$$$ is the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$, then $$$a$$$ is an interesting sequence if $$$p_1 = p_2 = \\ldots = p_n = 0$$$.For example, sequences $$$[1,3,2,3,1,2,3]$$$, $$$[4,4,4,4]$$$, $$$[25]$$$ are interesting, whereas $$$[1,2,3,4]$$$ ($$$p_2 = 1 \\ne 0$$$), $$$[4,1,1,2,4]$$$ ($$$p_1 = 1 \\oplus 1 \\oplus 2 = 2 \\ne 0$$$), $$$[29,30,30]$$$ ($$$p_2 = 29 \\ne 0$$$) aren't interesting.Here $$$a \\oplus b$$$ denotes bitwise XOR of integers $$$a$$$ and $$$b$$$.Find any interesting sequence $$$a_1, a_2, \\ldots, a_n$$$ (or report that there exists no such sequence) such that the sum of the elements in the sequence $$$a$$$ is equal to $$$m$$$, i.e. $$$a_1 + a_2 \\ldots + a_n = m$$$.As a reminder, the bitwise XOR of an empty sequence is considered to be $$$0$$$.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line and the only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le m \\le 10^9$$$) \u2014 the length of the sequence and the sum of the elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, if there exists some interesting sequence, output \"Yes\" on the first line, otherwise output \"No\". You may print each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\" will all be recognized as positive answer). If the answer is \"Yes\", output $$$n$$$ positive integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$a_i \\ge 1$$$), forming an interesting sequence such that $$$a_1 + a_2 \\ldots + a_n = m$$$. If there are multiple solutions, output any.", "sample_inputs": ["4\n1 3\n6 12\n2 1\n3 6"], "sample_outputs": ["Yes\n3\nYes\n1 3 2 2 3 1\nNo\nYes\n2 2 2"], "notes": "Note In the first test case, $$$[3]$$$ is the only interesting sequence of length $$$1$$$ having sum $$$3$$$. In the third test case, there is no sequence of length $$$2$$$ having sum of elements equal to $$$1$$$, so there is no such interesting sequence. In the fourth test case, $$$p_1 = p_2 = p_3 = 0$$$, because bitwise XOR of an empty sequence is $$$0$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "041143f69ce9d00924ce8deb56b723c5"} {"nl": {"description": "Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \\le k_i$$$ for all $$$1 \\le i \\le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \\dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 < k_2 < \\dots < k_n$$$ ($$$1 \\le k_i \\le 10^9$$$)\u00a0\u2014 the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \\dots, h_n$$$ ($$$1 \\le h_i \\le k_i \\le 10^9$$$)\u00a0\u2014 the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the least amount of mana required for Monocarp to kill all monsters.", "sample_inputs": ["3\n\n1\n\n6\n\n4\n\n2\n\n4 5\n\n2 2\n\n3\n\n5 7 9\n\n2 1 2"], "sample_outputs": ["10\n6\n7"], "notes": "NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively."}, "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 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 h = new Array[Int](n+1)\n val k = new Array[Int](n+1)\n for (i <- 1 to n) {\n k(i) = readInt()\n }\n for (i <- 1 to n) {\n h(i) = readInt()\n }\n var s = 0\n\n var ans = Vector[pair]()\n for (i <- 1 to n) {\n s = k(i) - h(i) + 1\n while (ans.nonEmpty && ans.last.b >= s) {\n s = min(s, ans.last.a)\n ans = ans.init\n }\n ans :+= pair(s, k(i))\n }\n var cnt = 0L\n var l = 0L\n for (c <- ans) {\n l = (c.b - c.a + 1).toLong\n cnt += l * (l+1L) / 2L\n }\n writer.println(cnt)\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": "690c28ef1275035895b9154ff0e17f4c"} {"nl": {"description": "The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, \"Beavershave 5000\". Beavershave 5000 can shave beavers by families! How does it work? Very easily!There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1,\u2009a2,\u2009...,\u2009an of n these beavers. Beavershave 5000 needs one session to shave beavers with ids from x to y (inclusive) if and only if there are such indices i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik, that ai1\u2009=\u2009x, ai2\u2009=\u2009x\u2009+\u20091, ..., aik\u2009-\u20091\u2009=\u2009y\u2009-\u20091, aik\u2009=\u2009y. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1,\u20092,\u20093,\u2009...,\u2009n.If we can't shave beavers from x to y in one session, then we can split these beavers into groups [x,\u2009p1], [p1\u2009+\u20091,\u2009p2], ..., [pm\u2009+\u20091,\u2009y] (x\u2009\u2264\u2009p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009pm\u2009<\u2009y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs m\u2009+\u20091 working sessions to shave beavers from x to y.All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types: what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive? two beavers on positions x and y (the beavers ax and ay) swapped. You can assume that any beaver can be shaved any number of times.", "input_spec": "The first line contains integer n \u2014 the total number of beavers, 2\u2009\u2264\u2009n. The second line contains n space-separated integers \u2014 the initial beaver permutation. The third line contains integer q \u2014 the number of queries, 1\u2009\u2264\u2009q\u2009\u2264\u2009105. The next q lines contain the queries. Each query i looks as pi xi yi, where pi is the query type (1 is to shave beavers from xi to yi, inclusive, 2 is to swap beavers on positions xi and yi). All queries meet the condition: 1\u2009\u2264\u2009xi\u2009<\u2009yi\u2009\u2264\u2009n. to get 30 points, you need to solve the problem with constraints: n\u2009\u2264\u2009100 (subproblem B1); to get 100 points, you need to solve the problem with constraints: n\u2009\u2264\u20093\u00b7105 (subproblems B1+B2). Note that the number of queries q is limited 1\u2009\u2264\u2009q\u2009\u2264\u2009105 in both subproblem B1 and subproblem B2.", "output_spec": "For each query with pi\u2009=\u20091, print the minimum number of Beavershave 5000 sessions.", "sample_inputs": ["5\n1 3 4 2 5\n6\n1 1 5\n1 3 4\n2 2 3\n1 1 5\n2 1 5\n1 1 5"], "sample_outputs": ["2\n1\n3\n5"], "notes": null}, "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, -1) // position -> id\n val I = Array.ofDim[Int](N) // id -> position\n REP(N) { i =>\n I(A(i)) = i\n }\n\n // id1 -> id2\u304c\u306e\u4f4d\u7f6e\u304c\u9006\u306b\u306a\u3063\u3066\u3044\u308b\u6570\n val cnt = new SegmentTree(N, 0)(_ + _) // [1, N-1]\n\n def updateInv(id: Int): Unit = {\n if (id > 0) {\n val inv = if (I(id - 1) > I(id)) 1 else 0\n cnt.update(id, inv)\n }\n if (id < N - 1) {\n val inv = if (I(id) > I(id + 1)) 1 else 0\n cnt.update(id + 1, inv)\n }\n }\n\n REP(N) { i =>\n updateInv(i)\n }\n\n REP(ni()) { _ =>\n val tpe = ni()\n val x, y = ni() - 1\n tpe match {\n case 1 =>\n val inv = cnt.query(x + 1, y + 1)\n val ans = 1 + inv // group = n - edge = n - (n - 1 - inv)\n out.println(ans)\n\n case 2 =>\n val idx = A(x)\n val idy = A(y)\n A(y) = idx\n A(x) = idy\n I(idx) = y\n I(idy) = x\n\n updateInv(idx)\n updateInv(idy)\n }\n }\n }\n\n /**\n * @param n \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\n * type A = Int\n */\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\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 = ni()\n val A = na(N, -1) // position -> id\n val I = Array.ofDim[Int](N) // id -> position\n REP(N) { i =>\n I(A(i)) = i\n }\n\n // id1 -> id2\u304c\u306e\u4f4d\u7f6e\u304c\u9006\u306b\u306a\u3063\u3066\u3044\u308b\u6570\n val cnt = new SegmentTree(N, 0)(_ + _) // [1, N-1]\n\n def updateInv(id: Int): Unit = {\n if (id > 0) {\n val inv = if (I(id - 1) > I(id)) 1 else 0\n cnt.update(id, inv)\n }\n if (id < N - 1) {\n val inv = if (I(id) > I(id + 1)) 1 else 0\n cnt.update(id + 1, inv)\n }\n }\n\n REP(N) { i =>\n updateInv(i)\n }\n\n REP(ni()) { _ =>\n val tpe = ni()\n val x, y = ni() - 1\n tpe match {\n case 1 =>\n val inv = cnt.query(x + 1, y + 1)\n val ans = 1 + inv // group = n - edge = n - (n - 1 - inv)\n out.println(ans)\n\n case 2 =>\n val idx = A(x)\n val idy = A(y)\n A(y) = idx\n A(x) = idy\n I(idx) = y\n I(idy) = x\n\n updateInv(x)\n updateInv(y)\n }\n }\n }\n\n /**\n * @param n \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\n * type A = Int\n */\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\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": "0bf3f5b910d58b8f608ab8214732eb05"} {"nl": {"description": "Polycarp has n dice d1,\u2009d2,\u2009...,\u2009dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1,\u2009d2,\u2009...,\u2009dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A\u2009=\u200911, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.", "input_spec": "The first line contains two integers n,\u2009A (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u2009n\u2009\u2264\u2009A\u2009\u2264\u2009s) \u2014 the number of dice and the sum of shown values where s\u2009=\u2009d1\u2009+\u2009d2\u2009+\u2009...\u2009+\u2009dn. The second line contains n integers d1,\u2009d2,\u2009...,\u2009dn (1\u2009\u2264\u2009di\u2009\u2264\u2009106), where di is the maximum value that the i-th dice can show.", "output_spec": "Print n integers b1,\u2009b2,\u2009...,\u2009bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.", "sample_inputs": ["2 8\n4 4", "1 3\n5", "2 3\n2 3"], "sample_outputs": ["3 3", "4", "0 1"], "notes": "NoteIn the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3."}, "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 Reader._\n import Writer._\n def exit() = {\n close()\n System.exit(0)\n }\n \n val N = readInt\n val A = readLong\n \n val dice = Array.fill(N)(readInt)\n val total = dice.foldLeft(0L)(_+_)\n \n println(dice map { d =>\n val h = max(d - (A-N+1), 0)\n val l = max(A - (total-d) - 1, 0)\n h + l\n } mkString \" \")\n \n \n \n \n exit\n \n object Reader {\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 object Writer {\n import java.io._\n private[this] val writer = new BufferedWriter(new OutputStreamWriter(System.out))\n \n def println(x: String) {\n writer.write(x)\n writer.newLine()\n }\n def println(x: Int): Unit = println(java.lang.Integer.toString(x))\n def println(x: Long): Unit = println(java.lang.Long.toString(x))\n def println(x: Double): Unit = println(java.lang.Double.toString(x))\n def println(x: Float): Unit = println(java.lang.Float.toString(x))\n def close() {\n writer.flush()\n writer.close()\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "2c51414eeb430ad06aac53a99ff95eff"} {"nl": {"description": "Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!", "input_spec": "The first line of the input contains three space-separated integers l, r and k (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u20091018, 2\u2009\u2264\u2009k\u2009\u2264\u2009109).", "output_spec": "Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print \"-1\" (without the quotes).", "sample_inputs": ["1 10 2", "2 4 5"], "sample_outputs": ["1 2 4 8", "-1"], "notes": "NoteNote to the first sample: numbers 20\u2009=\u20091, 21\u2009=\u20092, 22\u2009=\u20094, 23\u2009=\u20098 lie within the specified range. The number 24\u2009=\u200916 is greater then 10, thus it shouldn't be printed."}, "positive_code": [{"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.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}"}, {"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"}, {"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": "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"}], "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"} {"nl": {"description": "Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$. Each of its vertices also has an integer $$$a_i$$$ written on it. For each vertex $$$i$$$, Evlampiy calculated $$$c_i$$$\u00a0\u2014 the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. Illustration for the second example, the first integer is $$$a_i$$$ and the integer in parentheses is $$$c_i$$$After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $$$c_i$$$, but he completely forgot which integers $$$a_i$$$ were written on the vertices.Help him to restore initial integers!", "input_spec": "The first line contains an integer $$$n$$$ $$$(1 \\leq n \\leq 2000)$$$ \u2014 the number of vertices in the tree. The next $$$n$$$ lines contain descriptions of vertices: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \\leq p_i \\leq n$$$; $$$0 \\leq c_i \\leq n-1$$$), where $$$p_i$$$ is the parent of vertex $$$i$$$ or $$$0$$$ if vertex $$$i$$$ is root, and $$$c_i$$$ is the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. It is guaranteed that the values of $$$p_i$$$ describe a rooted tree with $$$n$$$ vertices.", "output_spec": "If a solution exists, in the first line print \"YES\", and in the second line output $$$n$$$ integers $$$a_i$$$ $$$(1 \\leq a_i \\leq {10}^{9})$$$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $$$a_i$$$ are between $$$1$$$ and $$$10^9$$$. If there are no solutions, print \"NO\".", "sample_inputs": ["3\n2 0\n0 2\n2 0", "5\n0 1\n1 3\n2 1\n3 0\n2 0"], "sample_outputs": ["YES\n1 2 1", "YES\n2 3 2 1 2"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn._;\n\nobject Main extends App {\n\n def insertAt[T](x: T, lst: List[T], i: Int): List[T] = {\n if (i == 0)\n x :: lst\n else if (i != 0 && lst.isEmpty)\n throw new Exception()\n else\n lst.head :: insertAt(x, lst.tail, i - 1)\n }\n\n /* get input */\n val n = readInt()\n val (pArr, cArr) = (1 to n)\n .map(_ => {\n val line = readLine().split(\"\\\\s\").map(_.toInt)\n (line(0), line(1))\n })\n .unzip\n\n /* build the graph */\n val edges = Array.fill(n + 1) { Array[Int]() }\n pArr.zipWithIndex.foreach { case (p, i) => edges(p) :+= (i + 1) }\n\n /* dfs */\n def dfs(nodeId: Int): List[Int] = {\n val branches = edges(nodeId).map { dfs(_) }.fold(List()) {\n case (a, b) => a ++ b\n }\n insertAt(nodeId, branches, cArr(nodeId - 1))\n }\n\n /* dfs(edges(0)(0)).foreach(x => print(x.toString + \" \"))\n println\n (1 to n).foreach(x => print(x.toString + \" \"))\n println */\n\n var result: List[Int] = null\n try {\n result = dfs(edges(0)(0))\n } catch {\n case e: Exception => { result = null }\n }\n if (result == null) {\n println(\"NO\")\n } else {\n println(\"YES\")\n result.zipWithIndex\n .sortBy(_._1)\n .foreach { case (_, i) => print((i + 1).toString + \" \") }\n println\n }\n}\n"}], "negative_code": [], "src_uid": "f097cc7057bb9a6b9fc1d2a11ee99835"} {"nl": {"description": "Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n\u2009-\u20091 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:let starting_time be an array of length ncurrent_time = 0dfs(v):\tcurrent_time = current_time + 1\tstarting_time[v] = current_time\tshuffle children[v] randomly (each permutation with equal possibility)\t// children[v] is vector of children cities of city v\tfor u in children[v]:\t\tdfs(u)As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of cities in USC. The second line contains n\u2009-\u20091 integers p2,\u2009p3,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009<\u2009i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.", "output_spec": "In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096.", "sample_inputs": ["7\n1 2 1 1 4 4", "12\n1 1 2 2 4 4 3 3 1 10 8"], "sample_outputs": ["1.0 4.0 5.0 3.5 4.5 5.0 5.0", "1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "750e1d9e43f916699537705c11d64d29"} {"nl": {"description": "The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows: If the current skill immediately follows another skill of a different type, then its damage is doubled. In other words, If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage; If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage; If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage; If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal. ", "input_spec": "Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$) \u2014 the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$), indicating the number of skills. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\leq a_i \\leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\leq b_i \\leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output the maximum damage the hero can deal.", "sample_inputs": ["4\n\n4\n\n0 1 1 1\n\n1 10 100 1000\n\n6\n\n0 0 0 1 1 1\n\n3 4 5 6 7 8\n\n3\n\n1 1 1\n\n1000000000 1000000000 1000000000\n\n1\n\n1\n\n1"], "sample_outputs": ["2112\n63\n3000000000\n1"], "notes": "NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \\times 1 + 2 \\times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \\times 6 + 2 \\times 4 + 2 \\times 7 + 2 \\times 5 + 2 \\times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$1$$$. "}, "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}"}, {"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"}], "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"} {"nl": {"description": "You are given n points on the straight line \u2014 the positions (x-coordinates) of the cities and m points on the same line \u2014 the positions (x-coordinates) of the cellular towers. All towers work in the same way \u2014 they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r\u2009=\u20090 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.", "input_spec": "The first line contains two positive integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1,\u2009b2,\u2009...,\u2009bm (\u2009-\u2009109\u2009\u2264\u2009bj\u2009\u2264\u2009109) \u2014 the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.", "output_spec": "Print minimal r so that each city will be covered by cellular network.", "sample_inputs": ["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"], "sample_outputs": ["4", "3"], "notes": null}, "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)\n val b = in.next().split(' ').map(_.toInt)\n\n var max = 0\n var i = 0\n var j = 0\n\n while (i < a.length && j < b.length && a(i) < b(0)) {\n max = Math.max(max, b(0) - a(i))\n i += 1\n }\n\n j += 1\n\n while (i < a.length && j < b.length) {\n while (i < a.length && a(i) < b(j)) {\n max = Math.max(max, Math.min(a(i) - b(j - 1), b(j) - a(i)))\n i += 1\n }\n j += 1\n }\n\n while (i < a.length) {\n max = Math.max(max, a(i) - b(m - 1))\n i += 1\n }\n\n println(max)\n\n}"}], "negative_code": [], "src_uid": "9fd8e75cb441dc809b1b2c48c4012c76"} {"nl": {"description": "You have to restore the wall. The wall consists of $$$N$$$ pillars of bricks, the height of the $$$i$$$-th pillar is initially equal to $$$h_{i}$$$, the height is measured in number of bricks. After the restoration all the $$$N$$$ pillars should have equal heights.You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $$$A$$$; remove a brick from the top of one non-empty pillar, the cost of this operation is $$$R$$$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $$$M$$$.You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $$$0$$$.What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?", "input_spec": "The first line of input contains four integers $$$N$$$, $$$A$$$, $$$R$$$, $$$M$$$ ($$$1 \\le N \\le 10^{5}$$$, $$$0 \\le A, R, M \\le 10^{4}$$$)\u00a0\u2014 the number of pillars and the costs of operations. The second line contains $$$N$$$ integers $$$h_{i}$$$ ($$$0 \\le h_{i} \\le 10^{9}$$$)\u00a0\u2014 initial heights of pillars.", "output_spec": "Print one integer\u00a0\u2014 the minimal cost of restoration.", "sample_inputs": ["3 1 100 100\n1 3 8", "3 100 1 100\n1 3 8", "3 100 100 1\n1 3 8", "5 1 2 4\n5 5 3 6 5", "5 1 2 2\n5 5 3 6 5"], "sample_outputs": ["12", "9", "4", "4", "3"], "notes": null}, "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 C643F(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 C643F(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n n = ni()\n a = ni()\n r = ni()\n m = ni()\n h = na(n)\n\n var lo = 0L\n var hi = 1e10.toLong\n while (hi - lo > 2) {\n val md1 = lo + (hi - lo) / 3\n val md2 = lo + 2 * (hi - lo) / 3\n if(cost(md1) > cost(md2)) lo = md1\n else hi = md2\n }\n\n var ans = Long.MaxValue\n lo to hi foreach { i =>\n ans = Math.min(cost(i), ans)\n }\n out.println(ans)\n }\n\n def cost(fh: Long): Long = {\n var req = 0L\n var extra = 0L\n REP(n) { i =>\n if(fh > h(i)) req += (fh - h(i))\n else if (fh < h(i)) extra += (h(i) - fh)\n }\n val x = Math.min(req, extra)\n// out.println(fh + \" \" + req + \" \" + extra + \" \" + (x * Math.min(m, a+r) + (req - x) * a + (extra - x) * r))\n x * Math.min(m, a+r) + (req - x) * a + (extra - x) * r\n }\n\n var n: Int = _\n var a: Int = _\n var r: Int = _\n var m: Int = _\n var h: Array[Int] = _\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 C643F(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 C643F(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\n\n import Main._\n import fScanner._\n\n def solve(): Unit = {\n n = ni()\n a = ni()\n r = ni()\n m = ni()\n h = na(n)\n\n var lo = 0\n var hi = 2 * 1e5.toInt\n while (hi - lo > 2) {\n val md1 = lo + (hi - lo) / 3\n val md2 = lo + 2 * (hi - lo) / 3\n if(cost(md1) > cost(md2)) lo = md1\n else hi = md2\n }\n\n var ans = Long.MaxValue\n lo to hi foreach { i =>\n ans = Math.min(cost(i), ans)\n }\n out.println(ans)\n }\n\n def cost(fh: Int): Long = {\n var req = 0\n var extra = 0\n REP(n) { i =>\n if(fh > h(i)) req += (fh - h(i))\n else if (fh < h(i)) extra += (h(i) - fh)\n }\n val x = Math.min(req, extra).toLong\n x * Math.min(m, a+r) + (req - x) * a + (extra - x) * r\n }\n\n var n: Int = _\n var a: Int = _\n var r: Int = _\n var m: Int = _\n var h: Array[Int] = _\n}\n"}], "src_uid": "c9c65223b8575676647fe943f8dff25a"} {"nl": {"description": "Theater stage is a rectangular field of size n\u2009\u00d7\u2009m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above)\u00a0\u2014 left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold: there is no actor in the cell the spotlight is placed to; there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.", "input_spec": "The first line contains two positive integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the number of rows and the number of columns in the plan. The next n lines contain m integers, 0 or 1 each\u00a0\u2014 the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.", "output_spec": "Print one integer\u00a0\u2014 the number of good positions for placing the spotlight.", "sample_inputs": ["2 4\n0 1 0 0\n1 0 1 0", "4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0"], "sample_outputs": ["9", "20"], "notes": "NoteIn the first example the following positions are good: the (1, 1) cell and right direction; the (1, 1) cell and down direction; the (1, 3) cell and left direction; the (1, 3) cell and down direction; the (1, 4) cell and left direction; the (2, 2) cell and left direction; the (2, 2) cell and up direction; the (2, 2) and right direction; the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example."}, "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 lines = in.take(n).map(_.split(' ').map(_.toInt)).toArray\n val rightToLeft = lines.map{line =>\n if (line.contains(1)) {\n m - 2 * line.count(_ == 1) + (line.lastIndexOf(1) - line.indexOf(1) + 1)\n }\n else 0\n }.sum\n val vertical = lines.transpose.map{line =>\n if (line.contains(1)) {\n n - 2 * line.count(_ == 1) + (line.lastIndexOf(1) - line.indexOf(1) + 1)\n }\n else 0\n }.sum\n\n println(rightToLeft + vertical)\n\n\n}\n"}], "negative_code": [], "src_uid": "c3a7d82f6c3cf8678a1c7c521e0a5f51"} {"nl": {"description": "Dreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from $$$1$$$ to $$$54$$$ after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in $$$n$$$ Codeforces rounds. His place in the first round is $$$a_1$$$, his place in the second round is $$$a_2$$$, ..., his place in the $$$n$$$-th round is $$$a_n$$$.You are given a positive non-zero integer $$$x$$$.Please, find the largest $$$v$$$ such that this person can collect all the places from $$$1$$$ to $$$v$$$ after $$$x$$$ more rated contests.In other words, you need to find the largest $$$v$$$, such that it is possible, that after $$$x$$$ more rated contests, for each $$$1 \\leq i \\leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.For example, if $$$n=6$$$, $$$x=2$$$ and $$$a=[3,1,1,5,7,10]$$$ then answer is $$$v=5$$$, because if on the next two contest he will take places $$$2$$$ and $$$4$$$, then he will collect all places from $$$1$$$ to $$$5$$$, so it is possible to get $$$v=5$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains two integers $$$n, x$$$ ($$$1 \\leq n, x \\leq 100$$$). The second line contains $$$n$$$ positive non-zero integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 100$$$).", "output_spec": "For each test case print one line containing the largest $$$v$$$, such that it is possible that after $$$x$$$ other contests, for each $$$1 \\leq i \\leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.", "sample_inputs": ["5\n6 2\n3 1 1 5 7 10\n1 100\n100\n11 1\n1 1 1 1 1 1 1 1 1 1 1\n1 1\n1\n4 57\n80 60 40 20"], "sample_outputs": ["5\n101\n2\n2\n60"], "notes": "NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place $$$1,2,\\ldots,99$$$ and place $$$101$$$ on them in some order, to collect places $$$1,2,\\ldots,101$$$."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.Vasya has a train lighting schedule for all n hours of the trip \u2014 n numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose k hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.", "input_spec": "The first input line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of hours on the train and the number of hours to read, correspondingly. The second line contains n space-separated integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009100), ai is the light level at the i-th hour.", "output_spec": "In the first output line print the minimum light level Vasya will read at. In the second line print k distinct space-separated integers b1,\u2009b2,\u2009...,\u2009bk, \u2014 the indexes of hours Vasya will read at (1\u2009\u2264\u2009bi\u2009\u2264\u2009n). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers bi in an arbitrary order.", "sample_inputs": ["5 3\n20 10 30 40 10", "6 5\n90 20 35 40 60 100"], "sample_outputs": ["20\n1 3 4", "35\n1 3 4 5 6"], "notes": "NoteIn the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20."}, "positive_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\" + res.map(_ + 1).mkString(\" \"))\n writer.close()\n}"}, {"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": "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}"}], "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"} {"nl": {"description": "Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: \"Is the unknown number divisible by number y?\".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.", "input_spec": "A single line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009103).", "output_spec": "Print the length of the sequence of questions k (0\u2009\u2264\u2009k\u2009\u2264\u2009n), followed by k numbers \u2014 the questions yi (1\u2009\u2264\u2009yi\u2009\u2264\u2009n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.", "sample_inputs": ["4", "6"], "sample_outputs": ["3\n2 4 3", "4\n2 4 3 5"], "notes": "NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter."}, "positive_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(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": "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": "\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": "//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 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 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}"}, {"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"} {"nl": {"description": "When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i\u2009+\u20091, then book number i\u2009+\u20092 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.", "input_spec": "The first line contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009t\u2009\u2264\u2009109) \u2014 the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104), where number ai shows the number of minutes that the boy needs to read the i-th book.", "output_spec": "Print a single integer \u2014 the maximum number of books Valera can read.", "sample_inputs": ["4 5\n3 1 2 1", "3 3\n2 2 3"], "sample_outputs": ["3", "1"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "You are given a non-empty string $$$s=s_1s_2\\dots s_n$$$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string \"one\" or at least one string \"two\" (or both at the same time) as a substring. In other words, Polycarp does not like the string $$$s$$$ if there is an integer $$$j$$$ ($$$1 \\le j \\le n-2$$$), that $$$s_{j}s_{j+1}s_{j+2}=$$$\"one\" or $$$s_{j}s_{j+1}s_{j+2}=$$$\"two\".For example: Polycarp does not like strings \"oneee\", \"ontwow\", \"twone\" and \"oneonetwo\" (they all have at least one substring \"one\" or \"two\"), Polycarp likes strings \"oonnee\", \"twwwo\" and \"twnoe\" (they have no substrings \"one\" and \"two\"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like $$$s=$$$\"onetwone\", then if Polycarp selects two indices $$$3$$$ and $$$6$$$, then \"onetwone\" will be selected and the result is \"ontwne\".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Next, the test cases are given. Each test case consists of one non-empty string $$$s$$$. Its length does not exceed $$$1.5\\cdot10^5$$$. The string $$$s$$$ consists only of lowercase Latin letters. It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed $$$1.5\\cdot10^6$$$.", "output_spec": "Print an answer for each test case in the input in order of their appearance. The first line of each answer should contain $$$r$$$ ($$$0 \\le r \\le |s|$$$) \u2014 the required minimum number of positions to be removed, where $$$|s|$$$ is the length of the given line. The second line of each answer should contain $$$r$$$ different integers \u2014 the indices themselves for removal in any order. Indices are numbered from left to right from $$$1$$$ to the length of the string. If $$$r=0$$$, then the second line can be skipped (or you can print empty). If there are several answers, print any of them.", "sample_inputs": ["4\nonetwone\ntestme\noneoneone\ntwotwo", "10\nonetwonetwooneooonetwooo\ntwo\none\ntwooooo\nttttwo\nttwwoo\nooone\nonnne\noneeeee\noneeeeeeetwooooo"], "sample_outputs": ["2\n6 3\n0\n\n3\n4 1 7 \n2\n1 4", "6\n18 11 12 1 6 21 \n1\n1 \n1\n3 \n1\n2 \n1\n6 \n0\n\n1\n4 \n0\n\n1\n1 \n2\n1 11"], "notes": "NoteIn the first example, answers are: \"onetwone\", \"testme\" \u2014 Polycarp likes it, there is nothing to remove, \"oneoneone\", \"twotwo\". In the second example, answers are: \"onetwonetwooneooonetwooo\", \"two\", \"one\", \"twooooo\", \"ttttwo\", \"ttwwoo\" \u2014 Polycarp likes it, there is nothing to remove, \"ooone\", \"onnne\" \u2014 Polycarp likes it, there is nothing to remove, \"oneeeee\", \"oneeeeeeetwooooo\". "}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1,\u20092,\u20092,\u20092,\u20091,\u20092] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: the first monster can't eat the second monster because a1\u2009=\u20091 is not greater than a2\u2009=\u20092; the second monster can't eat the third monster because a2\u2009=\u20092 is not greater than a3\u2009=\u20092; the second monster can't eat the fifth monster because they are not neighbors; the second monster can eat the first monster, the queue will be transformed to [3,\u20092,\u20092,\u20091,\u20092]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k\u2009\u2264\u2009n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500)\u00a0\u2014 the number of monsters in the initial queue. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the initial weights of the monsters. The third line contains single integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of monsters in the queue after the joke. The fourth line contains k integers b1,\u2009b2,\u2009...,\u2009bk (1\u2009\u2264\u2009bj\u2009\u2264\u20095\u00b7108)\u00a0\u2014 the weights of the monsters after the joke. Monsters are listed in the order from the beginning of the queue to the end.", "output_spec": "In case if no actions could lead to the final queue, print \"NO\" (without quotes) in the only line. Otherwise print \"YES\" (without quotes) in the first line. In the next n\u2009-\u2009k lines print actions in the chronological order. In each line print x\u00a0\u2014 the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again. When one monster eats another the queue decreases. If there are several answers, print any of them.", "sample_inputs": ["6\n1 2 2 2 1 2\n2\n5 5", "5\n1 2 3 4 5\n1\n15", "5\n1 1 1 3 3\n3\n2 1 6"], "sample_outputs": ["YES\n2 L\n1 R\n4 L\n3 L", "YES\n5 L\n4 L\n3 L\n2 L", "NO"], "notes": "NoteIn the first example, initially there were n\u2009=\u20096 monsters, their weights are [1,\u20092,\u20092,\u20092,\u20091,\u20092] (in order of queue from the first monster to the last monster). The final queue should be [5,\u20095]. The following sequence of eatings leads to the final queue: the second monster eats the monster to the left (i.e. the first monster), queue becomes [3,\u20092,\u20092,\u20091,\u20092]; the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5,\u20092,\u20091,\u20092]; the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5,\u20092,\u20093]; the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5,\u20095]. Note that for each step the output contains numbers of the monsters in their current order in the queue."}, "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"}, {"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"}], "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"} {"nl": {"description": "n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2,\u20093,\u2009...,\u2009n\u2009-\u20091 friends among those who stayed by the moment of their leaving, did the same.What is the maximum amount of people that could stay at the party in the end? ", "input_spec": "The first input line contains one number t \u2014 amount of tests (1\u2009\u2264\u2009t\u2009\u2264\u2009105). Each of the following t lines contains one integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "For each test output in a separate line one number \u2014 the maximum amount of people that could stay in the end.", "sample_inputs": ["1\n3"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"source_code": "object Party23B 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 t = in.nextInt()\n val strinbBuilder = new StringBuilder()\n\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n strinbBuilder.append(Math.max(n-2,0)).append(System.lineSeparator())\n }\n out.println(strinbBuilder.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}"}], "negative_code": [{"source_code": "object Party23B 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 t = in.nextInt()\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if((n+1)%4 == 0){\n out.println((n+1)/2-1)\n }else{\n out.println(((n/4)*4)/2)\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 = return next().toInt\n }\n}"}, {"source_code": "object Party23B 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 t = in.nextInt()\n val strinbBuilder = new StringBuilder()\n\n (1 to t).foreach{ _ =>\n val n = in.nextInt()\n if((n+1)%4 == 0){\n strinbBuilder.append((n+1)/2-1).append(System.lineSeparator())\n\n }else{\n strinbBuilder.append(((n/4)*4)/2).append(System.lineSeparator())\n }\n\n }\n out.println(strinbBuilder.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}"}], "src_uid": "f83c91c9e9252aba4736aa0bea82493b"} {"nl": {"description": "Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.", "input_spec": "First line contains two integer numbers, m and n (1\u2009\u2264\u2009m,\u2009n\u2009\u2264\u2009105). Second line contains description of the first cluster with m space separated integers, ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). Similarly, third line describes second cluster with n space separated integers, bi (1\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "Print one integer \u2014 minimal number of copy operations.", "sample_inputs": ["2 2\n2 6\n3 100", "2 3\n10 10\n1 1 1"], "sample_outputs": ["11", "6"], "notes": "NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2\u2009+\u20096\u2009+\u20093\u2009=\u200911 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2\u00b73\u2009=\u20096 copy operations."}, "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, m) = readInts(2)\n val as = readLongs(n)\n val bs = readLongs(m)\n val sumA = as.sum\n val sumB = bs.sum\n val maxA = as.max\n val maxB = bs.max\n \n var res = 0L\n if (maxA > maxB || (maxA == maxB && sumA > sumB)) {\n val maxIdx = as.indexOf(maxA) \n for (i <- as.indices) res += (if (i == maxIdx) sumB else (as(i) min sumB))\n } else {\n val maxIdx = bs.indexOf(maxB) \n for (i <- bs.indices) res += (if (i == maxIdx) sumA else (bs(i) min sumA))\n }\n\n println(res)\n}"}], "negative_code": [], "src_uid": "f56597c8c3d17d73b8ede2d81fe5cbe7"} {"nl": {"description": "An array $$$a_1, a_2, \\ldots, a_n$$$ is good if and only if for every subsegment $$$1 \\leq l \\leq r \\leq n$$$, the following holds: $$$a_l + a_{l + 1} + \\ldots + a_r = \\frac{1}{2}(a_l + a_r) \\cdot (r - l + 1)$$$. You are given an array of integers $$$a_1, a_2, \\ldots, a_n$$$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$): the number of test cases. Each of the next $$$t$$$ lines contains the description of a test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 70$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-100 \\leq a_i \\leq 100$$$): the initial array.", "output_spec": "For each test case, print one integer: the minimum number of elements that you need to replace to make the given array good.", "sample_inputs": ["5\n4\n1 2 3 4\n4\n1 1 2 2\n2\n0 -1\n6\n3 -2 4 -1 -4 0\n1\n-100"], "sample_outputs": ["0\n2\n0\n3\n0"], "notes": "NoteIn the first test case, the array is good already.In the second test case, one of the possible good arrays is $$$[1, 1, \\underline{1}, \\underline{1}]$$$ (replaced elements are underlined).In the third test case, the array is good already.In the fourth test case, one of the possible good arrays is $$$[\\underline{-2.5}, -2, \\underline{-1.5}, -1, \\underline{-0.5}, 0]$$$."}, "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 = 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"}, {"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"} {"nl": {"description": "Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2\u00b7n binary characters \"0\" or \"1\". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2\u00b7n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as s\u2009=\u2009s1s2... s2n. Similarly, let's represent Andrey's word as t\u2009=\u2009t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106). The second line contains string s \u2014 Yaroslav's word. The third line contains string t \u2014 Andrey's word. It is guaranteed that both words consist of 2\u00b7n characters \"0\" and \"1\".", "output_spec": "Print \"First\", if both players play optimally well and Yaroslav wins. If Andrey wins, print \"Second\" and if the game ends with a draw, print \"Draw\". Print the words without the quotes.", "sample_inputs": ["2\n0111\n0001", "3\n110110\n001001", "3\n111000\n000111", "4\n01010110\n00101101", "4\n01100000\n10010011"], "sample_outputs": ["First", "First", "Draw", "First", "Second"], "notes": null}, "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\nimport scala.util.Random\n\nobject CF293A {\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n val a, b = in()\n var c00, c01, c10, c11 = 0\n for (i <- 0 until a.length) {\n if (a(i) == '0') {\n if (b(i) == '0') {\n c00 += 1\n } else {\n c01 += 1\n }\n } else {\n if (b(i) == '0') {\n c10 += 1\n } else {\n c11 += 1\n }\n }\n }\n for (i <- 0 until n) {\n val d1 = if (c11 > 0) {\n c11 -= 1\n 1\n } else if (c10 > 0) {\n c10 -= 1\n 1\n } else if (c01 > 0) {\n c01 -= 1\n 0\n } else if (c00 > 0) {\n c00 -= 1\n 0\n } else {\n throw new AssertionError()\n }\n val d2 = if (c11 > 0) {\n c11 -= 1\n 1\n } else if (c01 > 0) {\n c01 -= 1\n 1\n } else if (c10 > 0) {\n c10 -= 1\n 0\n } else if (c00 > 0) {\n c00 -= 1\n 0\n } else {\n throw new AssertionError()\n }\n if (d1 != d2) {\n if (d1 > d2) {\n out.println(\"First\")\n } else {\n out.println(\"Second\")\n }\n return\n }\n }\n out.println(\"Draw\")\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 }, \"thread\", 64000000).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": "6f52388b652a900e63ec39406225392c"} {"nl": {"description": "You are given a permutation $$$p=[p_1, p_2, \\ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$. Let's call the number $$$m$$$ ($$$1 \\le m \\le n$$$) beautiful, if there exists two indices $$$l, r$$$ ($$$1 \\le l \\le r \\le n$$$), such that the numbers $$$[p_l, p_{l+1}, \\ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \\ldots, m$$$.For example, let $$$p = [4, 5, 1, 3, 2, 6]$$$. In this case, the numbers $$$1, 3, 5, 6$$$ are beautiful and $$$2, 4$$$ are not. It is because: if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$; if $$$l = 3$$$ and $$$r = 5$$$ we will have a permutation $$$[1, 3, 2]$$$ for $$$m = 3$$$; if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[4, 5, 1, 3, 2]$$$ for $$$m = 5$$$; if $$$l = 1$$$ and $$$r = 6$$$ we will have a permutation $$$[4, 5, 1, 3, 2, 6]$$$ for $$$m = 6$$$; it is impossible to take some $$$l$$$ and $$$r$$$, such that $$$[p_l, p_{l+1}, \\ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \\ldots, m$$$ for $$$m = 2$$$ and for $$$m = 4$$$. You are given a permutation $$$p=[p_1, p_2, \\ldots, p_n]$$$. For all $$$m$$$ ($$$1 \\le m \\le n$$$) determine if it is a beautiful number or not.", "input_spec": "The first line contains the only integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the given permutation $$$p$$$. The next line contains $$$n$$$ integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\le p_i \\le n$$$, all $$$p_i$$$ are different)\u00a0\u2014 the given permutation $$$p$$$. It is guaranteed, that the sum of $$$n$$$ from all test cases in the input doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ lines\u00a0\u2014 the answers to test cases in the order they are given in the input. The answer to a test case is the string of length $$$n$$$, there the $$$i$$$-th character is equal to $$$1$$$ if $$$i$$$ is a beautiful number and is equal to $$$0$$$ if $$$i$$$ is not a beautiful number.", "sample_inputs": ["3\n6\n4 5 1 3 2 6\n5\n5 3 1 2 4\n4\n1 4 3 2"], "sample_outputs": ["101011\n11111\n1001"], "notes": "NoteThe first test case is described in the problem statement.In the second test case all numbers from $$$1$$$ to $$$5$$$ are beautiful: if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$; if $$$l = 3$$$ and $$$r = 4$$$ we will have a permutation $$$[1, 2]$$$ for $$$m = 2$$$; if $$$l = 2$$$ and $$$r = 4$$$ we will have a permutation $$$[3, 1, 2]$$$ for $$$m = 3$$$; if $$$l = 2$$$ and $$$r = 5$$$ we will have a permutation $$$[3, 1, 2, 4]$$$ for $$$m = 4$$$; if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[5, 3, 1, 2, 4]$$$ for $$$m = 5$$$. "}, "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"}, {"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"}], "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"} {"nl": {"description": "Polycarp's workday lasts exactly $$$n$$$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $$$k$$$ bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $$$k$$$ is strictly greater than $$$1$$$.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute $$$x$$$ and the next bar in the minute $$$y$$$ ($$$x < y$$$). Then the break time is equal to $$$y - x - 1$$$ minutes. It is not necessary for Polycarp to eat all bars he has.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 200\\,000$$$, $$$2 \\le k \\le n$$$) \u2014 the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday. The second line contains the string with length $$$n$$$ consisting of zeros and ones. If the $$$i$$$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $$$i$$$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $$$i$$$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.", "output_spec": "Print the minimum possible break in minutes between eating chocolate bars.", "sample_inputs": ["3 3\n010", "8 3\n01010110"], "sample_outputs": ["1", "3"], "notes": "NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes $$$1$$$ and $$$8$$$ anyway, also he needs to eat the chocolate bar in the minute $$$5$$$, so that the time of the maximum break will be equal to $$$3$$$ minutes."}, "positive_code": [{"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"} {"nl": {"description": "This problem is same as the previous one, but has larger constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \\ldots, u_n$$$ ($$$1 \\leq u_i \\leq 10^5$$$)\u00a0\u2014 the colors of the ribbons the cats wear. ", "output_spec": "Print a single integer $$$x$$$\u00a0\u2014 the largest possible streak of days.", "sample_inputs": ["13\n1 1 1 2 2 2 3 3 3 4 4 4 5", "5\n10 100 20 200 1", "1\n100000", "7\n3 2 1 1 4 5 1", "6\n1 1 1 2 2 2"], "sample_outputs": ["13", "5", "1", "6", "5"], "notes": "NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u6700\u5927\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\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}"}, {"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": "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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u6700\u5927\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u6700\u5927\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u6700\u5927\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\n if (D(mx) == 1 && D.contains(mx - 1)) {\n ans = i + 1\n // 1\u3092\u4e00\u3064\u6e1b\u3089\u305b\u3070\u3044\u3044\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"} {"nl": {"description": "You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, \"cotst\" is a subsequence of \"contest\".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.", "input_spec": "First line contains a string A (1\u2009\u2264\u2009|A|\u2009\u2264\u2009103) consisting of lowercase Latin letters, where |A| is a length of A.", "output_spec": "Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.", "sample_inputs": ["aba", "ab"], "sample_outputs": ["aba", "aabaa"], "notes": "NoteIn the first example, \"aba\" is a subsequence of \"aba\" which is a palindrome.In the second example, \"ab\" is a subsequence of \"aabaa\" which is a palindrome."}, "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\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"}, {"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"} {"nl": {"description": "We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.Polycarpus was given an important task \u2014 check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows: Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected). Count the number of connected components in the graph that is defining the computer network at that moment. Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network). Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.", "input_spec": "The first line contains two space-separated integers n, m (2\u2009\u2264\u2009n\u2009\u2264\u2009500;\u00a01\u2009\u2264\u2009m\u2009\u2264\u2009104) \u2014 the number of computers and the number of cables, correspondingly. The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n;\u00a0xi\u2009\u2260\u2009yi) \u2014 the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables. The next line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20092\u00b7104) \u2014 the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009m) \u2014 the numbers of the cables that Polycarpus disconnects during the i-th experiment. ", "output_spec": "Print k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment. ", "sample_inputs": ["6 5\n1 2\n5 4\n2 3\n3 1\n3 6\n6\n1 3\n2 5\n1 5\n5 5\n2 4\n3 3"], "sample_outputs": ["4\n5\n6\n3\n4\n2"], "notes": null}, "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\nimport scala.collection.mutable.ArrayBuffer\n\nobject CF292D {\n\n class DJU(n: Int) {\n val p = Array.tabulate(n)(identity)\n val r = Array.fill(n)(0)\n\n def get(i: Int): Int = {\n if (p(i) == i) {\n i\n } else {\n p(i) = get(p(i))\n p(i)\n }\n }\n\n def join(i: Int, j: Int): Boolean = {\n val u = get(i)\n val v = get(j)\n if (u == v) {\n false\n } else {\n if (r(u) < r(v)) {\n p(u) = v\n } else {\n p(v) = u\n }\n if (r(u) == r(v)) {\n r(u) += 1\n }\n true\n }\n }\n\n def reset() {\n for (i <- 0 until n) {\n p(i) = i\n r(i) = 0\n }\n }\n }\n\n def solve(in: In, out: PrintWriter) {\n val n, m = in().toInt\n val x, y = Array.ofDim[Int](m)\n for (i <- 0 until m) {\n x(i) = in().toInt - 1\n y(i) = in().toInt - 1\n }\n val left_, right_ = ArrayBuffer.empty[Int]\n val d = new DJU(n)\n for (i <- 0 until m) {\n if (d.join(x(i), y(i))) {\n left_ += i\n }\n }\n d.reset()\n for (i <- m - 1 to (0, -1)) {\n if (d.join(x(i), y(i))) {\n right_ += i\n }\n }\n val left = left_.toArray\n val right = right_.toArray\n val k = in().toInt\n for (it <- 0 until k) {\n val l, r = in().toInt - 1\n d.reset()\n var ans = n\n var it = 0\n while (it < left.length && left(it) < l) {\n val i = left(it)\n it += 1\n if (d.join(x(i), y(i))) {\n ans -= 1\n }\n }\n it = 0\n while (it < left.length && right(it) > r) {\n val i = right(it)\n it += 1\n if (d.join(x(i), y(i))) {\n ans -= 1\n }\n }\n out.println(ans)\n }\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 }, \"thread\", 64000000).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": [{"source_code": "import io.Source\nimport java.io.PrintWriter\nimport scala.collection.mutable.ArrayBuffer\n\nobject CF292D {\n\n class DJU(n: Int) {\n val p = Array.tabulate(n)(identity)\n val r = Array.fill(n)(0)\n\n def get(i: Int): Int = {\n if (p(i) == i) {\n i\n } else {\n p(i) = get(p(i))\n p(i)\n }\n }\n\n def join(i: Int, j: Int): Boolean = {\n val u = get(i)\n val v = get(j)\n if (u == v) {\n false\n } else {\n if (r(u) < r(v)) {\n p(u) = v\n } else {\n p(v) = u\n }\n if (r(u) == r(v)) {\n r(u) += 1\n }\n true\n }\n }\n\n def reset() {\n for (i <- 0 until n) {\n p(i) = i\n r(i) = 0\n }\n }\n }\n\n def solve(in: In, out: PrintWriter) {\n val n, m = in().toInt\n val x, y = Array.ofDim[Int](m)\n for (i <- 0 until m) {\n x(i) = in().toInt - 1\n y(i) = in().toInt - 1\n }\n val left_, right_ = ArrayBuffer.empty[Int]\n val d = new DJU(n)\n for (i <- 0 until m) {\n if (d.join(x(i), y(i))) {\n left_ += i\n }\n }\n d.reset()\n for (i <- m - 1 to (0, -1)) {\n if (d.join(x(i), y(i))) {\n right_ += i\n }\n }\n val left = left_.toArray\n val right = right_.toArray\n val k = in().toInt\n for (it <- 0 until k) {\n val l, r = in().toInt - 1\n d.reset()\n var ans = n\n var it = 0\n while (it < left.length && left(it) < l) {\n val i = left(it)\n it += 1\n if (d.join(x(i), y(i))) {\n ans -= 1\n }\n }\n it = 0\n while (it < left.length && left(it) < l) {\n val i = right(it)\n it += 1\n if (d.join(x(i), y(i))) {\n ans -= 1\n }\n }\n out.println(ans)\n }\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 }, \"thread\", 64000000).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}"}], "src_uid": "357e4fe985e9eb0c10b9b363fce79ae7"} {"nl": {"description": "Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?", "input_spec": "The first line contains the only integer n (0\u2009\u2264\u2009n\u2009\u2264\u200910100000). It is guaranteed that n doesn't contain any leading zeroes.", "output_spec": "Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.", "sample_inputs": ["0", "10", "991"], "sample_outputs": ["0", "1", "3"], "notes": "NoteIn the first sample the number already is one-digit \u2014 Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991\u2009\u2192\u200919\u2009\u2192\u200910\u2009\u2192\u20091. After three transformations the number becomes one-digit."}, "positive_code": [{"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}"}, {"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}"}, {"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}"}], "negative_code": [], "src_uid": "ddc9201725e30297a5fc83f4eed75fc9"} {"nl": {"description": "You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \\neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \\dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ \u2014 a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \\dots, v_r$$$.", "input_spec": "The first line contains the single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of test cases. Next $$$T$$$ lines contain test cases \u2014 one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \\le n \\le 10^5$$$, $$$1 \\le l \\le r \\le n(n - 1) + 1$$$, $$$r - l + 1 \\le 10^5$$$) \u2014 the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print the segment $$$v_l, v_{l + 1}, \\dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.", "sample_inputs": ["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"], "sample_outputs": ["1 2 1 \n1 3 2 3 \n1"], "notes": "NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$."}, "positive_code": [{"source_code": "object D 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 Array(n, l, r) = readLine().split(\" \").map(_.toLong)\n\n def collect: Unit = {\n @tailrec\n def go(i: Int = 1, p: Long = 0L): Unit =\n (p, p + 2 * (n - i)) match {\n case (p, q) if i > n || p >= r => println()\n case _ if i == n => println(1)\n case (_, q) if q < l => go(i + 1, q)\n case (p, q) =>\n lazy val stream: Stream[Int] = i #:: (i + 1) #:: stream.zip(stream.tail).map {\n case (j, _) if j == i => i\n case (j, _) => j + 1\n }\n\n stream\n .drop(0 max (l - p - 1).toInt)\n .take((r.min(q) - p.max(l - 1)).toInt)\n .foreach(j => print(s\"$j \"))\n\n go(i + 1, q)\n }\n\n go()\n }\n\n collect\n }\n}\n"}], "negative_code": [{"source_code": "object D 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 Array(n, l, r) = readLine().split(\" \").map(_.toLong)\n\n def collect: Unit = {\n @tailrec\n def go(i: Int = 1, p: Long = 0L): Unit =\n (p, p + 2 * (n - i)) match {\n case (p, q) if i > n || p >= r => ()\n case _ if i == n => print(1)\n case (_, q) if q < l => go(i + 1, q)\n case (p, q) =>\n lazy val stream: Stream[Int] = i #:: (i + 1) #:: stream.zip(stream.tail).map {\n case (j, _) if j == i => i\n case (j, _) => j + 1\n }\n\n stream\n .drop(0 max (l - p - 1).toInt)\n .take((r.min(q) - p.max(l - 1)).toInt)\n .foreach(j => print(s\"$j \"))\n\n go(i + 1, q)\n }\n\n go()\n }\n\n collect\n }\n}\n"}], "src_uid": "afb43928545743b497b1a9975768f8e5"} {"nl": {"description": "Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version \u2014 positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.More formal, choose such a set of projects of minimum possible size that the following conditions hold: Polycarp's project is chosen; Polycarp's project depends (directly or indirectly) on all other projects in the set; no two projects share the name; for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.", "input_spec": "The first line contains an only integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000) \u2014 the number of projects in Vaja. The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n\u2009-\u20091) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding. It's guaranteed that there are no cyclic dependencies. ", "output_spec": "Output all Polycarp's project's dependencies in lexicographical order.", "sample_inputs": ["4\na 3\n2\nb 1\nc 1\n\u00a0\nb 2\n0\n\u00a0\nb 1\n1\nb 2\n\u00a0\nc 1\n1\nb 2", "9\ncodehorses 5\n3\nwebfrmk 6\nmashadb 1\nmashadb 2\n\u00a0\ncommons 2\n0\n\u00a0\nmashadb 3\n0\n\u00a0\nwebfrmk 6\n2\nmashadb 3\ncommons 2\n\u00a0\nextra 4\n1\nextra 3\n\u00a0\nextra 3\n0\n\u00a0\nextra 1\n0\n\u00a0\nmashadb 1\n1\nextra 3\n\u00a0\nmashadb 2\n1\nextra 1", "3\nabc 1\n2\nabc 3\ncba 2\n\nabc 3\n0\n\ncba 2\n0"], "sample_outputs": ["2\nb 1\nc 1", "4\ncommons 2\nextra 1\nmashadb 2\nwebfrmk 6", "1\ncba 2"], "notes": "NoteThe first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project \u00aba\u00bb (version 3) depends on are painted black. The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project \u00abcodehorses\u00bb (version 5) depends on are paint it black. Note that \u00abextra 1\u00bb is chosen instead of \u00abextra 3\u00bb since \u00abmashadb 1\u00bb and all of its dependencies are ignored due to \u00abmashadb 2\u00bb. "}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\n\nobject C {\n type Proj = (String, Int)\n\n def main(args: Array[String]): Unit = {\n val sc = new java.util.Scanner(System.in)\n val projects: mutable.Map[Proj, Seq[Proj]] = mutable.Map()\n val n = sc.nextInt\n val myProject = readProject(sc)\n val myDeps = readDependencies(sc)\n for (_ <- 1 until n) {\n projects += (readProject(sc) -> readDependencies(sc))\n }\n\n val result: ArrayBuffer[Proj] = ArrayBuffer()\n addDeps(myDeps)\n println(result.size)\n result.sortBy(_._1).foreach(t => println(s\"${t._1} ${t._2}\"))\n\n def addDeps(deps: Seq[Proj]): Unit = {\n val goodDeps: mutable.Map[String, Int] = mutable.Map()\n for {\n dep <- deps\n if myProject._1 != dep._1\n if !result.exists(_._1 == dep._1)\n if !goodDeps.contains(dep._1) || goodDeps(dep._1) < dep._2\n } {\n goodDeps += dep\n }\n val seq = goodDeps.toSeq\n if (seq.nonEmpty) {\n result ++= seq\n addDeps(seq.flatMap(projects))\n }\n }\n }\n\n def readProject(sc: java.util.Scanner): Proj = (sc.next(\"\\\\S+\"), sc.nextInt)\n\n def readDependencies(sc: java.util.Scanner): Seq[Proj] =\n for {\n _ <- 1 to sc.nextInt\n } yield readProject(sc)\n}\n"}], "negative_code": [], "src_uid": "8e79a1de43e055cf81d7b30d6090b7ff"} {"nl": {"description": "As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n\u2009-\u20091 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The \u00abTwo Paths\u00bb company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the \u00abTwo Paths\u00bb company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200), where n is the amount of cities in the country. The following n\u2009-\u20091 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n).", "output_spec": "Output the maximum possible profit.", "sample_inputs": ["4\n1 2\n2 3\n3 4", "7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7", "6\n1 2\n2 3\n2 4\n5 4\n6 4"], "sample_outputs": ["1", "0", "4"], "notes": null}, "positive_code": [{"source_code": "import java.util\nimport 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 java.lang.Integer.parseInt(next)\n }\n\n def nextLong: Long = {\n return java.lang.Long.parseLong(next)\n }\n\n def addEdge(edge: (Int, Int), graph: Array[List[Int]]): Array[List[Int]] = {\n graph(edge._1).add(edge._2)\n graph(edge._2).add(edge._1)\n return graph\n }\n\n def solve = {\n val n = nextInt\n val edges = new Array[(Int, Int)](n - 1)\n var graph = new Array[List[Int]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayList[Int]()\n }\n for (i <- 0 until n - 1) {\n edges(i) = (nextInt - 1, nextInt - 1)\n graph = addEdge(edges(i), graph)\n }\n var ans = Int.MinValue\n for (i <- 0 until n - 1) {\n val first = edges(i)._1\n val second = edges(i)._2\n val used = new Array[Boolean](n)\n val dist = new Array[Int](n)\n\n object Helper {\n def bfs(start: Int) = {\n val q: util.Queue[Int] = new util.LinkedList[Int]()\n q.add(start)\n dist(start) = 0\n while (!q.isEmpty) {\n val v = q.poll()\n used(v) = true\n for (i <- 0 until graph(v).size()) {\n val next: Int = graph(v).get(i)\n if (!used(next)) {\n dist(next) = dist(v) + 1\n q.add(next)\n }\n }\n }\n }\n\n def cleanUpWith(vert: Int) = {\n Arrays.fill(used, false)\n Arrays.fill(dist, -1)\n used(vert) = true\n }\n }\n\n var firstDiameter = 0\n Helper.cleanUpWith(first)\n Helper.bfs(second)\n val max1 = dist.zipWithIndex.max\n Helper.cleanUpWith(first)\n Helper.bfs(max1._2)\n firstDiameter = dist.max\n\n var secondDiameter = 0\n Helper.cleanUpWith(second)\n Helper.bfs(first)\n val max2 = dist.zipWithIndex.max\n Helper.cleanUpWith(second)\n Helper.bfs(max2._2)\n secondDiameter = dist.max\n\n ans = Math.max(ans, firstDiameter * secondDiameter)\n }\n out.println(ans)\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": "b07668a66a5e50659233ba055a893bd4"} {"nl": {"description": "Ashish has an array $$$a$$$ of size $$$n$$$.A subsequence of $$$a$$$ is defined as a sequence that can be obtained from $$$a$$$ by deleting some elements (possibly none), without changing the order of the remaining elements.Consider a subsequence $$$s$$$ of $$$a$$$. He defines the cost of $$$s$$$ as the minimum between: The maximum among all elements at odd indices of $$$s$$$. The maximum among all elements at even indices of $$$s$$$. Note that the index of an element is its index in $$$s$$$, rather than its index in $$$a$$$. The positions are numbered from $$$1$$$. So, the cost of $$$s$$$ is equal to $$$min(max(s_1, s_3, s_5, \\ldots), max(s_2, s_4, s_6, \\ldots))$$$.For example, the cost of $$$\\{7, 5, 6\\}$$$ is $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.Help him find the minimum cost of a subsequence of size $$$k$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\leq k \\leq n \\leq 2 \\cdot 10^5$$$) \u00a0\u2014 the size of the array $$$a$$$ and the size of the subsequence. The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "Output a single integer \u00a0\u2014 the minimum cost of a subsequence of size $$$k$$$.", "sample_inputs": ["4 2\n1 2 3 4", "4 3\n1 2 3 4", "5 3\n5 3 4 2 6", "6 4\n5 3 50 2 4 5"], "sample_outputs": ["1", "2", "2", "3"], "notes": "NoteIn the first test, consider the subsequence $$$s$$$ = $$$\\{1, 3\\}$$$. Here the cost is equal to $$$min(max(1), max(3)) = 1$$$.In the second test, consider the subsequence $$$s$$$ = $$$\\{1, 2, 4\\}$$$. Here the cost is equal to $$$min(max(1, 4), max(2)) = 2$$$.In the fourth test, consider the subsequence $$$s$$$ = $$$\\{3, 50, 2, 4\\}$$$. Here the cost is equal to $$$min(max(3, 2), max(50, 4)) = 3$$$."}, "positive_code": [{"source_code": "object D {\n\n import InOut._\n\n\n def main(args: Array[String]): Unit = {\n\n val n, k = nextInt\n val as = nextInts(n)\n\n def can2(limit: Long, isEven: Int): Boolean = {\n var i = 0\n var j = 0\n while (i < n && j < k) {\n if (as(i) > limit) {\n if (j % 2 == isEven) {\n j += 1\n }\n } else {\n j += 1\n }\n i += 1\n }\n j == k\n }\n\n def can(limit: Long): Boolean = {\n val c0 = can2(limit, 0)\n val c1 = can2(limit, 1)\n// println(limit, c0, c1)\n c0 || c1\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 = binSearch(0, as.max)\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\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": [], "src_uid": "d55ed15b600477e292406bef0b2d3b49"} {"nl": {"description": "Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \\ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \\leq i_1 < i_2 < \\ldots < i_k < m$$$ (possibly, empty), where $$$0 \\leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \\ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \\ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \\ldots, t$$$, or determine that he could have obtained this array without mistakes.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100\\,000$$$)\u00a0\u2014 the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the array Ildar obtained.", "output_spec": "If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \\ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$\u00a0\u2014 the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \\ldots, t$$$.", "sample_inputs": ["4\n0 1 2 1", "3\n1 0 1", "4\n0 1 2 239"], "sample_outputs": ["-1", "1", "4"], "notes": "NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed. $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$. $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$. $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$. $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong."}, "positive_code": [{"source_code": "object _1054B 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 a = io.read[Vector[Long]]\n val valid = mutable.Set.empty[Long]\n\n @tailrec\n def findInvalidIndex(i: Int, currMax: Long): Option[Int] = {\n if (i == a.length) {\n None\n } else if (valid.contains(a(i))) {\n findInvalidIndex(i + 1, currMax)\n } else if (a(i) == currMax + 1) {\n valid += a(i)\n findInvalidIndex(i + 1, currMax + 1)\n } else {\n Some(i + 1)\n }\n }\n\n io.write(findInvalidIndex(i = 0, currMax = -1).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}\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": "e17427897fd5147c601204cb1c48b143"} {"nl": {"description": "Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help\u00a0\u2014 print the sequence of indices of string $$$s$$$ on which he should jump.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \\le |s| \\le 2 \\cdot 10^5$$$), where $$$|s|$$$\u00a0\u2014 is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \\dots, j_m$$$ ($$$1 \\le j_i \\le |s|$$$)\u00a0\u2014 the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.", "sample_inputs": ["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"], "sample_outputs": ["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"], "notes": "NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$."}, "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 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"}, {"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"} {"nl": {"description": "After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.", "input_spec": "The first line contains two integers hh and mm (00\u2009\u2264\u2009hh\u2009\u2264\u200923,\u200900\u2009\u2264\u2009mm\u2009\u2264\u200959) \u2014 the time of Andrew's awakening. The second line contains four integers H, D, C and N (1\u2009\u2264\u2009H\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009D,\u2009C,\u2009N\u2009\u2264\u2009102).", "output_spec": "Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10\u2009-\u20094. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .", "sample_inputs": ["19 00\n255 1 100 1", "17 41\n1000 6 15 11"], "sample_outputs": ["25200.0000", "1365.0000"], "notes": "NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles."}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(hh, mm) = readInt()\n val Array(h, d, c, n) = readInt().map(_.toFloat)\n\n var price = 0.0\n if (hh >= 20) price = Math.ceil(h / n) * c * 0.8\n else price = Math.min(Math.ceil(h / n) * c, Math.ceil((h + ((20 - hh - 1)*60 + 60 - mm)*d) / n) * c * 0.8)\n\n print(\"%.4f\".format(price))\n\n /*val s = readString()\n val s1 = new mutable.HashSet[Char]()\n val s2 = new mutable.HashSet[Char]()\n val f1 = new Array[Int](s.length)\n val f2 = new Array[Int](s.length)\n\n for (i <- 0 until s.length) {\n s1 += s(i)\n f1(i) = s1.size\n }\n\n for (i <- s.length - 1 to 0 by -1) {\n s2 += s(i)\n f2(i) = s2.size\n }\n\n for (i <- 0 until s.length - 1)\n if (f1(i) == f2(i + 1) && f1(i) == 2) {\n print(\"Yes\")\n return\n }\n print(\"No\")*/\n\n/* val prime = Array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59)\n\n var Array(q) = readInt()\n while (q > 0) {\n var Array(l, r) = readInt()\n var result = 0\n if (l == 1) {\n l = 2\n result += 1\n }\n val maxb = (Math.log(r)/Math.log(2)).toInt\n for (i <- 2 to maxb if (prime.contains(i))) {\n var mina = Math.max(Math.pow(l, 1.0/i).ceil.toInt, 2)\n val maxa = Math.pow(r, 1.0/i).floor.toInt\n println(s\"$i $mina $maxa ${maxa - mina + 1}\")\n result += maxa - mina + 1\n }\n\n println(result)\n q -= 1\n }*/\n }\n}\n"}], "negative_code": [{"source_code": "object objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(hh, mm) = readInt()\n val Array(h, d, c, n) = readInt().map(_.toFloat)\n\n var price = 0.0\n if (hh >= 20) price = Math.ceil(h / n) * c\n else price = Math.min(Math.ceil(h / n) * c, Math.ceil((h + ((20 - hh - 1)*60 + 60 - mm))*d / n) * c)\n\n print(\"%.4f\".format(price))\n }\n}\n"}, {"source_code": "import scala.collection.mutable\n\nobject objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(hh, mm) = readInt()\n val Array(h, d, c, n) = readInt().map(_.toFloat)\n\n var price = 0.0\n if (hh >= 20) price = Math.ceil(h / n) * c * 0.8\n else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)\n\n print(\"%.4f\".format(price))\n\n /*val s = readString()\n val s1 = new mutable.HashSet[Char]()\n val s2 = new mutable.HashSet[Char]()\n val f1 = new Array[Int](s.length)\n val f2 = new Array[Int](s.length)\n\n for (i <- 0 until s.length) {\n s1 += s(i)\n f1(i) = s1.size\n }\n\n for (i <- s.length - 1 to 0 by -1) {\n s2 += s(i)\n f2(i) = s2.size\n }\n\n for (i <- 0 until s.length - 1)\n if (f1(i) == f2(i + 1) && f1(i) == 2) {\n print(\"Yes\")\n return\n }\n print(\"No\")*/\n\n/* val prime = Array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59)\n\n var Array(q) = readInt()\n while (q > 0) {\n var Array(l, r) = readInt()\n var result = 0\n if (l == 1) {\n l = 2\n result += 1\n }\n val maxb = (Math.log(r)/Math.log(2)).toInt\n for (i <- 2 to maxb if (prime.contains(i))) {\n var mina = Math.max(Math.pow(l, 1.0/i).ceil.toInt, 2)\n val maxa = Math.pow(r, 1.0/i).floor.toInt\n println(s\"$i $mina $maxa ${maxa - mina + 1}\")\n result += maxa - mina + 1\n }\n\n println(result)\n q -= 1\n }*/\n }\n}\n"}, {"source_code": "object objecta {\n import java.io.{BufferedReader, FileInputStream, InputStreamReader}\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 def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(\" \").map(_.toInt)\n def readString()(implicit reader: BufferedReader): String = reader.readLine()\n\n def main(args: Array[String]): Unit = {\n val Array(hh, mm) = readInt()\n val Array(h, d, c, n) = readInt().map(_.toFloat)\n\n var price = 0.0\n if (hh >= 20) price = Math.ceil(h / n) * c * 0.8\n else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)\n\n print(\"%.4f\".format(price))\n }\n}\n"}], "src_uid": "937acacc6d5d12d45c08047dde36dcf0"} {"nl": {"description": "You are given a positive integer $$$n$$$ greater or equal to $$$2$$$. For every pair of integers $$$a$$$ and $$$b$$$ ($$$2 \\le |a|, |b| \\le n$$$), you can transform $$$a$$$ into $$$b$$$ if and only if there exists an integer $$$x$$$ such that $$$1 < |x|$$$ and ($$$a \\cdot x = b$$$ or $$$b \\cdot x = a$$$), where $$$|x|$$$ denotes the absolute value of $$$x$$$.After such a transformation, your score increases by $$$|x|$$$ points and you are not allowed to transform $$$a$$$ into $$$b$$$ nor $$$b$$$ into $$$a$$$ anymore.Initially, you have a score of $$$0$$$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?", "input_spec": "A single line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100\\,000$$$)\u00a0\u2014 the given integer described above.", "output_spec": "Print an only integer\u00a0\u2014 the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print $$$0$$$.", "sample_inputs": ["4", "6", "2"], "sample_outputs": ["8", "28", "0"], "notes": "NoteIn the first example, the transformations are $$$2 \\rightarrow 4 \\rightarrow (-2) \\rightarrow (-4) \\rightarrow 2$$$.In the third example, it is impossible to perform even a single transformation."}, "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\n var ans = 0L\n 2 until N foreach { d =>\n 2 to N / d foreach { x =>\n ans += x * 4\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}"}], "negative_code": [], "src_uid": "03907ca0d34a2c80942ed3968b2c067d"} {"nl": {"description": "As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.Elections are coming. You know the number of voters and the number of parties\u00a0\u2014 $$$n$$$ and $$$m$$$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $$$i$$$-th voter $$$c_i$$$ bytecoins you can ask him to vote for any other party you choose.The United Party of Berland has decided to perform a statistical study\u00a0\u2014 you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 3000$$$)\u00a0\u2014 the number of voters and the number of parties respectively. Each of the following $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \\le p_i \\le m$$$, $$$1 \\le c_i \\le 10^9$$$)\u00a0\u2014 the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision. The United Party of Berland has the index $$$1$$$.", "output_spec": "Print a single number\u00a0\u2014 the minimum number of bytecoins needed for The United Party of Berland to win the elections.", "sample_inputs": ["1 2\n1 100", "5 5\n2 100\n3 200\n4 300\n5 400\n5 900", "5 5\n2 100\n3 200\n4 300\n5 800\n5 900"], "sample_outputs": ["0", "500", "600"], "notes": "NoteIn the first sample, The United Party wins the elections even without buying extra votes.In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $$$3$$$, $$$4$$$ and $$$5$$$ get one vote and party number $$$2$$$ gets no votes.In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party."}, "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.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}"}, {"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"} {"nl": {"description": "There is a $$$n \\times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can: move right to the cell $$$(x, y + 1)$$$\u00a0\u2014 it costs $$$x$$$ burles; move down to the cell $$$(x + 1, y)$$$\u00a0\u2014 it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?", "input_spec": "The first line contains the single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \\le n, m \\le 100$$$; $$$0 \\le k \\le 10^4$$$)\u00a0\u2014 the sizes of grid and the exact amount of money you need to spend.", "output_spec": "For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["6\n1 1 0\n2 2 2\n2 2 3\n2 2 4\n1 4 3\n100 100 10000"], "sample_outputs": ["YES\nNO\nYES\nNO\nYES\nNO"], "notes": "NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\\rightarrow$$$ $$$(1, 2)$$$ $$$\\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\\rightarrow$$$ $$$(2, 1)$$$ $$$\\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles."}, "positive_code": [{"source_code": "import scala.io.StdIn\r\nimport scala.math.min\r\nimport scala.math.max\r\n\r\nobject Main extends App {\r\n val t = StdIn.readInt()\r\n for (i <- 0 until t) {\r\n val values = StdIn.readLine().split(\" \").map(_.toInt)\r\n val n = min(values(0), values(1))\r\n val m = max(values(1), values(0))\r\n val t = values(2)\r\n\r\n println(if (n * m - 1 == t) \"YES\" else \"NO\")\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\r\nimport scala.math.min\r\nimport scala.math.max\r\n\r\nobject Main extends App {\r\n val t = StdIn.readInt()\r\n for (i <- 0 until t) {\r\n val values = StdIn.readLine().split(\" \").map(_.toInt)\r\n val n = min(values(0), values(1))\r\n val m = max(values(1), values(0))\r\n val t = values(2)\r\n\r\n println(if (n * (n - 1) + m - 1 == t) \"YES\" else \"NO\")\r\n }\r\n}\r\n"}], "src_uid": "8b0a9c7e997034d3ecce044b9f64aeba"} {"nl": {"description": "This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.", "input_spec": "The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 10^5)$$$\u00a0\u2014 the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$\u00a0\u2014 the prices of ice spheres.", "output_spec": "In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.", "sample_inputs": ["7\n1 3 2 2 4 5 4"], "sample_outputs": ["3\n3 1 4 2 4 2 5"], "notes": "NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each."}, "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject D2 {\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 val arr2 = new Array[Int](n)\n var trg = 1\n var src = 0\n while (trg < n) {\n arr2(trg) = arr(src)\n trg += 2\n src += 1\n }\n trg = 0\n while (trg < n) {\n arr2(trg) = arr(src)\n trg += 2\n src += 1\n }\n\n val result = (1 to n - 2).count(i => arr2(i) < arr2(i - 1) && arr2(i) < arr2(i + 1))\n out.println(result)\n out.println(arr2.mkString(\" \"))\n }\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"5\\n1 2 3 4 5\", \"2\\n3 1 4 2 5 \", \"Sample\"),\n (\"7\\n1 3 2 2 4 5 4\", \"3\\n3 1 4 2 4 2 5\", \"Sample 2\"),\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\\n3 1 4 2\", \"Size 4\"),\n (\"5\\n1 1 1 2 2\", \"1\\n1 1 2 1 2\", \"Size 5, v1\"),\n (\"5\\n1 1 2 2 2\", \"2\\n2 1 2 1 2\", \"Size 5, v2\"),\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": [], "src_uid": "6443dffb38285b6deb74f2371d8d0cac"} {"nl": {"description": "Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?There are $$$n$$$ stores numbered from $$$1$$$ to $$$n$$$ in Nlogonia. The $$$i$$$-th of these stores offers a positive integer $$$a_i$$$.Each day among the last $$$m$$$ days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.Dora considers Swiper to be her rival, and she considers that she beat Swiper on day $$$i$$$ if and only if the least common multiple of the numbers she bought on day $$$i$$$ is strictly greater than the least common multiple of the numbers that Swiper bought on day $$$i$$$.The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.However, Dora forgot the values of $$$a_i$$$. Help Dora find out if there are positive integer values of $$$a_i$$$ such that she beat Swiper on every day. You don't need to find what are the possible values of $$$a_i$$$ though.Note that it is possible for some values of $$$a_i$$$ to coincide in a solution.", "input_spec": "The first line contains integers $$$m$$$ and $$$n$$$ ($$$1\\leq m \\leq 50$$$, $$$1\\leq n \\leq 10^4$$$)\u00a0\u2014 the number of days and the number of stores. After this $$$m$$$ lines follow, the $$$i$$$-th line starts with an integer $$$s_i$$$ ($$$1\\leq s_i \\leq n-1$$$), the number of integers Dora bought on day $$$i$$$, followed by $$$s_i$$$ distinct integers, the indices of the stores where Dora bought an integer on the $$$i$$$-th day. The indices are between $$$1$$$ and $$$n$$$.", "output_spec": "Output must consist of a single line containing \"possible\" if there exist positive integers $$$a_i$$$ such that for each day the least common multiple of the integers bought by Dora is strictly greater than the least common multiple of the integers bought by Swiper on that day. Otherwise, print \"impossible\". Note that you don't have to restore the integers themselves.", "sample_inputs": ["2 5\n3 1 2 3\n3 3 4 5", "10 10\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10"], "sample_outputs": ["possible", "impossible"], "notes": "NoteIn the first sample, a possible choice for the values of the $$$a_i$$$ is $$$3, 4, 3, 5, 2$$$. On the first day, Dora buys the integers $$$3, 4$$$ and $$$3$$$, whose LCM is $$$12$$$, while Swiper buys integers $$$5$$$ and $$$2$$$, whose LCM is $$$10$$$. On the second day, Dora buys $$$3, 5$$$ and $$$2$$$, whose LCM is $$$30$$$, and Swiper buys integers $$$3$$$ and $$$4$$$, whose LCM is $$$12$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val M, N = ni()\n val sets = Array.fill[mutable.Set[Int]](N)(mutable.Set())\n REP(M) { i =>\n REP(ni()) { _ =>\n sets(i) += ni() - 1\n }\n }\n\n var ok = true\n REP(M) { i =>\n REP(M) { j =>\n if (i != j) {\n if (!sets(i).exists(sets(j).contains)) ok = false\n }\n }\n }\n\n if (ok) out.println(\"possible\")\n else out.println(\"impossible\")\n }\n}"}], "negative_code": [], "src_uid": "f217337f015224231e64a992329242e8"} {"nl": {"description": "Permutation p is an ordered set of integers p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn.You have a sequence of integers a1,\u2009a2,\u2009...,\u2009an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the size of the sought permutation. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single number \u2014 the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["2\n3 0", "3\n-1 -1 2"], "sample_outputs": ["2", "6"], "notes": "NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2,\u20091).In the second sample you need 6 moves to build permutation (1,\u20093,\u20092)."}, "positive_code": [{"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.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}"}, {"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\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}"}], "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 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) != 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"} {"nl": {"description": "You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase print a single integer\u00a0\u2014 the maximum number of moves you can perform on a given string $$$s$$$.", "sample_inputs": ["5\n()\n[]()\n([)]\n)]([\n)[(]"], "sample_outputs": ["1\n2\n2\n0\n1"], "notes": "NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: \"[]()\", then \"()\" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: \"([)]\". They form an RBS \"()\". Then \"[]\" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: \")[(]\" and get \")(\" as a result. You can erase nothing from it."}, "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"}, {"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"}], "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"} {"nl": {"description": "Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009105\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the elements of the array.", "output_spec": "Print a single integer \u2014 the minimum number of seconds needed to make all elements of the array equal to zero.", "sample_inputs": ["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"], "sample_outputs": ["1", "2", "4"], "notes": "NoteIn the first example you can add \u2009-\u20091 to all non-zero elements in one second and make them equal to zero.In the second example you can add \u2009-\u20092 on the first second, then the array becomes equal to [0,\u20090,\u2009\u2009-\u20093]. On the second second you can add 3 to the third (the only non-zero) element."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n\u2009-\u20091 edges and can be obtained by removing some of the edges from G.The degree of a vertex is the number of edges incident to this vertex.", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009min(400\u2009000,\u2009n\u00b7(n\u2009-\u20091)\u2009/\u20092))\u00a0\u2014 the number of vertices and the number of edges in the graph. The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, u\u2009\u2260\u2009v)\u00a0\u2014 the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers s, t, ds, dt (1\u2009\u2264\u2009s,\u2009t\u2009\u2264\u2009n, s\u2009\u2260\u2009t, 1\u2009\u2264\u2009ds,\u2009dt\u2009\u2264\u2009n\u2009-\u20091).", "output_spec": "If the answer doesn't exist print \"No\" (without quotes) in the only line of the output. Otherwise, in the first line print \"Yes\" (without quotes). In the each of the next (n\u2009-\u20091) lines print two integers \u2014 the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them.", "sample_inputs": ["3 3\n1 2\n2 3\n3 1\n1 2 1 1", "7 8\n7 4\n1 3\n5 4\n5 7\n3 2\n2 4\n6 1\n1 2\n6 4 1 4"], "sample_outputs": ["Yes\n3 2\n1 3", "Yes\n1 3\n5 7\n3 2\n7 4\n2 4\n6 1"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable._\n\nobject CF375_6B extends App {\n val nm = readLine.split(\" \").map(_.toInt)\n val va = new Array[Int](nm(1))\n val vb = new Array[Int](nm(1))\n for (i <- 0 until nm(1)) {\n val ab = readLine.split(\" \").map(_.toInt)\n va(i) = ab(0)\n vb(i) = ab(1)\n }\n val spl = readLine.split(\" \").map(_.toInt)\n val res = solve(nm(0), va, vb, spl(0), spl(1), spl(2), spl(3))\n if (res == null) {\n println(\"No\");\n } else {\n println(\"Yes\");\n for (ab <- res)\n println(ab._1 + \" \" + ab._2)\n }\n\n def solve(n: Int, va: Array[Int], vb: Array[Int], s: Int, t: Int, ds1: Int, dt1: Int): ArrayBuffer[(Int, Int)] = {\n val uf = new UF(n)\n val vs = new ArrayBuffer[Int]()\n val vt = new ArrayBuffer[Int]()\n var st_found = false\n val res = new ArrayBuffer[(Int, Int)]()\n \n for (i <- 0 until va.length) {\n val (a, b) = (va(i), vb(i))\n if (a == s || b == s) {\n if (a == t || b == t)\n st_found = true\n else\n vs += {if (a == s) b else a} \n } else if (a == t) \n vt += b \n else if (b == t)\n vt += a\n else {\n if (uf.unite(a, b)) {\n res += (a -> b)\n } \n }\n }\n \n val(rs, rt, rts) = getComp(vs, vt, uf)\n var ds = ds1 - rs.length\n var dt = dt1 - rt.length\n for (i <- rs)\n res += (s -> i)\n for (i <- rt) \n res += (t -> i)\n \n var f = 0\n if (st_found && rts.length == 0) {\n res += (s -> t) \n }\n else {\n res += (s -> rts(0)._1)\n res += (t -> rts(0)._2)\n f = 1\n }\n ds -= 1\n dt -= 1\n for (i <- f until rts.length) {\n if (ds > 0) {\n ds -= 1\n res += (s -> rts(i)._1)\n } else {\n dt -= 1\n res += (t -> rts(i)._2)\n }\n }\n \n return if (ds >= 0 && dt >= 0) res else null;\n }\n \n def toHashMap(v : ArrayBuffer[Int], uf : UF) = {\n var res = new HashMap[Int, Int]()\n for (i <- v) \n res += (uf.getRoot(i) -> i) \n res\n }\n \n def getComp(vs : ArrayBuffer[Int], vt : ArrayBuffer[Int], uf : UF) = {\n val hs = toHashMap(vs, uf)\n val ht = toHashMap(vt, uf) \n val rs = new ArrayBuffer[Int]()\n val rt = new ArrayBuffer[Int]()\n val rts = new ArrayBuffer[(Int, Int)]()\n \n for (kv <- hs) {\n if (ht.contains(kv._1)) {\n rts += (kv._2 -> ht(kv._1))\n ht -= kv._1\n }\n else\n rs += kv._2 \n }\n for (kv <- ht)\n rt += kv._2\n (rs, rt, rts)\n }\n}\n\nclass UF(N:Int) {\n private[this] val parents = Array.fill(N+1)(-1)\n \n def getRoot(x: Int) : Int = {\n var t = x\n while (parents(t) >= 0)\n t = parents(t)\n t\n }\n \n def sameComponent(x : Int, y : Int) = {\n getRoot(x) == getRoot(y)\n }\n \n def unite(x : Int, y : Int) : Boolean = {\n val rx = getRoot(x) \n val ry = getRoot(y)\n if (rx == ry)\n return false\n if (parents(rx) < parents(ry)) {\n // y to x\n parents(rx) += parents(ry)\n parents(ry) = rx\n } else {\n // x to y\n parents(ry) += parents(rx)\n parents(rx) = ry\n }\n true\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable._\n\nobject CF375_6B extends App {\n val nm = readLine.split(\" \").map(_.toInt)\n val va = new Array[Int](nm(1))\n val vb = new Array[Int](nm(1))\n for (i <- 0 until nm(1)) {\n val ab = readLine.split(\" \").map(_.toInt)\n va(i) = ab(0)\n vb(i) = ab(1)\n }\n val spl = readLine.split(\" \").map(_.toInt)\n val res = solve(nm(1), va, vb, spl(0), spl(1), spl(2), spl(3))\n if (res == null) {\n println(\"No\");\n } else {\n println(\"Yes\");\n for (ab <- res)\n println(ab._1 + \" \" + ab._2)\n }\n\n def solve(n: Int, va: Array[Int], vb: Array[Int], s: Int, t: Int, ds1: Int, dt1: Int): ArrayBuffer[(Int, Int)] = {\n val uf = new UF(n)\n val vs = new ArrayBuffer[Int]()\n val vt = new ArrayBuffer[Int]()\n var st_found = false\n val res = new ArrayBuffer[(Int, Int)]()\n \n for (i <- 0 until va.length) {\n val (a, b) = (va(i), vb(i))\n if (a == s || b == s) {\n if (a == t || b == t)\n st_found = true\n else\n vs += {if (a == s) b else a} \n } else if (a == t) \n vt += b \n else if (b == t)\n vt += a\n else {\n if (uf.unite(a, b)) {\n res += (a -> b)\n } \n }\n }\n \n val(rs, rt, rts) = getComp(vs, vt, uf)\n var ds = ds1 - rs.length\n var dt = dt1 - rt.length\n for (i <- rs) {\n res += (s -> i)\n ds -= 1;\n }\n for (i <- rt) {\n res += (t -> i)\n dt -= 1\n }\n \n var f = 0\n if (st_found && rts.length == 0) {\n res += (s -> t) \n }\n else {\n res += (s -> rts(0)._1)\n res += (t -> rts(0)._2)\n f = 1\n }\n ds -= 1\n dt -= 1\n for (i <- f until rts.length) {\n if (ds > 0) {\n ds -= 1\n res += (s -> rts(i)._1)\n } else {\n dt -= 1\n res += (t -> rts(i)._2)\n }\n }\n \n return if (ds >= 0 && dt >= 0) res else null;\n }\n \n def toHashMap(v : ArrayBuffer[Int], uf : UF) = {\n var res = new HashMap[Int, Int]()\n for (i <- v) \n res += (uf.getRoot(i) -> i) \n res\n }\n \n def getComp(vs : ArrayBuffer[Int], vt : ArrayBuffer[Int], uf : UF) = {\n val hs = toHashMap(vs, uf)\n val ht = toHashMap(vt, uf) \n val rs = new ArrayBuffer[Int]()\n val rt = new ArrayBuffer[Int]()\n val rts = new ArrayBuffer[(Int, Int)]()\n \n for (kv <- hs) {\n if (ht.contains(kv._1)) {\n rts += (kv._2 -> ht(kv._1))\n ht -= kv._1\n }\n else\n rs += kv._2 \n }\n for (kv <- ht)\n rt += kv._2\n (rs, rt, rts)\n }\n}\n\nclass UF(N:Int) {\n private[this] val parents = Array.fill(N+1)(-1)\n \n def getRoot(x: Int) : Int = {\n var t = x\n while (parents(t) >= 0)\n t = parents(t)\n t\n }\n \n def sameComponent(x : Int, y : Int) = {\n getRoot(x) == getRoot(y)\n }\n \n def unite(x : Int, y : Int) : Boolean = {\n val rx = getRoot(x) \n val ry = getRoot(y)\n if (rx == ry)\n return false\n if (parents(rx) < parents(ry)) {\n // y to x\n parents(rx) += parents(ry)\n parents(ry) = rx\n } else {\n // x to y\n parents(ry) += parents(rx)\n parents(rx) = ry\n }\n true\n }\n}"}], "src_uid": "40720fb6da02d5da97df2b90719c5559"} {"nl": {"description": "In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n\u2009\u2264\u20093000, )\u00a0\u2014 the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1\u2009\u2264\u2009si,\u2009ti\u2009\u2264\u2009n, 0\u2009\u2264\u2009li\u2009\u2264\u2009n).", "output_spec": "Print a single number \u2014 the answer to the problem. If the it is impossible to meet the conditions, print -1.", "sample_inputs": ["5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n3 5 2", "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n2 4 2", "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n3 5 1"], "sample_outputs": ["0", "1", "-1"], "notes": null}, "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.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 var graph: Array[ArrayBuffer[Int]] = null\n\n def Bfs(start: Int, dist: Array[Int]): Unit = {\n var queue = collection.mutable.Queue.empty[Int]\n dist(start) = 0\n queue += start\n while (queue.nonEmpty) {\n val start = queue.front\n queue = queue.tail\n graph(start).foreach(i =>\n if (dist(i) > dist(start) + 1) {\n dist(i) = dist(start) + 1\n queue += i\n }\n )\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[Int]](n)\n Range(0, n).foreach(\n graph(_) = new ArrayBuffer[Int]()\n )\n\n Range(0, m).foreach(i => {\n var (a, b) = (nextInt - 1, nextInt - 1)\n graph(a) += b\n graph(b) += a\n })\n\n val dist = Array.fill[Int](n, n)(n + 1)\n Range(0, n).foreach(i => Bfs(i, dist(i)))\n\n val (s0, t0, l0) = (nextInt - 1, nextInt - 1, nextInt)\n val (s1, t1, l1) = (nextInt - 1, nextInt - 1, nextInt)\n if (dist(s0)(t0) > l0 || dist(s1)(t1) > l1) {\n out.println(-1)\n } else {\n var res = dist(s0)(t0) + dist(s1)(t1)\n for (i <- Range(0, n); j <- Range(i + 1, n)) {\n val d0 = math.min(dist(s0)(i) + dist(i)(j) + dist(j)(t0),\n dist(s0)(j) + dist(j)(i) + dist(i)(t0))\n val d1 = math.min(dist(s1)(i) + dist(i)(j) + dist(j)(t1),\n dist(s1)(j) + dist(j)(i) + dist(i)(t1))\n if (d0 <= l0 && d1 <= l1) {\n res = math.min(res, d0 + d1 - dist(i)(j))\n }\n }\n out.println(m - res)\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.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 var graph: Array[ArrayBuffer[Int]] = null\n\n def Bfs(start: Int, dist: Array[Int]): Unit = {\n var queue = collection.mutable.Queue.empty[Int]\n dist(start) = 0\n queue += start\n while (queue.nonEmpty) {\n val start = queue.front\n queue = queue.tail\n graph(start).foreach(i =>\n if (dist(i) > dist(start) + 1) {\n dist(i) = dist(start) + 1\n queue += i\n }\n )\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[Int]](n)\n Range(0, n).foreach(\n graph(_) = new ArrayBuffer[Int]()\n )\n\n Range(0, m).foreach(i => {\n var (a, b) = (nextInt - 1, nextInt - 1)\n graph(a) += b\n graph(b) += a\n })\n\n val dist = Array.fill[Int](n, n)(n + 1)\n Range(0, n).foreach(i => Bfs(i, dist(i)))\n\n val (s0, t0, l0) = (nextInt - 1, nextInt - 1, nextInt)\n val (s1, t1, l1) = (nextInt - 1, nextInt - 1, nextInt)\n if (dist(s0)(t0) > l0 || dist(s1)(t1) > l1) {\n out.println(-1)\n } else {\n var res = dist(s0)(t0) + dist(s1)(t1)\n for (i <- Range(0, n); j <- Range(i + 1, n)) {\n if ((dist(s0)(i) + dist(i)(j) + dist(j)(t0) <= l0 ||\n dist(s0)(j) + dist(j)(i) + dist(i)(t0) <= l0) &&\n (dist(s1)(i) + dist(i)(j) + dist(j)(t1) <= l1 ||\n dist(s1)(j) + dist(j)(i) + dist(i)(t1) <= l1)) {\n res = math.min(res, dist(s0)(t0) + dist(s1)(t1) - dist(i)(j))\n }\n }\n out.println(m - res)\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": "3c5e1f11e6af3821ed8c28f15e429def"} {"nl": {"description": "Phoenix has $$$n$$$ blocks of height $$$h_1, h_2, \\dots, h_n$$$, and all $$$h_i$$$ don't exceed some value $$$x$$$. He plans to stack all $$$n$$$ blocks into $$$m$$$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than $$$x$$$. Please help Phoenix build $$$m$$$ towers that look beautiful. Each tower must have at least one block and all blocks must be used.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$x$$$ ($$$1 \\le m \\le n \\le 10^5$$$; $$$1 \\le x \\le 10^4$$$)\u00a0\u2014 the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively. The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \\le h_i \\le x$$$)\u00a0\u2014 the heights of the blocks. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.", "output_spec": "For each test case, if Phoenix cannot build $$$m$$$ towers that look beautiful, print NO. Otherwise, print YES, followed by $$$n$$$ integers $$$y_1, y_2, \\dots, y_n$$$, where $$$y_i$$$ ($$$1 \\le y_i \\le m$$$) is the index of the tower that the $$$i$$$-th block is placed in. If there are multiple solutions, print any of them.", "sample_inputs": ["2\n5 2 3\n1 2 3 1 2\n4 3 3\n1 1 2 3"], "sample_outputs": ["YES\n1 1 1 2 2\nYES\n1 2 2 3"], "notes": "NoteIn the first test case, the first tower has height $$$1+2+3=6$$$ and the second tower has height $$$1+2=3$$$. Their difference is $$$6-3=3$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.In the second test case, the first tower has height $$$1$$$, the second tower has height $$$1+2=3$$$, and the third tower has height $$$3$$$. The maximum height difference of any two towers is $$$3-1=2$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful."}, "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, m, x = nextInt\n val hs = nextInts(n).zipWithIndex.sorted.reverse\n val res = Array.ofDim[Int](n)\n val towers = Array.fill(m)(0L)\n\n val pq = new mutable.PriorityQueue[Int]()(Ordering.by(towers).reverse)\n for (i <- 0 until m) {\n res(hs(i)._2) = i + 1\n towers(i) = hs(i)._1\n pq += i\n }\n var i = m\n while (i < n) {\n val t = pq.dequeue()\n res(hs(i)._2) = t + 1\n towers(t) += hs(i)._1\n pq += t\n i += 1\n }\n val ok = (towers.max - towers.min) <= x\n if (ok) {\n out.println(\"YES\")\n out.println(res.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"}], "negative_code": [], "src_uid": "57df7947bb90328f543b984833a78e64"} {"nl": {"description": "You have a playlist consisting of $$$n$$$ songs. The $$$i$$$-th song is characterized by two numbers $$$t_i$$$ and $$$b_i$$$ \u2014 its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $$$3$$$ songs having lengths $$$[5, 7, 4]$$$ and beauty values $$$[11, 14, 6]$$$ is equal to $$$(5 + 7 + 4) \\cdot 6 = 96$$$.You need to choose at most $$$k$$$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 3 \\cdot 10^5$$$) \u2013 the number of songs in the playlist and the maximum number of songs you can choose, respectively. Each of the next $$$n$$$ lines contains two integers $$$t_i$$$ and $$$b_i$$$ ($$$1 \\le t_i, b_i \\le 10^6$$$) \u2014 the length and beauty of $$$i$$$-th song.", "output_spec": "Print one integer \u2014 the maximum pleasure you can get.", "sample_inputs": ["4 3\n4 7\n15 1\n3 6\n6 8", "5 3\n12 31\n112 4\n100 100\n13 55\n55 50"], "sample_outputs": ["78", "10000"], "notes": "NoteIn the first test case we can choose songs $$${1, 3, 4}$$$, so the total pleasure is $$$(4 + 3 + 6) \\cdot 6 = 78$$$.In the second test case we can choose song $$$3$$$. The total pleasure will be equal to $$$100 \\cdot 100 = 10000$$$."}, "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\u3067t\u304c\u4f4e\u3044\u9806\u306b\u629c\u3051\u3066\u3044\u3063\u3066\u6b32\u3057\u3044\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\u306e\u964d\u9806\u3067\u4e26\u3079\u308b\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) // \u6570\u304cK\u4ee5\u4e0b\u306e\u3068\u304d\u306fb\u304c\u5927\u304d\u3044\u9806\u306b\u9078\u3076\u3060\u3051\u3002\u305d\u3046\u3067\u306a\u3044\u3068\u6570\u3092\u5897\u3084\u3057\u305f\u65b9\u304c\u5f97\u306b\u306a\u308b\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"}, {"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"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.", "sample_inputs": ["6\n1\n2\n3\n4\n5\n6"], "sample_outputs": ["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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": "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"}], "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"} {"nl": {"description": "Petya got an array $$$a$$$ of numbers from $$$1$$$ to $$$n$$$, where $$$a[i]=i$$$.He performed $$$n$$$ operations sequentially. In the end, he received a new state of the $$$a$$$ array.At the $$$i$$$-th operation, Petya chose the first $$$i$$$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $$$i+1$$$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $$$a=[a_1, a_2, \\dots, a_n]$$$ becomes equal to the array $$$a = [a_i, a_1, a_2, \\dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \\dots, a_n]$$$.For example, if $$$a = [5,4,2,1,3]$$$ and $$$i=3$$$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays: $$$a = [5,4,2,1,3]$$$ (makes $$$0$$$ cyclic shifts, or any number that is divisible by $$$3$$$); $$$a = [2,5,4,1,3]$$$ (makes $$$1$$$ cyclic shift, or any number that has a remainder of $$$1$$$ when divided by $$$3$$$); $$$a = [4,2,5,1,3]$$$ (makes $$$2$$$ cyclic shifts, or any number that has a remainder of $$$2$$$ when divided by $$$3$$$). Let's look at an example. Let $$$n=6$$$, i.e. initially $$$a=[1,2,3,4,5,6]$$$. A possible scenario is described below. $$$i=1$$$: no matter how many cyclic shifts Petya makes, the array $$$a$$$ does not change. $$$i=2$$$: let's say Petya decided to make a $$$1$$$ cyclic shift, then the array will look like $$$a = [\\textbf{2}, \\textbf{1}, 3, 4, 5, 6]$$$. $$$i=3$$$: let's say Petya decided to make $$$1$$$ cyclic shift, then the array will look like $$$a = [\\textbf{3}, \\textbf{2}, \\textbf{1}, 4, 5, 6]$$$. $$$i=4$$$: let's say Petya decided to make $$$2$$$ cyclic shifts, the original array will look like $$$a = [\\textbf{1}, \\textbf{4}, \\textbf{3}, \\textbf{2}, 5, 6]$$$. $$$i=5$$$: let's say Petya decided to make $$$0$$$ cyclic shifts, then the array won't change. $$$i=6$$$: let's say Petya decided to make $$$4$$$ cyclic shifts, the array will look like $$$a = [\\textbf{3}, \\textbf{2}, \\textbf{5}, \\textbf{6}, \\textbf{1}, \\textbf{4}]$$$. You are given a final array state $$$a$$$ after all $$$n$$$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $$$n$$$ operations.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases in the test. The descriptions of the test cases follow. The first line of the description of each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 2\\cdot10^3$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains the final state of the array $$$a$$$: $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$) are written. All $$$a_i$$$ are distinct. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2\\cdot10^3$$$.", "output_spec": "For each test case, print the answer on a separate line. Print -1 if the given final value $$$a$$$ cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print $$$n$$$ non-negative integers $$$d_1, d_2, \\dots, d_n$$$ ($$$d_i \\ge 0$$$), where $$$d_i$$$ means that during the $$$i$$$-th operation the first $$$i$$$ elements of the array were cyclic shifted to the right $$$d_i$$$ times. If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of $$$d_i$$$ values is the smallest). If there are several such answers, print any of them.", "sample_inputs": ["3\n\n6\n\n3 2 5 6 1 4\n\n3\n\n3 1 2\n\n8\n\n5 8 1 3 2 6 4 7"], "sample_outputs": ["0 1 1 2 0 4 \n0 0 1 \n0 1 2 0 2 5 6 2"], "notes": "NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer $$$[3, 2, 1]$$$ also gives the same permutation, but since the total number of shifts $$$3+2+1$$$ is greater than $$$0+0+1$$$, this answer is not correct."}, "positive_code": [{"source_code": "object Solution {\r\n\r\n import scala.io.StdIn.readLine\r\n\r\n def rotate(i: Int, xs: List[Int]): List[Int] = {\r\n if (i == 1) List(0)\r\n else {\r\n val idx = xs.indexOf(i)\r\n if (idx + 1 == i) 0 :: rotate(i - 1, xs.take(xs.length - 1))\r\n else {\r\n val (left, right) = xs.splitAt(idx)\r\n val nxs = right.drop(1) ++ left\r\n left.length + 1 :: rotate(i - 1, nxs)\r\n }\r\n }\r\n }\r\n\r\n def f() = {\r\n val i = readLine().toInt\r\n val xs = readLine().split(\"\\\\s+\").map(_.toInt).toList\r\n println(rotate(i, xs).reverse.mkString(\" \"))\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n\r\n\r\n val cases = readLine().toInt\r\n for (\r\n i <- 0 until cases\r\n ) f()\r\n\r\n }\r\n\r\n}\r\n"}], "negative_code": [], "src_uid": "a83aaaa8984d1a6dda1adf10127b7abc"} {"nl": {"description": "Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.", "input_spec": "The first line of the input contains a single integer l (1\u2009\u2264\u2009l\u2009\u2264\u20091\u2009000)\u00a0\u2014 the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1\u2009\u2264\u2009p,\u2009q\u2009\u2264\u2009500)\u00a0\u2014 the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.", "output_spec": "Print a single real number\u00a0\u2014 the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10\u2009-\u20094. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .", "sample_inputs": ["100\n50\n50", "199\n60\n40"], "sample_outputs": ["50", "119.4"], "notes": "NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor."}, "positive_code": [{"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"}, {"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.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"}, {"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"}], "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"} {"nl": {"description": "$$$ \\def\\myred#1{\\color{red}{\\underline{\\bf{#1}}}} \\def\\myblue#1{\\color{blue}{\\overline{\\bf{#1}}}} $$$ $$$\\def\\RED{\\myred{Red}} \\def\\BLUE{\\myblue{Blue}}$$$You are given a sequence of $$$n$$$ non-negative integers $$$a_1, a_2, \\ldots, a_n$$$. Initially, all the elements of the sequence are unpainted. You can paint each number $$$\\RED$$$ or $$$\\BLUE$$$ (but not both), or leave it unpainted. For a color $$$c$$$, $$$\\text{Count}(c)$$$ is the number of elements in the sequence painted with that color and $$$\\text{Sum}(c)$$$ is the sum of the elements in the sequence painted with that color.For example, if the given sequence is $$$[2, 8, 6, 3, 1]$$$ and it is painted this way: $$$[\\myblue{2}, 8, \\myred{6}, \\myblue{3}, 1]$$$ (where $$$6$$$ is painted red, $$$2$$$ and $$$3$$$ are painted blue, $$$1$$$ and $$$8$$$ are unpainted) then $$$\\text{Sum}(\\RED)=6$$$, $$$\\text{Sum}(\\BLUE)=2+3=5$$$, $$$\\text{Count}(\\RED)=1$$$, and $$$\\text{Count}(\\BLUE)=2$$$.Determine if it is possible to paint the sequence so that $$$\\text{Sum}(\\RED) > \\text{Sum}(\\BLUE)$$$ and $$$\\text{Count}(\\RED) < \\text{Count}(\\BLUE)$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3\\le n\\le 2\\cdot 10^5$$$)\u00a0\u2014 the length of the given sequence. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$0\\le a_i\\le 10^9$$$)\u00a0\u2014 the given sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, print YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["4\n3\n1 2 3\n5\n2 8 6 3 1\n4\n3 5 4 2\n5\n1000000000 1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["NO\nYES\nNO\nNO"], "notes": "NoteIn the first test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\\myblue{1},\\myblue{2},\\myred{3}]$$$ (where $$$3$$$ is painted red, $$$1$$$ and $$$2$$$ are painted blue) then $$$\\text{Count}(\\RED)=1 < \\text{Count}(\\BLUE)=2$$$, but $$$\\text{Sum}(\\RED)=3 \\ngtr \\text{Sum}(\\BLUE)=3$$$. So, this is not a possible way to paint the sequence.In the second test case, a possible way to paint the sequence is described in the statement. We can see that $$$\\text{Sum}(\\RED)=6 > \\text{Sum}(\\BLUE)=5$$$ and $$$\\text{Count}(\\RED)=1 < \\text{Count}(\\BLUE)=2$$$.In the third test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\\myred{3},\\myred{5},\\myblue{4}, \\myblue{2}]$$$ (where $$$3$$$ and $$$5$$$ are painted red, $$$4$$$ and $$$2$$$ are painted blue) then $$$\\text{Sum}(\\RED) = 8 > \\text{Sum}(\\BLUE) = 6$$$ but $$$\\text{Count}(\\RED) = 2 \\nless \\text{Count}(\\BLUE) = 2$$$. So, this is not a possible way to paint the sequence.In the fourth test case, it can be proven that there is no possible way to paint the sequence satisfying sum and count constraints."}, "positive_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 QualityVsQuantity {\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// \"4\\n3\\n1 2 3\\n5\\n2 8 6 3 1\\n4\\n3 5 4 2\\n5\\n1000000000 1000000000 1000000000 1000000000 1000000000\".getBytes)))\r\n\r\n var t = file.readLine.toInt\r\n while (t > 0) {\r\n t = t - 1\r\n file.readLine\r\n val nums = file.readLine.split(\" \").map(_.toLong)\r\n val s = nums.sorted\r\n if (s.length == 3) {\r\n if (s(2) > s(0) + s(1)) println(\"yes\")\r\n else println(\"no\")\r\n } else {\r\n var i = 1; var j = s.length - 1\r\n var si = s(0) + s(1); var sj = s(j)\r\n var ci = 2; var cj = 1\r\n var res = \"no\"\r\n while (i < j && !(ci <= cj && si >= sj) && res != \"yes\") {\r\n if (ci > cj && si < sj) {\r\n res = \"yes\"\r\n } else if (ci > cj && si >= sj) {\r\n j = j - 1; cj = cj + 1; sj = sj + s(j)\r\n } else if (ci <= cj && si < sj) {\r\n i = i + 1; ci = ci + 1; si = si + s(i)\r\n }\r\n }\r\n println(res)\r\n }\r\n }\r\n }\r\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 QualityVsQuantity {\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// \"4\\n3\\n1 2 3\\n5\\n2 8 6 3 1\\n4\\n3 5 4 2\\n5\\n1000000000 1000000000 1000000000 1000000000 1000000000\".getBytes)))\r\n\r\n var t = file.readLine.toInt\r\n while (t > 0) {\r\n t = t - 1\r\n file.readLine\r\n val nums = file.readLine.split(\" \").map(_.toInt)\r\n val s = nums.sorted\r\n if (s.length == 3) {\r\n if (s(2) > s(0) + s(1)) println(\"yes\")\r\n else println(\"no\")\r\n } else {\r\n var i = 1; var j = s.length - 1\r\n var si = s(0) + s(1); var sj = s(j)\r\n var ci = 2; var cj = 1\r\n var res = \"no\"\r\n while (i < j && !(ci <= cj && si >= sj) && res != \"yes\") {\r\n if (ci > cj && si < sj) {\r\n res = \"yes\"\r\n } else if (ci > cj && si >= sj) {\r\n j = j - 1; cj = cj + 1; sj = sj + s(j)\r\n } else if (ci <= cj && si < sj) {\r\n i = i + 1; ci = ci + 1; si = si + s(i)\r\n }\r\n }\r\n println(res)\r\n }\r\n }\r\n }\r\n}"}], "src_uid": "4af59df1bc56ca8eb5913c2e57905922"} {"nl": {"description": "Little Dormi received a histogram with $$$n$$$ bars of height $$$a_1, a_2, \\ldots, a_n$$$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index $$$i$$$ ($$$1 \\le i \\le n$$$) where $$$a_i>0$$$, and assign $$$a_i := a_i-1$$$.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has $$$4$$$ columns of heights $$$4,8,9,6$$$: The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $$$4+4+1+3+6 = 18$$$, so if Little Dormi does not modify the histogram at all, the ugliness would be $$$18$$$.However, Little Dormi can apply the operation once on column $$$2$$$ and twice on column $$$3$$$, resulting in a histogram with heights $$$4,7,7,6$$$: Now, as the total vertical length of the outline (red lines) is $$$4+3+1+6=14$$$, the ugliness is $$$14+3=17$$$ dollars. It can be proven that this is optimal.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 4 \\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \\cdot 10^5$$$.", "output_spec": "For each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.", "sample_inputs": ["2\n4\n4 8 9 6\n6\n2 1 7 4 0 0"], "sample_outputs": ["17\n12"], "notes": "NoteExample $$$1$$$ is the example described in the statement.The initial histogram for example $$$2$$$ is given below: The ugliness is currently $$$2+1+6+3+4=16$$$.By applying the operation once on column $$$1$$$, six times on column $$$3$$$, and three times on column $$$4$$$, we can end up with a histogram with heights $$$1,1,1,1,0,0$$$: The vertical length of the outline is now $$$1+1=2$$$ and Little Dormi made $$$1+6+3=10$$$ operations, so the final ugliness is $$$2+10=12$$$, which can be proven to be optimal."}, "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 = 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"}, {"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"} {"nl": {"description": "Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant \u2014 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u20091000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai \u2014 integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.", "output_spec": "Print one real number \u2014 the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10\u2009-\u20096.", "sample_inputs": ["2 1\n0 0\n10 0", "5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0", "6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0"], "sample_outputs": ["0.200000000", "6.032163204", "3.000000000"], "notes": null}, "positive_code": [{"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"}, {"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 \u00d7(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(\u00d7(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"}, {"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}"}], "negative_code": [], "src_uid": "db4a25159067abd9e3dd22bc4b773385"} {"nl": {"description": "You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv\u2009=\u20090.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu\u2009=\u2009x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009104)\u00a0\u2014 the number of vertices in the tree. The second line contains n\u2009-\u20091 integers p2,\u2009p3,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009<\u2009i), where pi means that there is an edge between vertices i and pi. The third line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009n), where ci is the color you should color the i-th vertex into. It is guaranteed that the given graph is a tree. ", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of steps you have to perform to color the tree into given colors.", "sample_inputs": ["6\n1 2 2 1 5\n2 1 1 1 1 1", "7\n1 1 2 3 1 4\n3 3 1 1 1 2 3"], "sample_outputs": ["3", "5"], "notes": "NoteThe tree from the first sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):On seond step we color all vertices in the subtree of vertex 5 into color 1:On third step we color all vertices in the subtree of vertex 2 into color 1:The tree from the second sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):On second step we color all vertices in the subtree of vertex 3 into color 1:On third step we color all vertices in the subtree of vertex 6 into color 2:On fourth step we color all vertices in the subtree of vertex 4 into color 1:On fith step we color all vertices in the subtree of vertex 7 into color 3:"}, "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 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"}, {"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 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"}], "negative_code": [], "src_uid": "b23696f763d90335e8bfb0a5e2094c03"} {"nl": {"description": "Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: \"Fox\"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si\u2009\u2260\u2009ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100): number of names. Each of the following n lines contain one string namei (1\u2009\u2264\u2009|namei|\u2009\u2264\u2009100), the i-th name. Each name contains only lowercase Latin letters. All names are different.", "output_spec": "If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'\u2013'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word \"Impossible\" (without quotes).", "sample_inputs": ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"], "sample_outputs": ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a binary string of length $$$n$$$ (i.\u2009e. a string consisting of $$$n$$$ characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than $$$k$$$ moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices $$$i$$$ and $$$i+1$$$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer $$$q$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) \u2014 the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^6, 1 \\le k \\le n^2$$$) \u2014 the length of the string and the number of moves you can perform. The second line of the test case contains one string consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\\sum n \\le 10^6$$$).", "output_spec": "For each test case, print the answer on it: the lexicographically minimum possible string of length $$$n$$$ you can obtain from the given one if you can perform no more than $$$k$$$ moves.", "sample_inputs": ["3\n8 5\n11011010\n7 9\n1111100\n7 11\n1111100"], "sample_outputs": ["01011110\n0101111\n0011111"], "notes": "NoteIn the first example, you can change the string as follows: $$$1\\underline{10}11010 \\rightarrow \\underline{10}111010 \\rightarrow 0111\\underline{10}10 \\rightarrow 011\\underline{10}110 \\rightarrow 01\\underline{10}1110 \\rightarrow 01011110$$$. In the third example, there are enough operations to make the string sorted."}, "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": "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}"}, {"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"} {"nl": {"description": "You are given an integer array $$$a_1, a_2, \\dots, a_n$$$ and integer $$$k$$$.In one step you can either choose some index $$$i$$$ and decrease $$$a_i$$$ by one (make $$$a_i = a_i - 1$$$); or choose two indices $$$i$$$ and $$$j$$$ and set $$$a_i$$$ equal to $$$a_j$$$ (make $$$a_i = a_j$$$). What is the minimum number of steps you need to make the sum of array $$$\\sum\\limits_{i=1}^{n}{a_i} \\le k$$$? (You are allowed to make values of array negative).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$1 \\le k \\le 10^{15}$$$)\u00a0\u2014 the size of array $$$a$$$ and upper bound on its sum. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the array itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print one integer\u00a0\u2014 the minimum number of steps to make $$$\\sum\\limits_{i=1}^{n}{a_i} \\le k$$$.", "sample_inputs": ["4\n1 10\n20\n2 69\n6 9\n7 8\n1 2 1 3 1 2 1\n10 1\n1 2 3 1 2 6 1 6 8 10"], "sample_outputs": ["10\n0\n2\n7"], "notes": "NoteIn the first test case, you should decrease $$$a_1$$$ $$$10$$$ times to get the sum lower or equal to $$$k = 10$$$.In the second test case, the sum of array $$$a$$$ is already less or equal to $$$69$$$, so you don't need to change it.In the third test case, you can, for example: set $$$a_4 = a_3 = 1$$$; decrease $$$a_4$$$ by one, and get $$$a_4 = 0$$$. As a result, you'll get array $$$[1, 2, 1, 0, 1, 2, 1]$$$ with sum less or equal to $$$8$$$ in $$$1 + 1 = 2$$$ steps.In the fourth test case, you can, for example: choose $$$a_7$$$ and decrease in by one $$$3$$$ times; you'll get $$$a_7 = -2$$$; choose $$$4$$$ elements $$$a_6$$$, $$$a_8$$$, $$$a_9$$$ and $$$a_{10}$$$ and them equal to $$$a_7 = -2$$$. As a result, you'll get array $$$[1, 2, 3, 1, 2, -2, -2, -2, -2, -2]$$$ with sum less or equal to $$$1$$$ in $$$3 + 4 = 7$$$ steps."}, "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, k = nextLong\n val n = _n.toInt\n val as = nextLongs(n).sorted.reverse\n val min = as.last\n val sum = as.sum\n\n var res = Math.max(0L, min - (k - (sum - min)))\n var prefixSum = 0L\n// if (sum <= k) {\n// res = 0\n// }\n if (n == 1) {\n res = min - k\n }\n\n for (i <- 0 until n - 1) {\n prefixSum += as(i)\n val numTouched = i + 2L\n val untouchedSum = sum - prefixSum - min\n val maxTouchedSum = k - untouchedSum\n// val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)\n var maxTouchedLevel = if (maxTouchedSum >= 0) maxTouchedSum / numTouched\n else if (maxTouchedSum % numTouched == 0) maxTouchedSum / numTouched\n else (maxTouchedSum - (numTouched - Math.abs(maxTouchedSum) % numTouched)) / numTouched\n if (maxTouchedLevel > min) {\n maxTouchedLevel = min\n }\n val steps = i + 1 + min - maxTouchedLevel\n// println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)\n if (steps < res) {\n res = steps\n }\n }\n if (res < 0) res = 0\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": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val _n, k = nextLong\n val n = _n.toInt\n val as = nextLongs(n).sorted.reverse\n val min = as.last\n val sum = as.sum\n\n var res = Math.max(0, min - (k - (sum - min)))\n var prefixSum = 0L\n// if (sum <= k) {\n// res = 0\n// }\n if (n == 1) {\n res = min - k\n }\n\n for (i <- 0 until n - 1) {\n prefixSum += as(i)\n val untouched = sum - prefixSum - min\n val maxTouched = k - untouched\n// val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)\n var maxLevel = if (maxTouched >= 0) maxTouched / (i + 2)\n else (maxTouched - ((i + 2) - Math.abs(maxTouched) % (i + 2))) / (i + 2)\n if (maxLevel > min) {\n maxLevel = min\n }\n val steps = i + 1 + min - maxLevel\n// println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)\n if (steps < res) {\n res = steps\n }\n }\n if (res < 0) res = 0\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val _n, k = nextLong\n val n = _n.toInt\n val as = nextLongs(n).sorted.reverse\n val min = as.last\n val sum = as.sum\n\n var res = Math.max(0, min - (k - (sum - min)))\n var prefixSum = 0L\n// if (sum <= k) {\n// res = 0\n// }\n if (n == 1) {\n res = min - k\n }\n\n for (i <- 0 until n - 1) {\n prefixSum += as(i)\n val untouched = sum - prefixSum - min\n val maxTouched = k - untouched\n// val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)\n var maxLevel = if (maxTouched >= 0) maxTouched / (i + 2)\n else (maxTouched - Math.abs(maxTouched) % (i + 2)) / (i + 2)\n if (maxLevel > min) {\n maxLevel = min\n }\n val steps = i + 1 + min - maxLevel\n// println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)\n if (steps < res) {\n res = steps\n }\n }\n if (res < 0) res = 0\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val _n, k = nextLong\n val n = _n.toInt\n val as = nextLongs(n).sorted.reverse\n val min = as.last\n val sum = as.sum\n\n var res = Long.MaxValue\n var prefixSum = 0L\n if (n == 1) {\n res = min - k\n }\n\n for (i <- 0 until n - 1) {\n prefixSum += as(i)\n val untouched = sum - prefixSum - min\n val maxTouched = k - untouched\n// val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)\n val maxLevel = if (maxTouched >= 0) maxTouched / (i + 2)\n else (maxTouched - Math.abs(maxTouched) % (i + 2)) / (i + 2)\n val steps = i + 1 + min - maxLevel\n// println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)\n if (steps < res) {\n res = steps\n }\n }\n if (res < 0) res = 0\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val _n, k = nextLong\n val n = _n.toInt\n val as = nextLongs(n).sorted.reverse\n val min = as.last\n val sum = as.sum\n\n var res = Long.MaxValue\n var prefixSum = 0L\n if (n == 1) {\n res = min - k\n }\n\n for (i <- 0 until n - 1) {\n prefixSum += as(i)\n val untouched = sum - prefixSum - min\n val maxTouched = k - untouched\n val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)\n val steps = i + 1 + min - maxLevel\n// println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)\n if (steps < res) {\n res = steps\n }\n }\n if (res < 0) res = 0\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": "aec97dc779ba6b1d291fb1031dab93a7"} {"nl": {"description": "Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.", "input_spec": "The first line consists of a single integer $$$t$$$ $$$(1 \\le t \\le 50)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \\le n, m \\le 50)$$$\u00a0\u2014 the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \\in \\{0, 1\\})$$$.", "output_spec": "For each test case if Ashish wins the game print \"Ashish\" otherwise print \"Vivek\" (without quotes).", "sample_inputs": ["4\n2 2\n0 0\n0 0\n2 2\n0 0\n0 1\n2 3\n1 0 1\n1 1 0\n3 3\n1 0 0\n0 0 0\n1 0 0"], "sample_outputs": ["Vivek\nAshish\nVivek\nAshish"], "notes": "NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left."}, "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 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"}, {"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": "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"}], "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"} {"nl": {"description": "Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).", "input_spec": "The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \\le d < n \\le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \\le m \\le 100$$$) \u2014 the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \\le x_i, y_i \\le n$$$) \u2014 position of the $$$i$$$-th grasshopper.", "output_spec": "Print $$$m$$$ lines. The $$$i$$$-th line should contain \"YES\" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"], "sample_outputs": ["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"], "notes": "NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield. "}, "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, 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"}, {"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"} {"nl": {"description": "Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1,\u2009y1) and (x2,\u2009y2).Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix,\u2009viy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap.Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of computer mice on the desk. The second line contains four integers x1, y1, x2 and y2 (0\u2009\u2264\u2009x1\u2009\u2264\u2009x2\u2009\u2264\u2009100\u2009000), (0\u2009\u2264\u2009y1\u2009\u2264\u2009y2\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the coordinates of the opposite corners of the mousetrap. The next n lines contain the information about mice. The i-th of these lines contains four integers rix, riy, vix and viy, (0\u2009\u2264\u2009rix,\u2009riy\u2009\u2264\u2009100\u2009000, \u2009-\u2009100\u2009000\u2009\u2264\u2009vix,\u2009viy\u2009\u2264\u2009100\u2009000), where (rix,\u2009riy) is the initial position of the mouse, and (vix,\u2009viy) is its speed.", "output_spec": "In the only line print minimum possible non-negative number t such that if Igor closes the mousetrap at t seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such t, print -1. Your answer is considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20096. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .", "sample_inputs": ["4\n7 7 9 8\n3 5 7 5\n7 5 2 4\n3 3 7 8\n6 6 3 2", "4\n7 7 9 8\n0 3 -5 4\n5 0 5 4\n9 9 -1 -6\n10 5 -7 -10"], "sample_outputs": ["0.57142857142857139685", "-1"], "notes": "NoteHere is a picture of the first samplePoints A, B, C, D - start mice positions, segments are their paths.Then, at first time when all mice will be in rectangle it will be looks like this:Here is a picture of the second samplePoints A, D, B will never enter rectangle."}, "positive_code": [{"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = (t1 min t2) max 0\n if (et <= lt) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n } else maxT = -1\n // println(t1, t2, minT, maxT)\n } else if (ru <= u1.min(u2) || ru >= u1.max(u2)) maxT = -1 //standing outside\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT < maxT) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}], "negative_code": [{"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = (t1 min t2) max 0\n if (et <= lt) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n // println(t1, t2, minT, maxT)\n } else if (ru <= u1.min(u2) || ru >= u1.max(u2)) maxT = -1 //standing outside\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT < maxT) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (ru.toDouble - u1).abs / vu\n val t2 = (ru.toDouble - u2).abs / vu\n val lt = t1 max t2 max 0\n val et = t1 min t2\n if (et < lt + eps) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n// println(t1, t2, minT, maxT)\n }\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT <= maxT + eps) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (ru.toDouble - u1).abs / vu\n val t2 = (ru.toDouble - u2).abs / vu\n val lt = t1 max t2 max 0\n val et = t1 min t2\n if (et < lt + eps) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n// println(t1, t2, minT, maxT)\n }\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT < maxT + eps) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (ru.toDouble - u1).abs / vu\n val t2 = (ru.toDouble - u2).abs / vu\n val lt = t1 max t2 max 0\n val et = t1 min t2\n if (et < lt + eps) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n// println(t1, t2, minT, maxT)\n }\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT < maxT + eps) {\n println(f\"${(minT + maxT) / 2}%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = (t1 min t2) max 0\n if (et <= lt) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n // println(t1, t2, minT, maxT)\n } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT < maxT) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = (t1 min t2) max 0\n if (et <= lt + eps) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n // println(t1, t2, minT, maxT)\n } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT <= maxT + eps) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = (t1 min t2) max 0\n if (et <= lt) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n // println(t1, t2, minT, maxT)\n } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT < maxT) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = t1 min t2\n if (et >= 0) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n// println(t1, t2, minT, maxT)\n }\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT <= maxT + eps) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}, {"source_code": "import io.StdIn.readLine\n\nobject C extends App {\n val n = readLine.toInt\n var minT = 0.0\n var maxT = Double.MaxValue\n val eps = 1e-7\n val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)\n\n def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =\n if (vu != 0) {\n val t1 = (u1 - ru.toDouble) / vu\n val t2 = (u2 - ru.toDouble) / vu\n val lt = t1 max t2\n val et = t1 min t2\n if (et >= 0) {\n if (minT < et) minT = et\n if (maxT > lt) maxT = lt\n }\n // println(t1, t2, minT, maxT)\n } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside\n\n for (i <- 1 to n) {\n val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)\n\n check(rx, vx, x1, x2)\n check(ry, vy, y1, y2)\n }\n\n if (minT <= maxT + eps) {\n println(f\"$minT%.7f\")\n } else println(\"-1\")\n}"}], "src_uid": "2df45858a638a90d30315844df6d1084"} {"nl": {"description": "The legend of the foundation of Vectorland talks of two integers $$$x$$$ and $$$y$$$. Centuries ago, the array king placed two markers at points $$$|x|$$$ and $$$|y|$$$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $$$|x - y|$$$ and $$$|x + y|$$$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.Here $$$|z|$$$ denotes the absolute value of $$$z$$$.Now, Jose is stuck on a question of his history exam: \"What are the values of $$$x$$$ and $$$y$$$?\" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$. Now, he wants to know the number of unordered pairs formed by two different elements from these $$$n$$$ integers such that the legend could be true if $$$x$$$ and $$$y$$$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u00a0\u2014 the number of choices. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$)\u00a0\u2014 the choices Jose is considering.", "output_spec": "Print a single integer number\u00a0\u2014 the number of unordered pairs $$$\\{x, y\\}$$$ formed by different numbers from Jose's choices that could make the legend true.", "sample_inputs": ["3\n2 5 -3", "2\n3 6"], "sample_outputs": ["2", "1"], "notes": "NoteConsider the first sample. For the pair $$$\\{2, 5\\}$$$, the situation looks as follows, with the Arrayland markers at $$$|2| = 2$$$ and $$$|5| = 5$$$, while the Vectorland markers are located at $$$|2 - 5| = 3$$$ and $$$|2 + 5| = 7$$$: The legend is not true in this case, because the interval $$$[2, 3]$$$ is not conquered by Vectorland. For the pair $$$\\{5, -3\\}$$$ the situation looks as follows, with Arrayland consisting of the interval $$$[3, 5]$$$ and Vectorland consisting of the interval $$$[2, 8]$$$: As Vectorland completely contains Arrayland, the legend is true. It can also be shown that the legend is true for the pair $$$\\{2, -3\\}$$$, for a total of two pairs.In the second sample, the only pair is $$$\\{3, 6\\}$$$, and the situation looks as follows: Note that even though Arrayland and Vectorland share $$$3$$$ as endpoint, we still consider Arrayland to be completely inside of Vectorland."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = Array.ofDim[Int](N)\n REP(N) { i =>\n A(i) = abs(ni())\n }\n sort(A)\n\n debug(A)\n\n var ans = 0L\n REP(N) { i =>\n val x = A(i)\n if (x != 0) {\n // x < y\n val cntY = upperBound(A, x * 2) - (i + 1)\n debug(s\"x:$x cntY:$cntY\")\n ans += cntY\n }\n }\n\n out.println(ans)\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\n // \u8981\u306fcountLe\n // a > x [x-2, x-1, x, x, x, x+1] \u306e 5\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}"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = Array.ofDim[Int](N)\n REP(N) { i =>\n A(i) = abs(ni())\n }\n sort(A)\n\n debug(A)\n\n var ans = 0L\n REP(N) { i =>\n val x = A(i)\n if (x == 0) {\n ans += N - (i + 1)\n } else {\n // x < y\n val cntY = upperBound(A, x * 2) - (i + 1)\n debug(s\"x:$x cntY:$cntY\")\n ans += cntY\n }\n }\n\n out.println(ans)\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\n // \u8981\u306fcountLe\n // a > x [x-2, x-1, x, x, x, x+1] \u306e 5\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}"}], "src_uid": "642e2d1b427c025578424c81192be756"} {"nl": {"description": "Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times: Choose one of her cards X. This card mustn't be chosen before. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: If Y's position is Attack, then (X's strength) \u2009\u2265\u2009 (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). If Y's position is Defense, then (X's strength) \u2009>\u2009 (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage. Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of cards Jiro and Ciel have. Each of the next n lines contains a string position and an integer strength (0\u2009\u2264\u2009strength\u2009\u2264\u20098000) \u2014 the position and strength of Jiro's current card. Position is the string \"ATK\" for attack, and the string \"DEF\" for defense. Each of the next m lines contains an integer strength (0\u2009\u2264\u2009strength\u2009\u2264\u20098000) \u2014 the strength of Ciel's current card.", "output_spec": "Output an integer: the maximal damage Jiro can get.", "sample_inputs": ["2 3\nATK 2000\nDEF 1700\n2500\n2500\n2500", "3 4\nATK 10\nATK 100\nATK 1000\n1\n11\n101\n1001", "2 4\nDEF 0\nATK 0\n0\n0\n1\n1"], "sample_outputs": ["3000", "992", "1"], "notes": "NoteIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack \"ATK 2000\" card first, this attack destroys that card and Jiro gets 2500\u2009-\u20092000\u2009=\u2009500 damage. Then she uses the second card to destroy the \"DEF 1700\" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500\u2009+\u20092500\u2009=\u20093000.In the second test case, she should use the \"1001\" card to attack the \"ATK 100\" card, then use the \"101\" card to attack the \"ATK 10\" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001\u2009-\u2009100)\u2009+\u2009(101\u2009-\u200910)\u2009=\u2009992.In the third test case note that she can destroy the \"ATK 0\" card by a card with strength equal to 0, but she can't destroy a \"DEF 0\" card with that card."}, "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}"}, {"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"} {"nl": {"description": "A function is called Lipschitz continuous if there is a real constant K such that the inequality |f(x)\u2009-\u2009f(y)|\u2009\u2264\u2009K\u00b7|x\u2009-\u2009y| holds for all . We'll deal with a more... discrete version of this term.For an array , we define it's Lipschitz constant as follows: if n\u2009<\u20092, if n\u2009\u2265\u20092, over all 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n In other words, is the smallest non-negative integer such that |h[i]\u2009-\u2009h[j]|\u2009\u2264\u2009L\u00b7|i\u2009-\u2009j| holds for all 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n.You are given an array of size n and q queries of the form [l,\u2009r]. For each query, consider the subarray ; determine the sum of Lipschitz constants of all subarrays of .", "input_spec": "The first line of the input contains two space-separated integers n and q (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000 and 1\u2009\u2264\u2009q\u2009\u2264\u2009100)\u00a0\u2014 the number of elements in array and the number of queries respectively. The second line contains n space-separated integers (). The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer\u00a0\u2014 the sum of Lipschitz constants of all subarrays of .", "sample_inputs": ["10 4\n1 5 2 9 1 3 4 2 1 7\n2 4\n3 8\n7 10\n1 9", "7 6\n5 7 7 4 6 6 2\n1 2\n2 3\n2 6\n1 7\n4 7\n3 5"], "sample_outputs": ["17\n82\n23\n210", "2\n0\n22\n59\n16\n8"], "notes": "NoteIn the first query of the first sample, the Lipschitz constants of subarrays of with length at least 2 are: The answer to the query is their sum."}, "positive_code": [{"source_code": "object D{\n //import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.Stack\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,q)=(nextInt,nextInt)\n var h0=nextInt\n val dh=Array.ofDim[Long](n-1)\n for(i<-0 until n-1) {\n val h=nextInt\n dh(i)=math.abs(h-h0)\n h0=h\n }\n //get a,b\n val a,b=Array.ofDim[Int](n-1)\n val st=new Stack[Int]()\n a(0)= -1\n st.push(0)\n for(i<-1 until n-1){\n \n while(!st.isEmpty && dh(st.top) 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}"}, {"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}"}], "negative_code": [], "src_uid": "5d11fa8528f1dc873d50b3417bef8c79"} {"nl": {"description": "Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \\times 1 \\times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \\times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \\times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?", "input_spec": "The first line contains three positive space-separated integers $$$n, m, h$$$ ($$$1\\leq n, m, h \\leq 100$$$)\u00a0\u2014 the length, width and height. The second line contains $$$m$$$ non-negative space-separated integers $$$a_1,a_2,\\dots,a_m$$$, where $$$a_i$$$ is the height in the $$$i$$$-th column from left to right of the front view ($$$0\\leq a_i \\leq h$$$). The third line contains $$$n$$$ non-negative space-separated integers $$$b_1,b_2,\\dots,b_n$$$ ($$$0\\leq b_j \\leq h$$$), where $$$b_j$$$ is the height in the $$$j$$$-th column from left to right of the left view. Each of the following $$$n$$$ lines contains $$$m$$$ numbers, each is $$$0$$$ or $$$1$$$, representing the top view, where $$$j$$$-th number of $$$i$$$-th row is $$$1$$$ if $$$h_{i, j}>0$$$, and $$$0$$$ otherwise. It is guaranteed that there is at least one structure satisfying the input.", "output_spec": "Output $$$n$$$ lines, each of them contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.", "sample_inputs": ["3 7 3\n2 3 0 0 2 0 1\n2 1 3\n1 0 0 0 1 0 0\n0 0 0 0 0 0 1\n1 1 0 0 0 0 0", "4 5 5\n3 5 2 0 4\n4 2 5 4\n0 0 0 0 1\n1 0 1 0 0\n0 1 0 0 0\n1 1 1 0 0"], "sample_outputs": ["1 0 0 0 2 0 0\n0 0 0 0 0 0 1\n2 3 0 0 0 0 0", "0 0 0 0 4\n1 0 2 0 0\n0 5 0 0 0\n3 4 1 0 0"], "notes": "Note The graph above illustrates the object in the first example. The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "7361e8acf0d712c317e8b99211a7b548"} {"nl": {"description": "Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100\u2009000, inclusive. It is possible that some cards have the same integers on them.Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.You are to determine the total number of times Vasily takes the top card from the deck.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the number of cards in the deck. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100\u2009000), where ai is the number written on the i-th from top card in the deck.", "output_spec": "Print the total number of times Vasily takes the top card from the deck.", "sample_inputs": ["4\n6 3 1 2", "1\n1000", "7\n3 3 3 3 3 3 3"], "sample_outputs": ["7", "1", "7"], "notes": "NoteIn the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2,\u20096,\u20093]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6,\u20093]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards."}, "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"}, {"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"}], "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"} {"nl": {"description": "Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above.", "input_spec": "The first line contains three space-separated integers n,\u2009s,\u2009l (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009s\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009l\u2009\u2264\u2009105). The second line contains n integers ai separated by spaces (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Output the minimal number of strip pieces. If there are no ways to split the strip, output -1.", "sample_inputs": ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"], "sample_outputs": ["3", "-1"], "notes": "NoteFor the first sample, we can split the strip into 3 pieces: [1,\u20093,\u20091],\u2009[2,\u20094],\u2009[1,\u20092].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists."}, "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 case class SegTreeMin(as: Array[Int]) {\n\n val NEUTRAL = Int.MaxValue // neutral element in respect of operation used (min)\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 math.min(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 }\n\n case class SegTreeMax(as: Array[Int]) {\n\n val NEUTRAL = Int.MinValue // neutral element in respect of operation used (max)\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 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 }\n\n val Array(n, s, l) = readInts(3)\n val as = readInts(n)\n\n val stMin = SegTreeMin(as)\n val stMax = SegTreeMax(as)\n\n val solved = Array.fill(n + 1)(-1)\n solved(n) = 0\n\n def solve(left: Int): Int = {\n if (solved(left) >= 0) solved(left)\n else {\n var best = 1000000\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) >>> 1\n if (stMax.query(left, mid) - stMin.query(left, mid) > s) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val minRight = left + l - 1\n var right = binSearch(minRight, n - 1) - 1\n val limit = math.max(minRight, right - l)\n\n while (right >= limit) {\n val result = solve(right + 1) + 1\n if (result < best) {\n best = result\n right = -1\n } else right -= 1\n }\n solved(left) = best\n best\n }\n }\n\n val res = solve(0)\n\n println(if (res == 1000000) -1 else res)\n}"}], "negative_code": [], "src_uid": "3d670528c82a7d8dcd187b7304d36f96"} {"nl": {"description": "Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open\u00a0\u2014 for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.", "input_spec": "The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \\le s \\le n \\le 1000$$$)\u00a0\u2014 the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.", "output_spec": "Print \"YES\" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and \"NO\" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["5 3\n1 1 1 1 1\n1 1 1 1 1", "5 4\n1 0 0 0 1\n0 1 1 1 1", "5 2\n0 1 1 1 1\n1 1 1 1 1"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home."}, "positive_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, 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": "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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored A\u00b7B\u00b7C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A\u2009-\u20091)\u2009\u00d7\u2009(B\u2009-\u20092)\u2009\u00d7\u2009(C\u2009-\u20092) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1\u2009\u00d7\u20091\u2009\u00d7\u20091 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B \u0438 C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.", "input_spec": "The only line contains integer n from the problem's statement (1\u2009\u2264\u2009n\u2009\u2264\u2009109).", "output_spec": "Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specificator.", "sample_inputs": ["4", "7", "12"], "sample_outputs": ["28 41", "47 65", "48 105"], "notes": "NoteLet's consider the first sample test. If initially Sam has a parallelepiped consisting of 32\u2009=\u20092\u2009\u00d7\u20094\u2009\u00d7\u20094 hay blocks in his barn, then after the theft the barn has 4\u2009=\u2009(2\u2009-\u20091)\u2009\u00d7\u2009(4\u2009-\u20092)\u2009\u00d7\u2009(4\u2009-\u20092) hay blocks left. Thus, the thieves could have stolen 32\u2009-\u20094\u2009=\u200928 hay blocks. If Sam initially had a parallelepiped consisting of 45\u2009=\u20095\u2009\u00d7\u20093\u2009\u00d7\u20093 hay blocks in his barn, then after the theft the barn has 4\u2009=\u2009(5\u2009-\u20091)\u2009\u00d7\u2009(3\u2009-\u20092)\u2009\u00d7\u2009(3\u2009-\u20092) hay blocks left. Thus, the thieves could have stolen 45\u2009-\u20094\u2009=\u200941 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks."}, "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.math._\nobject Main {\n\n val oo = Long.MaxValue / 2;\n \n def main(args: Array[String]): Unit = {\n def factorize(n: Long): List[Long] = {\n val range = 1L to sqrt(n).asInstanceOf[Long]\n range.foldLeft(List[Long]()) { (xs: List[Long], i: Long) =>\n if (n % i == 0) {\n if (i * i != n) i :: n / i :: xs\n else i :: xs\n } else xs\n }\n } \n \n def solve(n: Int): (Long, Long) = {\n var min = +oo\n var max = -oo\n val factors = factorize(n)\n for(factor <- factors) {\n val subFactors = factorize(factor)\n for(subFactor <- subFactors) {\n val num = (1 + n / factor) * (2 + subFactor) * (2 + factor/ subFactor);\n min = Math.min(min, num)\n max = Math.max(max, num)\n }\n }\n (min - n, max - n)\n }\n val n = readInt()\n val ans = solve(n)\n print(ans._1 + \" \" + ans._2)\n }\n}"}], "negative_code": [], "src_uid": "2468eead8acc5b8f5ddc51bfa2bd4fb7"} {"nl": {"description": "Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds: divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$); multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ \u2014 the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.", "input_spec": "The first line of the input contatins an integer number $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 3 \\cdot 10^{18}$$$) \u2014 rearranged (reordered) sequence that Polycarp can wrote down on the board.", "output_spec": "Print $$$n$$$ integer numbers \u2014 rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.", "sample_inputs": ["6\n4 8 6 3 12 9", "4\n42 28 84 126", "2\n1000000000000000000 3000000000000000000"], "sample_outputs": ["9 3 6 12 4 8", "126 42 84 28", "3000000000000000000 1000000000000000000"], "notes": "NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$."}, "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 = 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "f9375003a3b64bab17176a05764c20e8"} {"nl": {"description": "The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n). For each query lj,\u2009rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj,\u2009alj\u2009+\u20091,\u2009...,\u2009arj.Help the Little Elephant to count the answers to all queries.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n).", "output_spec": "In m lines print m integers \u2014 the answers to the queries. The j-th line should contain the answer to the j-th query.", "sample_inputs": ["7 2\n3 1 2 2 3 3 7\n1 7\n3 4"], "sample_outputs": ["3\n1"], "notes": null}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val Array(n, m) = readLine().split(\" \").map(_.toInt).take(2)\n val a = readLine().split(\" \").map(_.toInt).take(n)\n\n val count = new Array[Int](n + 1)\n for(i <- a if (i <= n)) count(i) += 1\n val set = new Array[Int](500)\n\n var size = 0\n for(i <- 1 to n if (count(i) >= i)) {\n set(size) = i\n size += 1\n }\n\n val l = new Array[Int](m)\n val r = new Array[Int](m)\n val ret = new Array[Int](m)\n for(i <- 0 until m) {\n val Array(left, right) = readLine().split(\" \").map(x => x.toInt - 1)\n l(i) = left\n r(i) = right\n }\n\n for(i <- 0 until size) {\n val sum = new Array[Int](n)\n for(j <- 0 until n) {\n if (j > 0) sum(j) = sum(j - 1)\n if (set(i) == a(j)) sum(j) += 1\n }\n for(j <- 0 until m) {\n var s = sum(r(j))\n if (l(j) > 0) s -= sum(l(j) - 1)\n if (s == set(i)) ret(j) += 1\n }\n }\n println(ret.mkString(\"\\n\"))\n }\n}"}], "negative_code": [], "src_uid": "5c92ede00232d6a22385be29ecd06ddd"} {"nl": {"description": "You have $$$n$$$ sticks of the given lengths.Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.Let $$$S$$$ be the area of the rectangle and $$$P$$$ be the perimeter of the rectangle. The chosen rectangle should have the value $$$\\frac{P^2}{S}$$$ minimal possible. The value is taken without any rounding.If there are multiple answers, print any of them.Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$T \\ge 1$$$) \u2014 the number of lists of sticks in the testcase. Then $$$2T$$$ lines follow \u2014 lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th list. The first line of the pair contains a single integer $$$n$$$ ($$$4 \\le n \\le 10^6$$$) \u2014 the number of sticks in the $$$i$$$-th list. The second line of the pair contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_j \\le 10^4$$$) \u2014 lengths of the sticks in the $$$i$$$-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all $$$T$$$ lists doesn't exceed $$$10^6$$$ in each testcase.", "output_spec": "Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th list of the input. That is the lengths of the four sticks you choose from the $$$i$$$-th list, so that they form a rectangle and the value $$$\\frac{P^2}{S}$$$ of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them.", "sample_inputs": ["3\n4\n7 2 2 7\n8\n2 8 1 4 8 2 1 5\n5\n5 5 5 5 5"], "sample_outputs": ["2 7 7 2\n2 2 1 1\n5 5 5 5"], "notes": "NoteThere is only one way to choose four sticks in the first list, they form a rectangle with sides $$$2$$$ and $$$7$$$, its area is $$$2 \\cdot 7 = 14$$$, perimeter is $$$2(2 + 7) = 18$$$. $$$\\frac{18^2}{14} \\approx 23.143$$$.The second list contains subsets of four sticks that can form rectangles with sides $$$(1, 2)$$$, $$$(2, 8)$$$ and $$$(1, 8)$$$. Their values are $$$\\frac{6^2}{2} = 18$$$, $$$\\frac{20^2}{16} = 25$$$ and $$$\\frac{18^2}{8} = 40.5$$$, respectively. The minimal one of them is the rectangle $$$(1, 2)$$$.You can choose any four of the $$$5$$$ given sticks from the third list, they will form a square with side $$$5$$$, which is still a rectangle with sides $$$(5, 5)$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "Given a connected undirected graph with $$$n$$$ vertices and an integer $$$k$$$, you have to either: either find an independent set that has exactly $$$\\lceil\\frac{k}{2}\\rceil$$$ vertices. or find a simple cycle of length at most $$$k$$$. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \\le k \\le n \\le 10^5$$$, $$$n-1 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of vertices and edges in the graph, and the parameter $$$k$$$ from the statement. Each of the next $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u,v \\le n$$$) that mean there's an edge between vertices $$$u$$$ and $$$v$$$. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.", "output_spec": "If you choose to solve the first problem, then on the first line print $$$1$$$, followed by a line containing $$$\\lceil\\frac{k}{2}\\rceil$$$ distinct integers not exceeding $$$n$$$, the vertices in the desired independent set. If you, however, choose to solve the second problem, then on the first line print $$$2$$$, followed by a line containing one integer, $$$c$$$, representing the length of the found cycle, followed by a line containing $$$c$$$ distinct integers not exceeding $$$n$$$, the vertices in the desired cycle, in the order they appear in the cycle.", "sample_inputs": ["4 4 3\n1 2\n2 3\n3 4\n4 1", "4 5 3\n1 2\n2 3\n3 4\n4 1\n2 4", "4 6 3\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4", "5 4 5\n1 2\n1 3\n2 4\n2 5"], "sample_outputs": ["1\n1 3", "2\n3\n2 3 4", "2\n3\n1 2 3", "1\n1 4 5"], "notes": "NoteIn the first sample:Notice that printing the independent set $$$\\{2,4\\}$$$ is also OK, but printing the cycle $$$1-2-3-4$$$ isn't, because its length must be at most $$$3$$$.In the second sample:Notice that printing the independent set $$$\\{1,3\\}$$$ or printing the cycle $$$2-1-4$$$ is also OK.In the third sample:In the fourth sample:"}, "positive_code": [{"source_code": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n if (u < k && v < k) {\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n }\n val adjs = ajdBuilders.map(_.result())\n\n val depths, path = Array.fill(n) {\n -1\n }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n for (u <- 0 until k) {\n if (depths(u) == -1) {\n dfs1(u, 0)\n }\n }\n\n val subsetBuilders = Array.fill(2){new mutable.ArrayBuilder.ofInt}\n for (i <- 0 until k) {\n subsetBuilders(depths(i) % 2) += i + 1\n }\n val subsets = subsetBuilders.map(_.result())\n val bigger = subsets.maxBy(_.length)\n out.println(1)\n out.println(bigger.iterator.take((k + 1) / 2).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\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val depths, path = Array.fill(n) {\n -1\n }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n dfs1(0, 0)\n\n val subsetBuilders = Array.fill(2){new mutable.ArrayBuilder.ofInt}\n for (i <- 0 until n) {\n subsetBuilders(depths(i) % 2) += i + 1\n }\n val subsets = subsetBuilders.map(_.result())\n val Array(bigger, _) = subsets.sortBy(- _.length)\n out.println(1)\n out.println(bigger.iterator.take((k + 1) / 2).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\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n out.println(2)\n\n val depths, path = Array.fill(n){ -1 }\n val resBuilder = new mutable.ArrayBuilder.ofInt\n\n def dfs(u: Int, depth: Int): Unit = {\n //val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs(v, depth + 1)\n } else {\n if (depth > 0 && v != path(depth - 1) && depth - depths(v) < k) {\n var i = depth\n resBuilder += v + 1\n while (i >= 0 && path(i) != v) {\n resBuilder += path(i) + 1\n i -= 1\n }\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n new Thread(null,\n new Runnable() {\n def run(): Unit = {\n dfs(0, 0)\n }\n },\n \"1\",\n 100000000).start()\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 java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth > k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n out.println(2)\n\n val depths, path = Array.fill(n){ -1 }\n val resBuilder = new mutable.ArrayBuilder.ofInt\n\n def dfs(u: Int, depth: Int): Unit = {\n //val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs(v, depth + 1)\n } else {\n if (depth > 0 && v != path(depth - 1) && depth - depths(v) < k) {\n var j = depth\n resBuilder += v + 1\n while (j >= 0 && path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n dfs(0, 0)\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 java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth >= k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n assert(res(j) > 0)\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth > k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n assert(res(j) > 0)\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth >= k) {\n var j = 0\n val resBuilder = new mutable.ArrayBuilder.ofInt\n while (j < k) {\n resBuilder += path(j) + 1\n j += 2\n }\n val res = resBuilder.result()\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth * 2 > k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth + 2 >= k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n assert(res(j) > 0)\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n out.println(2)\n\n val depths, path = Array.fill(n){ -1 }\n val resBuilder = new mutable.ArrayBuilder.ofInt\n\n def dfs(u: Int, depth: Int): Unit = {\n //val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n if (depths(adjs(u)(i)) == -1) {\n dfs(adjs(u)(i), depth + 1)\n } else {\n val v = adjs(u)(i)\n if ((depth == 0 || v != path(depth - 1)) && depth - depths(v) < k) {\n var i = depth\n resBuilder += v + 1\n while (i >= 0 && path(i) != v) {\n resBuilder += path(i) + 1\n i -= 1\n }\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n new Thread(null,\n new Runnable() {\n def run(): Unit = {\n dfs(0, 0)\n }\n },\n \"1\",\n 100000000).start()\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 java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n out.println(2)\n\n val depths, path = Array.fill(n) {\n -1\n }\n\n def dfs(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var j = 1\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (j < k) {\n resBuilder += path(depth - j) + 1\n j += 2\n }\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n dfs(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth > k) {\n var j = 0\n val resBuilder = new mutable.ArrayBuilder.ofInt\n while (j <= k) {\n resBuilder += path(j) + 1\n j += 2\n }\n val res = resBuilder.result()\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val depths, path = Array.fill(n) {\n -1\n }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n dfs1(0, 0)\n\n val subsetBuilders = Array.fill(2){new mutable.ArrayBuilder.ofInt}\n for (i <- 0 until n) {\n subsetBuilders(depths(i) % 2) += i + 1\n }\n val subsets = subsetBuilders.map(_.result())\n subsets.sortBy(- _.length)\n out.println(1)\n out.println(subsets(0).iterator.take((k + 1) / 2).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\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth * 2 >= k) {\n var j = 0\n val resBuilder = new mutable.ArrayBuilder.ofInt\n while (j < k) {\n resBuilder += path(j) + 1\n j += 2\n }\n val res = resBuilder.result()\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val depths, path = Array.fill(n) {\n -1\n }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n dfs1(0, 0)\n\n val subsetBuilders = Array.fill(2){new mutable.ArrayBuilder.ofInt}\n for (i <- 0 until k) {\n subsetBuilders(depths(i) % 2) += i + 1\n }\n val subsets = subsetBuilders.map(_.result())\n val Array(bigger, _) = subsets.sortBy(- _.length)\n out.println(1)\n out.println(bigger.iterator.take((k + 1) / 2).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\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth + 1 >= k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n assert(res(j) > 0)\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n out.println(2)\n\n val depths, path = Array.fill(n){ -1 }\n\n def dfs(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs(v, depth + 1)\n } else {\n if (v != prev && depths(v) < depth && depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n dfs(0, 0)\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 java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth >= k) {\n var j = 0\n val resBuilder = new mutable.ArrayBuilder.ofInt\n while (j <= k) {\n resBuilder += path(j) + 1\n j += 2\n }\n val res = resBuilder.result()\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth >= k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val depths, path = Array.fill(n) {\n -1\n }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth > k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\n\n val subsetBuilders = Array.fill(2){new mutable.ArrayBuilder.ofInt}\n for (i <- 0 until n) {\n subsetBuilders(depths(i) % 2) += i + 1\n }\n val subsets = subsetBuilders.map(_.result())\n subsets.sortBy(- _.length)\n out.println(1)\n out.println(subsets(0).iterator.take((k + 1) / 2).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\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": "import java.util\n\nimport scala.collection.mutable\n\nobject D {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n\n val n, m, k = nextInt\n val ajdBuilders = Array.fill(n) {\n new mutable.ArrayBuilder.ofInt\n }\n\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n ajdBuilders(u) += v\n ajdBuilders(v) += u\n }\n val adjs = ajdBuilders.map(_.result())\n\n val vs = new java.util.TreeSet[Int]\n for (i <- 0 until n) vs.add(i)\n\n val indepBuilder = new mutable.ArrayBuilder.ofInt\n while (!vs.isEmpty) {\n val v = vs.first()\n vs.remove(v)\n indepBuilder += v + 1\n var i = 0\n while (i < adjs(v).length) {\n vs.remove(adjs(v)(i))\n i += 1\n }\n }\n\n val indep = indepBuilder.result()\n if (indep.length >= (k + 1) / 2) {\n out.println(1)\n out.println(indep.iterator.take((k + 1) / 2).mkString(\" \"))\n } else {\n val depths, path = Array.fill(n){ -1 }\n\n def dfs1(u: Int, depth: Int): Unit = {\n val prev = if (depth == 0) -1 else path(depth - 1)\n depths(u) = depth\n path(depth) = u\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs1(v, depth + 1)\n } else if (v != prev && depths(v) < depth) {\n if (depth - depths(v) < k) {\n var j = depth\n val resBuilder = new mutable.ArrayBuilder.ofInt\n resBuilder += v + 1\n while (path(j) != v) {\n resBuilder += path(j) + 1\n j -= 1\n }\n val res = resBuilder.result()\n out.println(2)\n out.println(res.length)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n }\n }\n i += 1\n }\n }\n\n def dfs2(u: Int, depth: Int): Unit = {\n depths(u) = depth\n path(depth) = u\n if (depth * 2 >= k) {\n var j = 0\n val res = Array.ofDim[Int]((k + 1) / 2)\n while (j < res.length) {\n res(j) = path(2 * j) + 1\n j += 1\n }\n out.println(1)\n out.println(res.mkString(\" \"))\n out.flush()\n System.exit(0)\n } else {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (depths(v) == -1) {\n dfs2(v, depth + 1)\n }\n i += 1\n }\n }\n }\n\n dfs1(0, 0)\n util.Arrays.fill(depths, -1)\n dfs2(0, 0)\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"}], "src_uid": "e87930c6bc4559806376b09c58e00dcc"} {"nl": {"description": "You are given $$$n$$$ words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters \"a\", \"e\", \"o\", \"i\", and \"u\" are vowels. Note that \"y\" is never vowel.For example of a beautiful lyric, \"hello hellooowww\" \"whatsup yowowowow\" is a beautiful lyric because there are two vowels each in \"hello\" and \"whatsup\", four vowels each in \"hellooowww\" and \"yowowowow\" (keep in mind that \"y\" is not a vowel), and the last vowel of each line is \"o\".For example of a not beautiful lyric, \"hey man\"\"iam mcdic\" is not a beautiful lyric because \"hey\" and \"iam\" don't have same number of vowels and the last vowels of two lines are different (\"a\" in the first and \"i\" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.", "input_spec": "The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 10^{5}$$$)\u00a0\u2014 the number of words. The $$$i$$$-th of the next $$$n$$$ lines contains string $$$s_{i}$$$ consisting lowercase alphabet letters\u00a0\u2014 the $$$i$$$-th word. It is guaranteed that the sum of the total word length is equal or less than $$$10^{6}$$$. Each word contains at least one vowel.", "output_spec": "In the first line, print $$$m$$$\u00a0\u2014 the number of maximum possible beautiful lyrics. In next $$$2m$$$ lines, print $$$m$$$ beautiful lyrics (two lines per lyric). If there are multiple answers, print any.", "sample_inputs": ["14\nwow\nthis\nis\nthe\nfirst\nmcdics\ncodeforces\nround\nhooray\ni\nam\nproud\nabout\nthat", "7\narsijo\nsuggested\nthe\nidea\nfor\nthis\nproblem", "4\nsame\nsame\nsame\ndiffer"], "sample_outputs": ["3\nabout proud\nhooray round\nwow first\nthis is\ni that\nmcdics am", "0", "1\nsame differ\nsame same"], "notes": "NoteIn the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. \"about proud hooray round\" forms a beautiful lyric because \"about\" and \"hooray\" have same number of vowels, \"proud\" and \"round\" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word \"codeforces\".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word \"same\" up to three times."}, "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\ncase class Point(x: Int, y: Int)\n\ncase class Key(num: Int, last: Int)\n\nclass Answer {\n var l1_fst: Int = -1\n var l1_snd: Int = -1\n var l2_fst: Int = -1\n var l2_snd: Int = -1\n\n override def toString: String = s\"[$l1_fst:$l1_snd,$l2_fst:$l2_snd]\"\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val W = mutable.Map[Key, ArrayBuffer[Int]]()\n val C = mutable.Map[Int, Int]().withDefaultValue(0)\n val S = Array.ofDim[String](N)\n\n val V = \"aiueo\"\n\n def keyOf(s: String) = {\n val num = s.count(a => V.contains(a))\n val i = s.lastIndexWhere(a => V.contains(a))\n Key(num, V.indexWhere(_ == s(i)))\n }\n\n REP(N) { i =>\n val s = ns()\n S(i) = s\n val key = keyOf(s)\n if (!W.contains(key)) W(key) = ArrayBuffer()\n W(key) += i\n\n C(key.num) += 1\n }\n\n debug(W.keySet.mkString(\" \"))\n debug(C.mkString(\" \"))\n\n val numPairs = C.values.map(_ / 2).sum\n val keyPairs = W.values.map(_.length / 2).sum\n debug(s\"nums:$numPairs keys:$keyPairs\")\n\n val M = min(numPairs / 2, keyPairs)\n\n val used = Array.ofDim[Boolean](N)\n val ans = ArrayBuffer[Answer]()\n\n val it = W.keys.iterator\n var m = M\n while(m > 0 && it.hasNext) {\n val k = it.next\n val w = W(k)\n val cnt = min(m, w.length / 2)\n C(k.num) -= cnt\n REP(cnt * 2) { i =>\n if (i%2 == 0) ans += new Answer\n if (i%2 == 0) ans.last.l1_snd = w(i)\n else ans.last.l2_snd = w(i)\n used(w(i)) = true\n }\n m -= cnt\n }\n\n debug(ans.mkString(\" \"))\n\n val unused = mutable.Map[Int, ArrayBuffer[Int]]()\n for {\n k <- W.keys\n v <- W(k)\n } {\n if (!used(v)) {\n if (!unused.contains(k.num)) unused(k.num) = ArrayBuffer()\n unused(k.num) += v\n }\n }\n\n var p = 0\n val it2 = unused.valuesIterator\n while(p < M && it2.hasNext) {\n val vs = it2.next()\n val cnt = min(vs.length / 2, M - p)\n REP(cnt * 2) { i =>\n if (i%2 == 0) ans(p + i/2).l1_fst = vs(i)\n else ans(p + i/2).l2_fst = vs(i)\n }\n p += cnt\n }\n\n debug(ans.mkString(\" \"))\n\n out.println(M)\n REP(M) { i =>\n val a = ans(i)\n out.println(s\"${S(a.l1_fst)} ${S(a.l1_snd)}\")\n out.println(s\"${S(a.l2_fst)} ${S(a.l2_snd)}\")\n }\n }\n}"}], "negative_code": [], "src_uid": "f06f7d0dcef10f064f5ce1e9eccf3928"} {"nl": {"description": "Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105). The second line contains the sequence of 2n positive integers a1,\u2009a2,\u2009...,\u2009a2n (1\u2009\u2264\u2009ai\u2009\u2264\u20095000) \u2014 the numbers that are written on the cards. The numbers on the line are separated by single spaces.", "output_spec": "If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line \u2014 the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.", "sample_inputs": ["3\n20 30 10 30 20 10", "1\n1 2"], "sample_outputs": ["4 2\n1 5\n6 3", "-1"], "notes": null}, "positive_code": [{"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport collection.mutable.ArrayBuffer\nimport java.lang.System\n\nobject test {\n def main(args: Array[String]): Unit = {\n val lines=Source.fromFile(\"input.txt\").getLines.toList\n val writer=new PrintWriter(new File(\"output.txt\"))\n \n val a=lines(1).split(\" \").map(x=>x.toInt)\n val arr=new Array[Int](5001)\n var sb=new StringBuffer\n \n for(i<-0 to a.length-1)\n {\n if(arr(a(i))>0)\n {\n sb.append(arr(a(i))+\" \"+(i+1)+\"\\n\")\n arr(a(i))=0\n }\n else\n {\n arr(a(i))=i+1\n }\n }\n \n arr.foreach(i=>\n {\n if(i>0)\n {\n writer.println(-1)\n writer.close()\n return\n }\n }\n )\n\n writer.println(sb)\n writer.close()\n }\n\n}"}], "negative_code": [{"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport collection.mutable.ArrayBuffer\n\nobject test {\n def main(args: Array[String]): Unit = {\n val lines=Source.fromFile(\"input.txt\").getLines.toList\n val writer=new PrintWriter(new File(\"output.txt\"))\n \n val n=lines(0).toInt\n val a=lines(1).split(\" \").map(x=>x.toInt)\n val arr=new Array[ArrayBuffer[Int]](5001)\n for(i<-0 to 5000) \n arr(i)=new ArrayBuffer[Int]()\n \n for(i<-0 to a.length-1)\n arr(a(i))+=i+1\n \n arr.foreach(i=>\n if(i.length%2==1)\n {\n writer.println(-1)\n return\n }\n )\n \n arr.foreach(i=>\n for(j<-0 to i.length/2-1)\n writer.println(i(j)+\" \"+i(j+1))\n )\n }\n\n}"}, {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport collection.mutable.ArrayBuffer\n\nobject test {\n def main(args: Array[String]): Unit = {\n val lines=Source.fromFile(\"input.txt\").getLines.toList\n val writer=new PrintWriter(new File(\"output.txt\"))\n \n val n=lines(0).toInt\n val a=lines(1).split(\" \").map(x=>x.toInt)\n val arr=new Array[ArrayBuffer[Int]](5001)\n for(i<-0 to 5000) \n arr(i)=new ArrayBuffer[Int]()\n \n for(i<-0 to a.length-1)\n arr(a(i))+=i+1\n \n arr.foreach(i=>\n if(i.length%2==1)\n {\n writer.println(-1)\n return\n }\n )\n \n arr.foreach(i=>\n for(j<-0 to i.length/2-1)\n writer.println(i(j)+\" \"+i(j+1))\n )\n \n writer.close()\n }\n\n}"}, {"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\nimport collection.mutable.ArrayBuffer\n\nobject test {\n def main(args: Array[String]): Unit = {\n val lines=Source.fromFile(\"input.txt\").getLines.toList\n val writer=new PrintWriter(new File(\"output.txt\"))\n \n val n=lines(0).toInt\n val a=lines(1).split(\" \").map(x=>x.toInt)\n val arr=new Array[ArrayBuffer[Int]](5001)\n for(i<-0 to 5000) \n arr(i)=new ArrayBuffer[Int]()\n \n for(i<-0 to a.length-1)\n arr(a(i))+=i+1\n \n arr.foreach(i=>\n if(i.length%2==1)\n {\n writer.println(-1)\n writer.close()\n return\n }\n )\n \n arr.foreach(i=>\n for(j<-0 to i.length/2-1)\n writer.println(i(j)+\" \"+i(j+1))\n )\n \n writer.close()\n }\n\n}"}], "src_uid": "0352429425782d7fe44818594eb0660c"} {"nl": {"description": "You are given three integers $$$a \\le b \\le c$$$.In one move, you can add $$$+1$$$ or $$$-1$$$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers $$$A \\le B \\le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$.You have to answer $$$t$$$ independent test cases. ", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line as three space-separated integers $$$a, b$$$ and $$$c$$$ ($$$1 \\le a \\le b \\le c \\le 10^4$$$).", "output_spec": "For each test case, print the answer. In the first line print $$$res$$$ \u2014 the minimum number of operations you have to perform to obtain three integers $$$A \\le B \\le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$. On the second line print any suitable triple $$$A, B$$$ and $$$C$$$.", "sample_inputs": ["8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46"], "sample_outputs": ["1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48"], "notes": null}, "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 val c = ni()\n\n var ans = Long.MaxValue\n var A = a\n var B = b\n var C = c\n\n REP(2 * a, 1) { f =>\n f to 2 * b by f foreach { g =>\n REP(2) { h =>\n val CC = g * (c / g) + h * g\n val p = Math.abs(f - a) + Math.abs(g - b) + Math.abs(CC - c)\n if(p < ans) {\n ans = p\n A = f\n B = g\n C = CC\n }\n }\n }\n }\n out.println(ans)\n out.println(A + \" \" + B + \" \" + C)\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 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 val c = ni()\n\n var ans = Long.MaxValue\n val ansA = Array.ofDim[Long](3)\n\n 1 to 2 * a foreach { f =>\n val u = Math.abs(f - a)\n 0 to 2 * b by f filter(f<=) foreach { g =>\n val x = (c / g).toLong\n val v = if(x * g >= b) Math.min(Math.abs(x*g-c), Math.abs((x+1)*g - c)) else if((x+1)*g >= b) Math.abs((x+1)*g - c) else -1\n if(v > -1) {\n val p =u+ Math.abs(g - b) + v\n if(p < ans) {\n ans = p\n ansA(0) = f\n ansA(1) = g\n ansA(2) = if(Math.abs(x*g - c) == v) x*g else (x+1)*g\n }\n }\n }\n }\n out.println(ans)\n out.println(ansA.mkString(\" \"))\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 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 val c = ni()\n\n var ans = Long.MaxValue\n val ansA = Array.ofDim[Long](3)\n\n 1 to 2 * a foreach { f =>\n var u = Math.abs(f - a)\n 0 to 2 * b by f filter(f<=) foreach { g =>\n val x = c / g\n val v = if(x * g >= b) Math.min(Math.abs(x*g-c), Math.abs((x+1)*g - c)) else if((x+1)*g >= b) Math.abs((x+1)*g - c) else -1\n if(v > -1) {\n val p =u+ Math.abs(g - b) + v\n if(p < ans) {\n ans = p\n ansA(0) = f\n ansA(1) = g\n ansA(2) = if(Math.abs(x*g - c) == v) x*g else (x+1)*g\n }\n }\n }\n }\n out.println(ans)\n out.println(ansA.mkString(\" \"))\n }\n }\n}\n"}], "src_uid": "140737ecea3ff1c71cdd5e51e6abf297"} {"nl": {"description": "The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters \"0\" and \"1\".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p\u2009=\u2009x\u00a0xor\u00a0y, q\u2009=\u2009x\u00a0or\u00a0y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.", "input_spec": "The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters \"0\" and \"1\". The strings are not empty, their length doesn't exceed 106.", "output_spec": "Print \"YES\" if a can be transformed into b, otherwise print \"NO\". Please do not print the quotes.", "sample_inputs": ["11\n10", "1\n01", "000\n101"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \\ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?", "input_spec": "The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \\le n \\le 10^{5}$$$, $$$1 \\le k \\le 10^{5}$$$, $$$1 \\le m \\le 10^{7}$$$)\u00a0\u2014 the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^{6}$$$)\u00a0\u2014 the initial powers of the superheroes in the cast of avengers.", "output_spec": "Output a single number\u00a0\u2014 the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["2 4 6\n4 7", "4 2 6\n1 3 2 3"], "sample_outputs": ["11.00000000000000000000", "5.00000000000000000000"], "notes": "NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each."}, "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, M = ni()\n val A = na(N)\n sort(A)\n val cum = cumSum(A)\n\n// debug(cum)\n\n var ans = cum(N).toDouble / N\n REP(N) { i =>\n // i\u4eba\u524a\u9664\n val num = N - i\n val remain = M - i // \u524a\u9664\u5f8c\u306e\u6b8b\u308a\n\n// debug(s\"$i $num $remain\")\n\n if (remain >= 0) {\n val add = min(remain, num.toLong * K)\n// debug(s\"$i $num $remain\")\n val sum = cum(N) - cum(i)\n val v = (sum + add).toDouble / num\n ans = max(v, ans)\n }\n }\n\n out.println(f\"$ans%.10f\")\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": "d6e44bd8ac03876cb03be0731f7dda3d"} {"nl": {"description": "Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then \u2014 zero or more lowercase letters.To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.", "input_spec": "The only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.", "output_spec": "Print a single number \u2014 the least number of actions needed to make the message fancy.", "sample_inputs": ["PRuvetSTAaYA", "OYPROSTIYAOPECHATALSYAPRIVETSTASYA", "helloworld"], "sample_outputs": ["5", "0", "0"], "notes": null}, "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val toUpper = new Array[Int](a.length)\n val toLower = new Array[Int](a.length)\n toUpper(0) = if (a(0).isLower) 1 else 0\n for (i <- 1 to (a.length-1)) {\n toUpper(i) = if (a(i).isLower) toUpper(i - 1) + 1 else toUpper(i - 1)\n }\n toLower(a.length-1) = if (a(a.length-1).isUpper) 1 else 0\n for (i <- (a.length-2) to 0 by -1) {\n toLower(i) = if (a(i).isUpper) toLower(i + 1) + 1 else toLower(i + 1)\n }\n\n var ans = 1000000\n for (i <- 0 to a.length) {\n var target = \n if (0 == a.length - 1) {\n math.min(toLower(0), toUpper(0))\n }\n else if (i == 0) {\n toLower(0)\n } else if (i == a.length) {\n toUpper(i-1)\n } else {\n toLower(i) + toUpper(i-1)\n }\n\n if (ans > target) {\n ans = target\n }\n }\n\n // println(toUpper.mkString(\", \"))\n // println(toLower.mkString(\", \"))\n println(ans)\n }\n}\n"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val toUpper = new Array[Int](a.length)\n val toLower = new Array[Int](a.length)\n toUpper(0) = if (a(0).isLower) 1 else 0\n for (i <- 1 to (a.length-1)) {\n toUpper(i) = if (a(i).isLower) toUpper(i - 1) + 1 else toUpper(i - 1)\n }\n toLower(a.length-1) = if (a(a.length-1).isUpper) 1 else 0\n for (i <- (a.length-2) to 0 by -1) {\n toLower(i) = if (a(i).isUpper) toLower(i + 1) + 1 else toLower(i + 1)\n }\n\n var ans = 1000000\n for (i <- 0 to a.length-1) {\n var target = \n if (0 == a.length - 1) {\n math.min(toLower(0), toUpper(0))\n }\n else if (i == 0) {\n toLower(0)\n } else if (i == a.length - 1) {\n toUpper(i)\n } else {\n toLower(i) + toUpper(i-1)\n }\n\n if (ans > target) {\n ans = target\n }\n }\n\n // println(toUpper.mkString(\", \"))\n // println(toLower.mkString(\", \"))\n println(ans)\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val toUpper = new Array[Int](a.length)\n val toLower = new Array[Int](a.length)\n toUpper(0) = if (a(0).isLower) 1 else 0\n for (i <- 1 to (a.length-1)) {\n toUpper(i) = if (a(i).isLower) toUpper(i - 1) + 1 else toUpper(i - 1)\n }\n toLower(a.length-1) = if (a(a.length-1).isUpper) 1 else 0\n for (i <- (a.length-2) to 0 by -1) {\n toLower(i) = if (a(i).isUpper) toLower(i + 1) + 1 else toLower(i + 1)\n }\n\n var ans = 1000000\n for (i <- 0 to a.length-1) {\n var target = \n if (0 == a.length - 1) {\n math.min(toLower(0), toUpper(0))\n }\n else if (i == 0) {\n toLower(0)\n } else if (i == a.length) {\n toUpper(i-1)\n } else {\n toLower(i) + toUpper(i-1)\n }\n\n if (ans > target) {\n ans = target\n }\n }\n\n // println(toUpper.mkString(\", \"))\n // println(toLower.mkString(\", \"))\n println(ans)\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val toUpper = new Array[Int](a.length)\n val toLower = new Array[Int](a.length)\n toUpper(0) = if (a(0).isLower) 1 else 0\n for (i <- 1 to (a.length-1)) {\n toUpper(i) = if (a(i).isLower) toUpper(i - 1) + 1 else toUpper(i - 1)\n }\n toLower(a.length-1) = if (a(a.length-1).isUpper) 1 else 0\n for (i <- (a.length-2) to 0 by -1) {\n toLower(i) = if (a(i).isUpper) toLower(i + 1) + 1 else toLower(i + 1)\n }\n\n var ans = 1000000\n for (i <- 0 to a.length-1) {\n var target = \n if (i == 0) {\n toLower(0)\n } else if (i == a.length - 1) {\n toUpper(i)\n } else {\n toLower(i) + toUpper(i-1)\n }\n\n if (ans > target) {\n ans = target\n }\n }\n\n // println(toUpper.mkString(\", \"))\n // println(toLower.mkString(\", \"))\n println(ans)\n }\n}\n"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val a = readLine()\n val toUpper = new Array[Int](a.length)\n val toLower = new Array[Int](a.length)\n toUpper(0) = if (a(0).isLower) 1 else 0\n for (i <- 1 to (a.length-1)) {\n toUpper(i) = if (a(i).isLower) toUpper(i - 1) + 1 else toUpper(i - 1)\n }\n toLower(a.length-1) = if (a(a.length-1).isUpper) 1 else 0\n for (i <- (a.length-2) to 0 by -1) {\n toLower(i) = if (a(i).isUpper) toLower(i + 1) + 1 else toLower(i + 1)\n }\n\n var ans = 1000000\n for (i <- 0 to a.length-1) {\n var target = \n if (i == 0) {\n toUpper(0)\n } else if (i == a.length - 1) {\n toLower(i)\n } else {\n toLower(i) + toUpper(i-1)\n }\n\n if (ans > target) {\n ans = target\n }\n }\n\n // println(toUpper.mkString(\", \"))\n // println(toLower.mkString(\", \"))\n println(ans)\n }\n}\n"}], "src_uid": "92996552cc26a05258f2f2a1eb5f8a8f"} {"nl": {"description": "Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.Recently, Kuznecov has found two strings, $$$a$$$ and $$$b$$$, of lengths $$$n$$$ and $$$m$$$ respectively. They consist of lowercase English letters and no character is contained in both strings. Let another string $$$c$$$ be initially empty. Kuznecov can do the following two types of operations: Choose any character from the string $$$a$$$, remove it from $$$a$$$, and add it to the end of $$$c$$$. Choose any character from the string $$$b$$$, remove it from $$$b$$$, and add it to the end of $$$c$$$. But, he can not do more than $$$k$$$ operations of the same type in a row. He must perform operations until either $$$a$$$ or $$$b$$$ becomes empty. What is the lexicographically smallest possible value of $$$c$$$ after he finishes?A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \\neq y$$$; in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. This is followed by the test cases description. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1\\leq n,m,k \\leq 100$$$)\u00a0\u2014 parameters from the statement. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The third line of each test case contains the string $$$b$$$ of length $$$m$$$. The strings contain only lowercase English letters. It is guaranteed that no symbol appears in $$$a$$$ and $$$b$$$ simultaneously.", "output_spec": "In each test case, output a single string $$$c$$$\u00a0\u2014 the answer to the problem.", "sample_inputs": ["3\n\n6 4 2\n\naaaaaa\n\nbbbb\n\n5 9 3\n\ncaaca\n\nbedededeb\n\n7 7 1\n\nnoskill\n\nwxhtzdy"], "sample_outputs": ["aabaabaa\naaabbcc\ndihktlwlxnyoz"], "notes": "NoteIn the first test case, it is optimal to take two 'a's from the string $$$a$$$ and add them to the string $$$c$$$. Then it is forbidden to take more characters from $$$a$$$, hence one character 'b' from the string $$$b$$$ has to be taken. Following that logic, we end up with $$$c$$$ being 'aabaabaa' when string $$$a$$$ is emptied.In the second test case it is optimal to take as many 'a's from string $$$a$$$ as possible, then take as many 'b's as possible from string $$$b$$$. In the end, we take two 'c's from the string $$$a$$$ emptying it. "}, "positive_code": [{"source_code": "\n\nobject Solution {\n import java.io.PrintWriter\n import java.util.logging.{Level, Logger}\n import scala.io.StdIn\n def getSolution(size: Int, strOne: String, strTwo: String): String = {\n val lenA = 6\n val lenB = 4\n //val size = 2\n\n // passes -> result:aabaabaa\n //var strA = \"aaaaaa\".sortWith(_ < _)\n //var strB = \"bbbb\".sortWith(_ < _)\n //val size = 2\n\n //var strA = \"caaca\".sortWith(_ < _)\n //var strB = \"bedededeb\".sortWith(_ < _)println\n //val size = 3\n val logger = Logger.getGlobal\n// logger.setLevel(Level.INFO)\n logger.setLevel(Level.OFF)\n var strA = strOne.sortWith(_ < _)\n var strB = strTwo.sortWith(_ < _)\n\n //result = \"aabaabaa\n\n var takenFromA = 0\n var takenFromB = 0\n var result = \"\"\n while(strA != \"\" && strB != \"\") {\n logger.info(\"=============================\")\n logger.info(\"result:\" + result)\n if(takenFromB != size && takenFromA != size) {\n logger.info(\"taken size is not exceeded\")\n logger.info(\"takenFromA: \" + takenFromA)\n logger.info(\"takenFromB: \" + takenFromB)\n logger.info(\"strA: \" + strA)\n logger.info(\"strB: \" + strB)\n if (strA(0) < strB(0)) {\n logger.info(\"taking from A\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n } else {\n logger.info(\"taking from B\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n } else {\n logger.info(\"!taken size for one string is exceeded\")\n var once = false\n if(takenFromB == size) {\n logger.info(\"resetting B\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n once = true\n }\n if (takenFromA == size && !once) {\n logger.info(\"resetting A\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n }\n\n }\n result\n }\n\n def main(args: Array[String]) {\n val N = StdIn.readLine().toInt\n\n for (i <- 0 until N) {\n val size = StdIn.readLine().split(\" \")(2).toInt\n val strOne = StdIn.readLine\n val strTwo = StdIn.readLine\n\n println(getSolution(size, strOne, strTwo))\n }\n }\n}\n\n"}], "negative_code": [{"source_code": "\n\nobject Solution {\n import java.io.PrintWriter\n import java.util.logging.{Level, Logger}\n import scala.io.StdIn\n def getSolution(size: Int, strOne: String, strTwo: String): String = {\n val lenA = 6\n val lenB = 4\n //val size = 2\n\n // passes -> result:aabaabaa\n //var strA = \"aaaaaa\".sortWith(_ < _)\n //var strB = \"bbbb\".sortWith(_ < _)\n //val size = 2\n\n //var strA = \"caaca\".sortWith(_ < _)\n //var strB = \"bedededeb\".sortWith(_ < _)println\n //val size = 3\n val logger = Logger.getGlobal\n// logger.setLevel(Level.INFO)\n logger.setLevel(Level.OFF)\n var strA = strOne.sortWith(_ < _)\n var strB = strTwo.sortWith(_ < _)\n\n //result = \"aabaabaa\n\n var takenFromA = 0\n var takenFromB = 0\n var result = \"\"\n while(strA != \"\" && strB != \"\") {\n logger.info(\"=============================\")\n logger.info(\"result:\" + result)\n if(takenFromB != size && takenFromA != size) {\n logger.info(\"taken size is not exceeded\")\n logger.info(\"takenFromA: \" + takenFromA)\n logger.info(\"takenFromB: \" + takenFromB)\n logger.info(\"strA: \" + strA)\n logger.info(\"strB: \" + strB)\n if (strA(0) < strB(0)) {\n logger.info(\"taking from A\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n } else {\n logger.info(\"taking from B\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n } else {\n logger.info(\"!taken size for one string is exceeded\")\n var once = false\n if(takenFromB == size) {\n logger.info(\"resetting B\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n once = true\n }\n if (takenFromA == size && !once) {\n logger.info(\"resetting A\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n }\n\n }\n result\n }\n\n def main(args: Array[String]) {\n println(\"started\")\n val N = StdIn.readLine().toInt\n\n for (i <- 0 until N) {\n val size = StdIn.readLine().split(\" \")(2).toInt\n val strOne = StdIn.readLine\n val strTwo = StdIn.readLine\n\n println(getSolution(size, strOne, strTwo))\n }\n }\n}\n\n"}, {"source_code": "object Solution {\n import java.io.PrintWriter\n import java.util.logging.{Level, Logger}\n import scala.io.StdIn\n\n def getSolution(size: Int, strOne: String, strTwo: String): String = {\n val lenA = 6\n val lenB = 4\n\n val logger = Logger.getGlobal\n //logger.setLevel(Level.INFO)\n logger.setLevel(Level.OFF)\n var strA = strOne.sortWith(_ < _)\n var strB = strTwo.sortWith(_ < _)\n\n\n var takenFromA = 0\n var takenFromB = 0\n var result = \"\"\n while(strA != \"\" && strB != \"\") {\n logger.info(\"=============================\")\n logger.info(\"result:\" + result)\n if(takenFromB != size && takenFromA != size) {\n logger.info(\"taken size is not exceeded\")\n logger.info(\"takenFromA: \" + takenFromA)\n logger.info(\"takenFromB: \" + takenFromB)\n logger.info(\"strA: \" + strA)\n logger.info(\"strB: \" + strB)\n if (strA(0) < strB(0)) {\n logger.info(\"taking from A\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n } else {\n logger.info(\"taking from B\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n } else {\n logger.info(\"!taken size for one string is exceeded\")\n var once = false\n if(takenFromB == size) {\n logger.info(\"resetting B\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n once = true\n }\n if (takenFromA == size) {\n logger.info(\"resetting A\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n }\n\n }\n result\n }\n\n def main(args: Array[String]) {\n val N = StdIn.readLine().toInt\n\n for (i <- 0 until N) {\n val size = StdIn.readLine().split(\" \")(2).toInt\n val strOne = StdIn.readLine\n val strTwo = StdIn.readLine\n\n println(getSolution(size, strOne, strTwo))\n }\n }\n}"}, {"source_code": "object Solution {\n import java.io.PrintWriter\n import java.util.logging.{Level, Logger}\n import scala.io.StdIn\n\n def getSolution(size: Int, strOne: String, strTwo: String): String = {\n val lenA = 6\n val lenB = 4\n\n val logger = Logger.getGlobal\n //logger.setLevel(Level.INFO)\n logger.setLevel(Level.OFF)\n var strA = strOne.sortWith(_ < _)\n var strB = strTwo.sortWith(_ < _)\n\n\n var takenFromA = 0\n var takenFromB = 0\n var result = \"\"\n while(strA != \"\" && strB != \"\") {\n logger.info(\"=============================\")\n logger.info(\"result:\" + result)\n if(takenFromB != size && takenFromA != size) {\n logger.info(\"taken size is not exceeded\")\n logger.info(\"takenFromA: \" + takenFromA)\n logger.info(\"takenFromB: \" + takenFromB)\n logger.info(\"strA: \" + strA)\n logger.info(\"strB: \" + strB)\n if (strA(0) < strB(0)) {\n logger.info(\"taking from A\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n } else {\n logger.info(\"taking from B\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n } else {\n logger.info(\"!taken size for one string is exceeded\")\n if(takenFromB == size) {\n logger.info(\"resetting B\")\n result = result + strA(0)\n strA = strA.drop(1)\n takenFromA = takenFromA + 1\n takenFromB = 0\n }\n if (takenFromA == size) {\n logger.info(\"resetting A\")\n result = result + strB(0)\n strB = strB.drop(1)\n takenFromB = takenFromB + 1\n takenFromA = 0\n }\n }\n\n }\n result\n }\n\n def main(args: Array[String]) {\n val N = StdIn.readLine().toInt\n\n for (i <- 0 until N) {\n val size = StdIn.readLine().split(\" \")(2).toInt\n val strOne = StdIn.readLine\n val strTwo = StdIn.readLine\n\n println(getSolution(size, strOne, strTwo))\n }\n }\n}"}], "src_uid": "1d46a356c5515f8894cbb83e438cc544"} {"nl": {"description": "In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network\u00a0\u2014 for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety\u00a0\u2014 in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009400, 0\u2009\u2264\u2009m\u2009\u2264\u2009n(n\u2009-\u20091)\u2009/\u20092)\u00a0\u2014 the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, u\u2009\u2260\u2009v). You may assume that there is at most one railway connecting any two towns.", "output_spec": "Output one integer\u00a0\u2014 the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output \u2009-\u20091.", "sample_inputs": ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"], "sample_outputs": ["2", "-1", "3"], "notes": "NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing $$$n$$$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $$$i$$$, he will have to fight $$$k_i$$$ monsters in a row: first a monster with armor $$$a_{i, 1}$$$, then a monster with armor $$$a_{i, 2}$$$ and so on, finally, a monster with armor $$$a_{i, k_i}$$$.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by $$$1$$$.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of caves. The $$$i$$$-th of the next $$$n$$$ lines contains an integer $$$k_i$$$ ($$$1 \\le k_i \\le 10^5$$$)\u00a0\u2014 the number of monsters in the $$$i$$$-th cave, followed by $$$k_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \\ldots, a_{i, k_i}$$$ ($$$1 \\le a_{i, j} \\le 10^9$$$)\u00a0\u2014 armor levels of the monsters in cave $$$i$$$ in order the hero has to fight them. It is guaranteed that the sum of $$$k_i$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.", "sample_inputs": ["2\n1\n1 42\n2\n3 10 15 8\n2 12 11"], "sample_outputs": ["43\n13"], "notes": "NoteIn the first test case, the hero has to beat a single monster with armor $$$42$$$, it's enough to have power $$$43$$$ to achieve that.In the second test case, the hero can pass the level with initial power $$$13$$$ as follows: enter cave $$$2$$$: beat a monster with armor $$$12$$$, power increases to $$$14$$$; beat a monster with armor $$$11$$$, power increases to $$$15$$$; enter cave $$$1$$$: beat a monster with armor $$$10$$$, power increases to $$$16$$$; beat a monster with armor $$$15$$$, power increases to $$$17$$$; beat a monster with armor $$$8$$$, power increases to $$$18$$$. "}, "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 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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.You may choose at most one consecutive subarray of $$$a$$$ and multiply all values contained in this subarray by $$$x$$$. You want to maximize the beauty of array after applying at most one such operation.", "input_spec": "The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 3 \\cdot 10^5, -100 \\le x \\le 100$$$) \u2014 the length of array $$$a$$$ and the integer $$$x$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$) \u2014 the array $$$a$$$.", "output_spec": "Print one integer \u2014 the maximum possible beauty of array $$$a$$$ after multiplying all values belonging to some consecutive subarray $$$x$$$.", "sample_inputs": ["5 -2\n-3 8 -2 1 -6", "12 -3\n1 3 3 7 1 3 3 7 1 3 3 7", "5 10\n-1 -2 -3 -4 -5"], "sample_outputs": ["22", "42", "0"], "notes": "NoteIn the first test case we need to multiply the subarray [-2, 1, -6], and the array becomes [-3, 8, 4, -2, 12] with beauty 22 ([-3, 8, 4, -2, 12]).In the second test case we don't need to multiply any subarray at all.In the third test case no matter which subarray we multiply, the beauty of array will be equal to 0."}, "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.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, X = ni()\n val A = nal(N)\n val B = Array.ofDim[Long](N)\n REP(N) { i =>\n B(i) = A(i) * X\n }\n val R = calcLRMax(B, A)\n val L = calcLRMax(B.reverse, A.reverse).reverse\n\n debug(\"L\")\n debug(L)\n debug(\"R\")\n debug(R)\n\n var ans = 0L\n REP(N) { i =>\n val v = R(i) + (if (i > 0) L(i - 1) else 0)\n ans = max(ans, v)\n }\n\n out.println(ans)\n }\n\n /**\n * LR\u306e\u5f62\u3092\u4f5c\u308b\u5834\u5408\u306e\u3001[i, j) {i <= j <= N} \u306e\u7bc4\u56f2\u306esum\u306e\u6700\u5927\u5024\n */\n def calcLRMax(L: Array[Long], R: Array[Long]): Array[Long] = {\n val n = L.length\n val dp = Array.ofDim[Long](2, n + 1) // 0: L, 1: R\n REP_r(n) { i =>\n val ll = L(i) + dp(0)(i + 1) // L + L\n val lr = L(i) + dp(1)(i + 1) // L + R\n val l = L(i) // L + 0\n dp(0)(i) = max(max(ll, lr), l)\n val rr = R(i) + dp(1)(i + 1) // R + R\n val r = R(i) // R + 0\n dp(1)(i) = max(rr, r)\n }\n val A = Array.ofDim[Long](n)\n REP(n) { i =>\n // 0, L, R\n A(i) = max(0, max(dp(0)(i), dp(1)(i)))\n }\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 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[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": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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, X = ni()\n val A = nal(N)\n val B = Array.ofDim[Long](N)\n REP(N) { i =>\n B(i) = A(i) * X\n }\n\n // i\u304b\u3089\u9023\u7d9a\u3057\u305f\u90e8\u5206\u5217\u3092\u8db3\u3057\u305f\u6642\u306b\u3001\u4e00\u756a\u5927\u304d\u304f\u306a\u308b\u5024\n def mkMax(as: Array[Long]): Array[Long] = {\n val cum = cumSum(as)\n val res = Array.ofDim[Long](as.length)\n var mx = cum.last\n REP_r(as.length) { i =>\n mx = max(mx, cum(i + 1))\n res(i) = mx - cum(i)\n }\n res\n }\n\n def maxSubSum(as: Array[Long]): Long = {\n var ms = 0L\n var sum = 0L\n var res = 0L\n REP(as.length) { i =>\n sum += as(i)\n ms = min(ms, sum)\n res = max(res, sum - ms)\n }\n res\n }\n\n debug(s\"maxSubSumA:${maxSubSum(A)} maxSubSumB:${maxSubSum(B)}\")\n\n // \u30eb\u30fc\u30d7\u3067\u4e21\u7aef\u304c0\u306e\u30b1\u30fc\u30b9\u3092\u30ab\u30d0\u30fc\u3057\u3066\u306a\u3044\u306e\u3067\u3053\u3053\u3067\u3084\u308b\n var ans = max(maxSubSum(A), maxSubSum(B))\n\n val max_A_R = mkMax(A)\n reverse(A)\n val max_A_L = mkMax(A)\n reverse(max_A_L)\n val max_B_R = mkMax(B)\n reverse(B)\n val max_B_L = mkMax(B)\n reverse(max_B_L)\n\n debug(max_A_R)\n debug(max_A_L)\n debug(max_B_R)\n debug(max_B_L)\n\n // \u4e21\u7aef\u3092\u5fc5\u305a\u542b\u3080\n TO(0, N - 2) { i =>\n val ba = max_A_R(i + 1) + max_B_L(i)\n val ab = max_A_L(i) + max_B_R(i + 1)\n debug(s\"i:$i ab:$ab ba:$ba\")\n ans = max(ans, max(ba, ab))\n }\n\n out.println(ans)\n }\n\n def reverse(as: Array[Long]): 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 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[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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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, X = ni()\n val A = nal(N)\n val B = Array.ofDim[Long](N)\n REP(N) { i =>\n B(i) = A(i) * X\n }\n\n // B\u306b\u3057\u305f\u65b9\u304c\u5f97\u306a\u5ea6\u5408\u3044\n val C = Array.ofDim[Long](N)\n REP(N) { i =>\n C(i) = B(i) - A(i)\n }\n\n debug(C)\n\n def maxSubSum(as: Array[Long]): (Int, Int) = {\n var sum = 0L\n var ms = 0L\n var mx = 0L\n var ms_ix = -1\n var ans: (Int, Int) = (-1, -1)\n REP(as.length) { i =>\n sum += as(i)\n if (sum < ms) {\n ms = sum\n ms_ix = i\n }\n if (sum - ms > mx) {\n mx = sum - ms\n ans = (ms_ix + 1, i)\n }\n }\n ans\n }\n\n debug(maxSubSum(C).toString)\n\n var ans = 0L\n val (bl, br) = maxSubSum(C)\n // ABA\u306e\u30b1\u30fc\u30b9\n if (bl != -1 && br != -1) {\n TO(bl, br) { i =>\n ans += B(i)\n }\n\n debug(ans.toString)\n // \u4e21\u7aef\u306b\u5e83\u304c\u308b\n var rsum = 0L\n var rmax = 0L\n TO(br + 1, N - 1) { i =>\n rsum += A(i)\n rmax = max(rmax, rsum)\n }\n var lsum = 0L\n var lmax = 0L\n REP_r(bl) { i =>\n lsum += A(i)\n lmax = max(lmax, lsum)\n }\n\n debug(s\"lmax:$lmax rmax:$rmax\")\n ans += lmax + rmax\n }\n\n // B\u304c\u306a\u3044\u30b1\u30fc\u30b9\n val (al, ar) = maxSubSum(A)\n if (al != -1 && ar != -1) {\n var sum = 0L\n TO(al, ar) { i => sum += A(i) }\n ans = max(ans, sum)\n }\n\n out.println(ans)\n }\n\n def reverse(as: Array[Long]): 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 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[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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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, X = ni()\n val A = nal(N)\n val B = Array.ofDim[Long](N)\n REP(N) { i =>\n B(i) = A(i) * X\n }\n\n // B\u306b\u3057\u305f\u65b9\u304c\u5f97\u306a\u5ea6\u5408\u3044\n val C = Array.ofDim[Long](N)\n REP(N) { i =>\n C(i) = B(i) - A(i)\n }\n\n // i\u304b\u3089\u9023\u7d9a\u3057\u305f\u90e8\u5206\u5217\u3092\u8db3\u3057\u305f\u6642\u306b\u3001\u4e00\u756a\u5927\u304d\u304f\u306a\u308bj\n def mkMax(as: Array[Long]): Array[(Int, Long)] = {\n val cum = cumSum(as)\n val res = Array.ofDim[(Int, Long)](as.length)\n var j = as.length - 1\n REP_r(as.length) { i =>\n if (cum(j + 1) < cum(i + 1)) j = i\n res(i) = (j, cum(j + 1) - cum(i))\n }\n res\n }\n\n def maxSubSum(as: Array[Long]): Long = {\n var sum = 0L\n var ms = 0L\n var mx = 0L\n REP(as.length) { i =>\n sum += as(i)\n if (sum < ms) {\n ms = sum\n }\n if (sum - ms > mx) {\n mx = sum - ms\n }\n }\n mx\n }\n\n // B\u304c\u306a\u3044\u5834\u5408\n var ans = maxSubSum(A)\n\n val max_C = mkMax(C).map(_._1)\n\n val max_A = mkMax(A).map(_._2)\n reverse(A)\n val max_A_rev = mkMax(A).map(_._2)\n reverse(max_A_rev)\n val cumB = cumSum(B)\n\n debug(max_A)\n debug(max_A_rev)\n\n // ABA\n REP(N) { l =>\n val r = max_C(l)\n val la = if (l > 0) max_A_rev(l - 1) else 0\n val ra = if (r < N - 1) max_A(r + 1) else 0\n val b = cumB(r + 1) - cumB(l)\n ans = max(ans, la + b + ra)\n }\n\n out.println(ans)\n }\n\n def reverse(as: Array[Long]): 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 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[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}"}], "src_uid": "92b6ab47c306a15631f045d624a1bf37"} {"nl": {"description": "There are $$$n$$$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $$$1$$$ to $$$n$$$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $$$i$$$ ($$$1 \\leq i \\leq n$$$) will decide to go for boiled water at minute $$$t_i$$$.Tank with a boiled water is located to the left of the $$$1$$$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $$$p$$$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the $$$i$$$-th seat wants to go for a boiled water, he will first take a look on all seats from $$$1$$$ to $$$i - 1$$$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $$$i$$$ are busy, he will go to the tank.There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.Your goal is to find for each passenger, when he will receive the boiled water for his noodles.", "input_spec": "The first line contains integers $$$n$$$ and $$$p$$$ ($$$1 \\leq n \\leq 100\\,000$$$, $$$1 \\leq p \\leq 10^9$$$)\u00a0\u2014 the number of people and the amount of time one person uses the tank. The second line contains $$$n$$$ integers $$$t_1, t_2, \\dots, t_n$$$ ($$$0 \\leq t_i \\leq 10^9$$$)\u00a0\u2014 the moments when the corresponding passenger will go for the boiled water.", "output_spec": "Print $$$n$$$ integers, where $$$i$$$-th of them is the time moment the passenger on $$$i$$$-th seat will receive his boiled water.", "sample_inputs": ["5 314\n0 310 942 628 0"], "sample_outputs": ["314 628 1256 942 1570"], "notes": "NoteConsider the example.At the $$$0$$$-th minute there were two passengers willing to go for a water, passenger $$$1$$$ and $$$5$$$, so the first passenger has gone first, and returned at the $$$314$$$-th minute. At this moment the passenger $$$2$$$ was already willing to go for the water, so the passenger $$$2$$$ has gone next, and so on. In the end, $$$5$$$-th passenger was last to receive the boiled water."}, "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 Event(t: Long, tpe: Int, i: Int) // 0: \u623b\u308b, 1: \u8179\u6e1b\u308b, 2: waiting\u51e6\u7406\n\n class Queue(n: Int) {\n private val as = Array.ofDim[Int](n)\n var p = 0\n var cur = 0\n\n def +=(a: Int): Unit = {\n as(p) = a\n p += 1\n }\n\n def dequeue(): Int = {\n val a = as(cur)\n cur += 1\n a\n }\n\n def head: Int = as(cur)\n\n def apply(i: Int): Int = as(cur + i)\n\n def length: Int = p - cur\n def isEmpty: Boolean = length == 0\n def nonEmpty: Boolean = !isEmpty\n\n def mkString(delimiter: String = \"\"): String = as.slice(cur, cur + length).mkString(delimiter)\n}\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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\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 \u304cLong\u3068\u304b\u3058\u3083\u306a\u3044\u5834\u5408\u306f\u3053\u308c\u3089\u3092\u5b9f\u88c5\u3057\u306a\u3044\u3068\u4e0b\u306e\u5974\u3089\u304c\u4f7f\u3048\u306a\u3044\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 class LongMinHeap(n: Int) {\n private val N = Integer.highestOneBit(n - 1) + 1 << 1\n private val heap = Array.ofDim[Long](N) // 1-indexed\n private var p = 0\n\n private def up(i: Int): Unit = {\n if (i >= 2) {\n val p = i / 2\n if (heap(i) < heap(p)) {\n val tmp = heap(p)\n heap(p) = heap(i)\n heap(i) = tmp\n up(p)\n }\n }\n }\n\n private def minchild(i: Int): Int = {\n if (i * 2 + 1 > p) {\n i * 2\n } else {\n if (heap(i * 2) < heap(i * 2 + 1)) i * 2\n else i * 2 + 1\n }\n }\n\n private def down(i: Int): Unit = {\n if (i * 2 <= p) {\n val mc = minchild(i)\n if (heap(i) > heap(mc)) {\n val tmp = heap(mc)\n heap(mc) = heap(i)\n heap(i) = tmp\n down(mc)\n }\n }\n }\n\n def add(x: Long): Unit = {\n p += 1\n heap(p) = x\n up(p)\n }\n\n def removeMin(): Unit = {\n heap(1) = heap(p)\n p -= 1\n down(1)\n }\n\n def min: Long = heap(1)\n def apply(i: Int): Long = heap(i + 1)\n def length: Int = p\n def toArray: Array[Long] = heap.slice(1, p + 1)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n import java.util\n import java.util.Comparator\n val n, p = ni()\n val t = na(n)\n\n // \u30a4\u30d9\u30f3\u30c8\u30ad\u30e5\u30fc\n val E = new util.TreeSet[Event](new Comparator[Event] {\n override def compare(o1: Event, o2: Event): Int = {\n if (o1.t == o2.t) {\n if (o1.tpe == o2.tpe) {\n Integer.compare(o1.i, o2.i) // \u5de6\u5074\u512a\u5148\n } else {\n Integer.compare(o1.tpe, o2.tpe)\n }\n }\n else java.lang.Long.compare(o1.t, o2.t)\n }\n })\n REP(n) { i =>\n E.add(Event(t(i), 1, i))\n }\n val q = new Queue(n) // \u6c34\u98f2\u307f\u30ad\u30e5\u30fc\n val bit = new BIT(n) // \u5e2d\u304c\u7a7a\u3044\u3066\u3044\u308b\u304b\n val waitings = new LongMinHeap(n) // \u5e2d\u3067\u5f85\u3063\u3066\u3044\u308b\u4eba\n\n def processWaiting(t: Long): Unit = {\n // \u4e00\u756a\u5de6\u304c\u3060\u3081\u3067\u3001\uff12\u4eba\u3081\u4ee5\u964d\u304c\u5927\u4e08\u592b\u3063\u3066\u3053\u3068\u306f\u3042\u308a\u3048\u306a\u3044\n if (waitings.length > 0) {\n val next = waitings.min.toInt\n if (bit.sum(next) == 0) {\n waitings.removeMin()\n bit.add(next, 1)\n debug(s\"water($t:$next)\")\n q += next\n if (q.length == 1) {\n E.add(Event(t + p, 0, -1))\n }\n }\n }\n }\n\n val ans = Array.ofDim[Long](n)\n while(!E.isEmpty) {\n val e = E.pollFirst()\n if (e.tpe == 1) {\n debug(s\"addWait(${e.t}:${e.i})\")\n waitings.add(e.i)\n E.add(Event(e.t, 2, -1))\n } else if (e.tpe == 0) {\n val ret = q.dequeue()\n debug(s\"return(${e.t}:$ret)\")\n ans(ret) = e.t\n bit.add(ret, -1)\n E.add(Event(e.t, 2, -1))\n if (q.nonEmpty) {\n E.add(Event(e.t + p, 0, -1))\n }\n } else {\n processWaiting(e.t)\n }\n }\n out.println(ans.mkString(\" \"))\n }\n}"}], "negative_code": [], "src_uid": "7cd09ca9008c23117d98a365be31440e"} {"nl": {"description": "You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.", "input_spec": "The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \\le n,k \\le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$, the elements of the array.", "output_spec": "Print the minimum non-zero element before each operation in a new line.", "sample_inputs": ["3 5\n1 2 3", "4 2\n10 3 5 3"], "sample_outputs": ["1\n1\n1\n0\n0", "3\n2"], "notes": "NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2."}, "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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \\times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the initial heights of the parts of the wall.", "output_spec": "Print \"YES\" if Vova can complete the wall using any amount of bricks (possibly zero). Print \"NO\" otherwise.", "sample_inputs": ["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10", "3\n1 2 3"], "sample_outputs": ["YES", "YES", "YES", "NO"], "notes": "NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete."}, "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.util\n val N = ni()\n val A = na(N)\n REP(N) { i =>\n A(i) = A(i) % 2\n }\n val set = new java.util.TreeSet[Integer]()\n REP(N) { i =>\n set.add(i)\n }\n\n val q = new util.ArrayDeque[Integer]()\n\n var i = 0\n while(i < N - 1) {\n if (A(i) == A(i + 1)) {\n set.remove(i)\n set.remove(i + 1)\n q.add(i - 1)\n i += 1\n }\n i += 1\n }\n\n while(!q.isEmpty) {\n val pos = q.poll()\n if (set.contains(pos)) {\n val pos2 = set.higher(pos)\n if (pos2 != null && A(pos) == A(pos2)) {\n set.remove(pos)\n set.remove(pos2)\n val prev = set.lower(pos)\n if (prev != null) q.add(prev)\n }\n }\n }\n\n val ok = set.size() < 2\n\n if (ok) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n\n /**\n * \u6700\u5927M\u500b\u306e\u30b0\u30eb\u30fc\u30d7\u306b\u5206\u5272\u3057\u3066\u30b0\u30eb\u30fc\u30d7\u6bce\u306e\u914d\u5217\u306b\u5165\u308c\u308b\n */\n def grouped(N: Int, M: Int, g: Array[Int], v: Array[Int]): Array[Array[Int]] = {\n val cnt = Array.ofDim[Int](M)\n val C = Array.ofDim[Array[Int]](M)\n REP(N) { i =>\n cnt(g(i)) += 1\n }\n REP(M) { i =>\n C(i) = new Array(cnt(i))\n }\n REP_r(N) { i =>\n cnt(g(i)) -= 1\n C(g(i))(cnt(g(i))) = v(i)\n }\n C\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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 = na(N)\n val set = new java.util.TreeSet[Integer]()\n REP(N) { i =>\n set.add(i)\n }\n\n val P = mutable.Map[Int, java.util.PriorityQueue[Integer]]()\n REP_r(N) { i =>\n if (!P.contains(A(i))) P(A(i)) = new java.util.PriorityQueue[Integer]()\n P(A(i)).add(i)\n }\n val nums = new java.util.PriorityQueue[Integer]()\n P.keys.foreach(k => nums.add(k))\n\n def ok: Boolean = {\n // \u4e00\u756a\u5927\u304d\u3044\u9ad8\u3055\u306f\u8003\u616e\u3057\u306a\u304f\u3066\u3044\u3044\n val mx = nums.size + 2\n var i = 0\n while(!nums.isEmpty && i < mx) {\n val num = nums.poll()\n val p = P(num)\n var addNext = false\n while(!p.isEmpty) {\n if (p.size() == 1) {\n if (!P.contains(num + 2)) P(num + 2) = new java.util.PriorityQueue[Integer]()\n P(num + 2).add(p.poll())\n addNext = true\n } else {\n val p1 = p.poll()\n val p2 = p.poll()\n if (set.higher(p1) == p2) {\n set.remove(p1)\n set.remove(p2)\n } else {\n if (!P.contains(num + 2)) P(num + 2) = new java.util.PriorityQueue[Integer]()\n P(num + 2).add(p1)\n P(num + 2).add(p2)\n addNext = true\n }\n }\n }\n\n if (addNext) nums.add(num + 2)\n\n i += 1\n }\n\n nums.size() <= 1\n }\n\n if (ok) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n\n /**\n * \u6700\u5927M\u500b\u306e\u30b0\u30eb\u30fc\u30d7\u306b\u5206\u5272\u3057\u3066\u30b0\u30eb\u30fc\u30d7\u6bce\u306e\u914d\u5217\u306b\u5165\u308c\u308b\n */\n def grouped(N: Int, M: Int, g: Array[Int], v: Array[Int]): Array[Array[Int]] = {\n val cnt = Array.ofDim[Int](M)\n val C = Array.ofDim[Array[Int]](M)\n REP(N) { i =>\n cnt(g(i)) += 1\n }\n REP(M) { i =>\n C(i) = new Array(cnt(i))\n }\n REP_r(N) { i =>\n cnt(g(i)) -= 1\n C(g(i))(cnt(g(i))) = v(i)\n }\n C\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "bb4ecfaaccd538e23f883a18f9672af8"} {"nl": {"description": "Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types \u2014 shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $$$a$$$ sticks and $$$b$$$ diamonds?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \\le a, b \\le 10^9$$$)\u00a0\u2014 the number of sticks and the number of diamonds, respectively.", "output_spec": "For each test case print one integer \u2014 the maximum number of emeralds Polycarp can earn.", "sample_inputs": ["4\n4 4\n1000000000 0\n7 15\n8 7"], "sample_outputs": ["2\n0\n7\n5"], "notes": "NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything."}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers: $$$n_0$$$ \u2014 the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$; $$$n_1$$$ \u2014 the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$; $$$n_2$$$ \u2014 the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$\"1110011110\", the following substrings would be written: \"11\", \"11\", \"10\", \"00\", \"01\", \"11\", \"11\", \"11\", \"10\". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \\le n_0, n_1, n_2 \\le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.", "output_spec": "Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.", "sample_inputs": ["7\n1 3 5\n1 1 1\n3 9 3\n0 1 0\n3 1 2\n0 0 3\n2 0 0"], "sample_outputs": ["1110011110\n0011\n0110001100101011\n10\n0000111\n1111\n000"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "In the evening Polycarp decided to analyze his today's travel expenses on public transport.The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b\u2009<\u2009a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.For example, if Polycarp made three consecutive trips: \"BerBank\" \"University\", \"University\" \"BerMall\", \"University\" \"BerBank\", then he payed a\u2009+\u2009b\u2009+\u2009a\u2009=\u20092a\u2009+\u2009b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards?", "input_spec": "The first line contains five integers n,\u2009a,\u2009b,\u2009k,\u2009f (1\u2009\u2264\u2009n\u2009\u2264\u2009300, 1\u2009\u2264\u2009b\u2009<\u2009a\u2009\u2264\u2009100, 0\u2009\u2264\u2009k\u2009\u2264\u2009300, 1\u2009\u2264\u2009f\u2009\u2264\u20091000) where: n \u2014 the number of Polycarp trips, a \u2014 the cost of a regualar single trip, b \u2014 the cost of a trip after a transshipment, k \u2014 the maximum number of travel cards Polycarp can buy, f \u2014 the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space \u2014 the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different.", "output_spec": "Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards.", "sample_inputs": ["3 5 3 1 8\nBerBank University\nUniversity BerMall\nUniversity BerBank", "4 2 1 300 1000\na A\nA aa\naa AA\nAA a"], "sample_outputs": ["11", "5"], "notes": "NoteIn the first example Polycarp can buy travel card for the route \"BerBank University\" and spend 8 burles. Note that his second trip \"University\" \"BerMall\" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8\u2009+\u20093\u2009=\u200911 burles.In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u20095 burles."}, "positive_code": [{"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 var (n, a, b, k, f) = (in.next.toInt, in.next.toInt, in.next.toInt, in.next.toInt, in.next.toInt)\n val map = HashMap[String, Int]()\n var last : String = \"\";\n for(i <- 0 until n){\n var (from, to) = (in.next, in.next)\n var cost = if(last == from) b else a\n last = to\n var key = if(from > to) from + to else to + from\n map.put(key, map.getOrElse(key, 0) + cost)\n }\n var ans = 0\n map.values.toList.sorted.reverse.foreach((e) => {\n if(e > f && k > 0){\n k -= 1\n ans += f\n }else{\n ans += e\n }\n })\n println(ans)\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"}], "negative_code": [], "src_uid": "dc93c41e70c7eb82af407359b194d28a"} {"nl": {"description": "Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer: If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\\frac{3a}{2}$$$; If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 10^4$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x, y \\le 10^9$$$) \u2014 the current number and the number that Petya wants to get.", "output_spec": "For the $$$i$$$-th test case print the answer on it \u2014 YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["7\n2 3\n1 1\n3 6\n6 8\n1 2\n4 1\n31235 6578234"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO\nYES\nYES"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1\u2009=\u20093,\u2009r1\u2009=\u20096,\u2009k1\u2009=\u20091 then the answer is abbacaa. If after that we would process the query l2\u2009=\u20091,\u2009r2\u2009=\u20094,\u2009k2\u2009=\u20092 then we would get the string baabcaa.", "input_spec": "The first line of the input contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u200910\u2009000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009300)\u00a0\u2014 the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009|s|,\u20091\u2009\u2264\u2009ki\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the description of the i-th query.", "output_spec": "Print the resulting string s after processing all m queries.", "sample_inputs": ["abacaba\n2\n3 6 1\n1 4 2"], "sample_outputs": ["baabcaa"], "notes": "NoteThe sample is described in problem statement."}, "positive_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: 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "A multi-subject competition is coming! The competition has $$$m$$$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has $$$n$$$ candidates. For the $$$i$$$-th person he knows subject $$$s_i$$$ the candidate specializes in and $$$r_i$$$ \u2014 a skill level in his specialization (this level can be negative!). The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same.Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition).", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le m \\le 10^5$$$) \u2014 the number of candidates and the number of subjects. The next $$$n$$$ lines contains two integers per line: $$$s_i$$$ and $$$r_i$$$ ($$$1 \\le s_i \\le m$$$, $$$-10^4 \\le r_i \\le 10^4$$$) \u2014 the subject of specialization and the skill level of the $$$i$$$-th candidate.", "output_spec": "Print the single integer \u2014 the maximum total sum of skills of delegates who form a valid delegation (according to rules above) or $$$0$$$ if every valid non-empty delegation has negative sum.", "sample_inputs": ["6 3\n2 6\n3 6\n2 5\n3 5\n1 9\n3 1", "5 3\n2 6\n3 6\n2 5\n3 5\n1 11", "5 2\n1 -1\n1 -5\n2 -1\n2 -1\n1 -10"], "sample_outputs": ["22", "23", "0"], "notes": "NoteIn the first example it's optimal to choose candidates $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, so two of them specialize in the $$$2$$$-nd subject and other two in the $$$3$$$-rd. The total sum is $$$6 + 6 + 5 + 5 = 22$$$.In the second example it's optimal to choose candidates $$$1$$$, $$$2$$$ and $$$5$$$. One person in each subject and the total sum is $$$6 + 6 + 11 = 23$$$.In the third example it's impossible to obtain a non-negative sum."}, "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, r) = na2(N)\n rep(N) { i => s(i) -= 1 }\n\n val cnt = Array.ofDim[Int](M)\n val cumR = Array.ofDim[Array[Long]](M)\n rep(N) { i =>\n cnt(s(i)) += 1\n }\n rep(M) { i =>\n cumR(i) = new Array(cnt(i))\n }\n rep(N) { i =>\n cnt(s(i)) -= 1\n cumR(s(i))(cnt(s(i))) = r(i)\n }\n\n var len = 0\n rep(M) { i =>\n val R = cumR(i)\n len = max(len, R.length)\n Sorting.quickSort(R)\n\n // reverse\n rep(R.length / 2) { j =>\n val t = R(j)\n R(j) = R(R.length - 1 - j)\n R(R.length - 1 - j) = t\n }\n\n rep(R.length - 1, 1) { j =>\n R(j) += R(j - 1)\n }\n }\n Sorting.quickSort(cumR)(Ordering.by(_.length))\n\n var ans = 0L\n var l = 0\n rep(len, 1) { k =>\n var sum = 0L\n while(l < M && cumR(l).length < k) l += 1\n if (l < M) {\n l until M foreach { i =>\n if (cumR(i)(k - 1) > 0) sum += cumR(i)(k - 1)\n }\n ans = max(ans, sum)\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}"}], "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 (s, r) = na2(N)\n rep(N) { i => s(i) -= 1 }\n\n val cnt = Array.ofDim[Int](M)\n val cumR = Array.ofDim[Array[Int]](M)\n rep(N) { i =>\n cnt(s(i)) += 1\n }\n rep(M) { i =>\n cumR(i) = new Array(cnt(i))\n }\n rep(N) { i =>\n cnt(s(i)) -= 1\n cumR(s(i))(cnt(s(i))) = r(i)\n }\n\n var len = 0\n rep(M) { i =>\n val R = cumR(i)\n len = max(len, R.length)\n Sorting.quickSort(R)\n\n // reverse\n rep(R.length / 2) { j =>\n val t = R(j)\n R(j) = R(R.length - 1 - j)\n R(R.length - 1 - j) = t\n }\n\n rep(R.length - 1, 1) { j =>\n R(j) += R(j - 1)\n }\n }\n Sorting.quickSort(cumR)(Ordering.by(_.length))\n\n var ans = 0\n var l = 0\n rep(len, 1) { k =>\n var sum = 0\n while(l < M && cumR(l).length < k) l += 1\n if (l < M) {\n l until M foreach { i =>\n sum += cumR(i)(k - 1)\n }\n ans = max(ans, sum)\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}\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 (s, r) = na2(N)\n rep(N) { i => s(i) -= 1 }\n\n val cnt = Array.ofDim[Int](M)\n val cumR = Array.ofDim[Array[Long]](M)\n rep(N) { i =>\n cnt(s(i)) += 1\n }\n rep(M) { i =>\n cumR(i) = new Array(cnt(i))\n }\n rep(N) { i =>\n cnt(s(i)) -= 1\n cumR(s(i))(cnt(s(i))) = r(i)\n }\n\n var len = 0\n rep(M) { i =>\n val R = cumR(i)\n len = max(len, R.length)\n Sorting.quickSort(R)\n\n // reverse\n rep(R.length / 2) { j =>\n val t = R(j)\n R(j) = R(R.length - 1 - j)\n R(R.length - 1 - j) = t\n }\n\n rep(R.length - 1, 1) { j =>\n R(j) += R(j - 1)\n }\n }\n Sorting.quickSort(cumR)(Ordering.by(_.length))\n\n var ans = 0L\n var l = 0\n rep(len, 1) { k =>\n var sum = 0L\n while(l < M && cumR(l).length < k) l += 1\n if (l < M) {\n l until M foreach { i =>\n sum += cumR(i)(k - 1)\n }\n ans = max(ans, sum)\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}"}], "src_uid": "cb688cc52bd2bf0af77084dc4a25c28b"} {"nl": {"description": "In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1,\u2009a2,\u2009...,\u2009an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.", "input_spec": "The first line contains two integers n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) and m (1\u2009\u2264\u2009m\u2009\u2264\u2009109)\u00a0\u2014 the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the types of toys that Tanya already has.", "output_spec": "In the first line print a single integer k\u00a0\u2014 the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1,\u2009t2,\u2009...,\u2009tk (1\u2009\u2264\u2009ti\u2009\u2264\u2009109)\u00a0\u2014 the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.", "sample_inputs": ["3 7\n1 3 4", "4 14\n4 6 12 8"], "sample_outputs": ["2\n2 5", "4\n7 2 3 1"], "notes": "NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys."}, "positive_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).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}"}, {"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"}, {"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 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"}], "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"} {"nl": {"description": "Paprika loves permutations. She has an array $$$a_1, a_2, \\dots, a_n$$$. She wants to make the array a permutation of integers $$$1$$$ to $$$n$$$.In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers $$$i$$$ ($$$1 \\le i \\le n$$$) and $$$x$$$ ($$$x > 0$$$), then perform $$$a_i := a_i \\bmod x$$$ (that is, replace $$$a_i$$$ by the remainder of $$$a_i$$$ divided by $$$x$$$). In different operations, the chosen $$$i$$$ and $$$x$$$ can be different.Determine the minimum number of operations needed to make the array a permutation of integers $$$1$$$ to $$$n$$$. If it is impossible, output $$$-1$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$. ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output the minimum number of operations needed to make the array a permutation of integers $$$1$$$ to $$$n$$$, or $$$-1$$$ if it is impossible.", "sample_inputs": ["4\n2\n1 7\n3\n1 5 4\n4\n12345678 87654321 20211218 23571113\n9\n1 2 3 4 18 19 5 6 7"], "sample_outputs": ["1\n-1\n4\n2"], "notes": "NoteFor the first test, the only possible sequence of operations which minimizes the number of operations is: Choose $$$i=2$$$, $$$x=5$$$. Perform $$$a_2 := a_2 \\bmod 5 = 2$$$. For the second test, it is impossible to obtain a permutation of integers from $$$1$$$ to $$$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\n\nobject Solution extends App {\n\n //=====Solution=========\n val testNumber = readInt()\n 1.to(testNumber).foreach { _ =>\n val integerNumber = readInt()\n val numbers = readInts()\n\n val remainingNumbers = new MutableMultiSet[Int](numbers)\n\n @tailrec\n def findAnswer(testNumber: Int, answer: Int): Int = (testNumber, answer) match {\n case (0, answer) => answer\n case (testNumber, -1) => findAnswer(testNumber - 1, -1)\n case (testNumber, answer) => if (remainingNumbers.contains(testNumber)) {\n remainingNumbers.remove(testNumber)\n findAnswer(testNumber - 1, answer)\n } else {\n val maxValue = remainingNumbers.max\n if (maxValue >= testNumber * 2 + 1) {\n remainingNumbers.remove(maxValue)\n findAnswer(testNumber - 1, answer + 1)\n } else {\n findAnswer(testNumber - 1, - 1)\n }\n }\n }\n\n println(findAnswer(integerNumber, 0))\n }\n\n\n\n\n\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 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": "85ad953161bb8841eed7c47a66381688"} {"nl": {"description": "During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $$$n$$$ high school students numbered from $$$1$$$ to $$$n$$$. Initially, each student $$$i$$$ is on position $$$i$$$. Each student $$$i$$$ is characterized by two numbers\u00a0\u2014 $$$a_i$$$ and $$$b_i$$$. Dissatisfaction of the person $$$i$$$ equals the product of $$$a_i$$$ by the number of people standing to the left of his position, add the product $$$b_i$$$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $$$i$$$, which is on the position $$$j$$$, equals $$$a_i \\cdot (j-1) + b_i \\cdot (n-j)$$$.The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.Although Stas is able to solve such problems, this was not given to him. He turned for help to you.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the number of people in the queue. Each of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq 10^8$$$)\u00a0\u2014 the characteristic of the student $$$i$$$, initially on the position $$$i$$$.", "output_spec": "Output one integer\u00a0\u2014 minimum total dissatisfaction which can be achieved by rearranging people in the queue.", "sample_inputs": ["3\n4 2\n2 3\n6 1", "4\n2 4\n3 3\n7 1\n2 3", "10\n5 10\n12 4\n31 45\n20 55\n30 17\n29 30\n41 32\n7 1\n5 5\n3 15"], "sample_outputs": ["12", "25", "1423"], "notes": "NoteIn the first example it is optimal to put people in this order: ($$$3, 1, 2$$$). The first person is in the position of $$$2$$$, then his dissatisfaction will be equal to $$$4 \\cdot 1+2 \\cdot 1=6$$$. The second person is in the position of $$$3$$$, his dissatisfaction will be equal to $$$2 \\cdot 2+3 \\cdot 0=4$$$. The third person is in the position of $$$1$$$, his dissatisfaction will be equal to $$$6 \\cdot 0+1 \\cdot 2=2$$$. The total dissatisfaction will be $$$12$$$.In the second example, you need to put people in this order: ($$$3, 2, 4, 1$$$). The total dissatisfaction will be $$$25$$$."}, "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.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 import java.util.Comparator\n val N = ni()\n val (a, b) = na2(N)\n case class Entry(v: Int, pos: Int)\n\n val E = Array.ofDim[Entry](N)\n REP(N) { i =>\n E(i) = Entry(b(i) - a(i), i)\n }\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)\n })\n debug(E.mkString(\" \"))\n\n var ans = 0L\n REP(N) { i =>\n val p = E(i).pos\n val j = i + 1\n debug(s\"a:${a(p)} b:${b(p)}, j:$j (j - 1):${(j - 1)} (N - j):${(N - j)}\")\n ans += a(p).toLong * (j - 1) + b(p).toLong * (N - j)\n debug(s\"ans:$ans\")\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[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": "028e83d83cc99a2b3826627efd87a304"} {"nl": {"description": "For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \\le j < d$$$ and $$$d < j \\le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \\le j \\le n$$$.Help mayor find the earliest not-so-rainy day of summer.", "input_spec": "The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 100\\,000$$$, $$$0 \\le x, y \\le 7$$$)\u00a0\u2014 the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.", "output_spec": "Print a single integer\u00a0\u2014 the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.", "sample_inputs": ["10 2 2\n10 9 6 7 8 3 2 1 4 5", "10 2 3\n10 9 6 7 8 3 2 1 4 5", "5 5 5\n100000 10000 1000 100 10"], "sample_outputs": ["3", "8", "5"], "notes": "NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"}, {"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"}], "negative_code": [], "src_uid": "5e2a5ee02c1a2f35a52e76cde96463a3"} {"nl": {"description": "You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i.\u00a0e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\\sum\\limits_{i = 1}^{n}{n^{n - i} \\cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$; $$$p_i \\neq p_j$$$ if $$$i \\neq j$$$)\u00a0\u2014 values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.", "sample_inputs": ["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"], "sample_outputs": ["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"], "notes": "NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \\cdot 4 + 4^2 \\cdot 3 + 4^1 \\cdot 2 + 4^0 \\cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \\cdot 5 + 5^3 \\cdot 2 + 5^2 \\cdot 4 + 5^1 \\cdot 3 + 5^0 \\cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \\cdot 6 + 6^4 \\cdot 1 + 6^3 \\cdot 5 + 6^2 \\cdot 3 + 6^1 \\cdot 4 + 6^0 \\cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$."}, "positive_code": [{"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 res = new mutable.ArrayBuilder.ofInt\n\n val sorted = new java.util.TreeMap[Int, Int]\n for (i <- ps.indices) {\n sorted.put(ps(i), i)\n }\n var right = n\n while (!sorted.isEmpty) {\n val idx = sorted.lastEntry().getValue\n for (i <- idx until right) {\n res += ps(i)\n sorted.remove(ps(i))\n }\n right = idx\n }\n\n out.println(res.result().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": "1637670255f8bd82a01e2ab20cdcc9aa"} {"nl": {"description": "In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k\u2009+\u20091 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j\u2009-\u2009i|. Help Farmer John protect his cows by calculating this minimum possible distance.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009k\u2009<\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k\u2009+\u20091 characters of this string are '0', so there exists at least one possible choice of k\u2009+\u20091 rooms for Farmer John and his cows to stay in.", "output_spec": "Print the minimum possible distance between Farmer John's room and his farthest cow.", "sample_inputs": ["7 2\n0100100", "5 1\n01010", "3 2\n000"], "sample_outputs": ["2", "2", "1"], "notes": "NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems \u2014 Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems \u2014 Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \\le t_i \\le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \\le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \\le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both \"mandatory\" and \"non-mandatory\" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.", "input_spec": "The first line contains the integer $$$m$$$ ($$$1 \\le m \\le 10^4$$$)\u00a0\u2014 the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \\le n \\le 2\\cdot10^5$$$, $$$1 \\le T \\le 10^9$$$, $$$1 \\le a < b \\le 10^9$$$)\u00a0\u2014 the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \\le t_i \\le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\\cdot10^5$$$.", "output_spec": "Print the answers to $$$m$$$ test cases. For each set, print a single integer\u00a0\u2014 maximal number of points that he can receive, before leaving the exam.", "sample_inputs": ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"], "sample_outputs": ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"], "notes": null}, "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 class Entry(var easy: Int, var hard: 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N, T = ni()\n val A, B = nl()\n val isEasy = na(N).map(_ == 0)\n val cntE = isEasy.count(identity)\n val cntH = N - cntE\n val E = new java.util.TreeMap[Int, Entry]\n REP(N) { i =>\n val t = ni()\n if (!E.containsKey(t)) {\n E.put(t, new Entry(0, 0))\n }\n if (isEasy(i)) E.get(t).easy += 1\n else E.get(t).hard += 1\n }\n\n val n = E.size()\n val cumE, cumH = Array.ofDim[Int](n + 1)\n var i = 0\n val it = E.entrySet().iterator()\n val time = Array.ofDim[Int](n)\n while(it.hasNext) {\n val e = it.next()\n cumE(i + 1) = cumE(i) + e.getValue.easy\n cumH(i + 1) = cumH(i) + e.getValue.hard\n time(i) = e.getKey\n i += 1\n }\n debug(cumE)\n debug(cumH)\n debug(time)\n\n var ans = 0\n\n def calc(lst: Int, manT: Long, cumE: Int, cumH: Int): Int = {\n var remainT = lst - manT\n var v = cumE + cumH\n debug(s\"manT:$manT lst:$lst remainT:$remainT v:$v\")\n if (remainT >= 0) {\n val remainE = cntE - cumE\n val cnt = min(remainE, (remainT / A).toInt)\n v += cnt\n remainT -= A * cnt\n if (remainT >= 0) {\n val remainH = cntH - cumH\n val cnt = min(remainH, (remainT / B).toInt)\n v += cnt\n remainT -= B * cnt\n }\n v\n } else {\n 0\n }\n }\n\n // [0, t1)\u306e\u30b1\u30fc\u30b9\n ans = max(ans, calc(time(0)-1, 0, 0, 0))\n REP(n) { i =>\n val manT = cumE(i + 1) * A + cumH(i + 1) * B\n val lst = if (i == n - 1) T else time(i + 1) - 1\n ans = max(ans, calc(lst, manT, cumE(i + 1), cumH(i + 1)))\n }\n out.println(ans)\n }\n }\n}"}], "negative_code": [], "src_uid": "6c165390c7f9fee059ef197ef40ae64f"} {"nl": {"description": "Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things: The maximum beauty difference of flowers that Pashmak can give to Parmida. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way. ", "input_spec": "The first line of the input contains n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). In the next line there are n space-separated integers b1, b2, ..., bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.", "sample_inputs": ["2\n1 2", "3\n1 4 5", "5\n3 1 2 3 1"], "sample_outputs": ["1 1", "4 1", "2 4"], "notes": "NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this: choosing the first and the second flowers; choosing the first and the fifth flowers; choosing the fourth and the second flowers; choosing the fourth and the fifth flowers. "}, "positive_code": [{"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": "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 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"}, {"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}"}, {"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": "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}"}], "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"} {"nl": {"description": "Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \\leq l \\leq r \\leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \\leq x, k \\leq n$$$, $$$l \\leq x < x + 2k \\leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.", "input_spec": "The first line contains the string $$$s$$$ ($$$1 \\leq |s| \\leq 300\\,000$$$), consisting of zeros and ones.", "output_spec": "Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \\leq l \\leq r \\leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \\leq x, k \\leq n$$$, $$$l \\leq x < x + 2k \\leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.", "sample_inputs": ["010101", "11001100"], "sample_outputs": ["3", "0"], "notes": "NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$."}, "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\n def isBad(l: Int, r: Int): Boolean = {\n var x = l\n var good = false\n while (x < r && !good) {\n var k = 1\n while (x + k + k < r && !good) {\n if (s(x) == s(x + k) && s(x) == s(x + k + k)) good = true\n k += 1\n }\n x += 1\n }\n !good\n }\n\n var res = s.length.toLong * (s.length - 1) / 2\n\n for (l <- 0 until s.length) {\n for (len <- 2 until 20) {\n if (l + len <= s.length && isBad(l, l + len)) {\n res -= 1\n }\n }\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "71bace75df1279ae55a6e755159d4191"} {"nl": {"description": "A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of dice in the tower. The second line contains an integer x (1\u2009\u2264\u2009x\u2009\u2264\u20096) \u2014 the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20096;\u00a0ai\u2009\u2260\u2009bi) \u2014 the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.", "output_spec": "Print \"YES\" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print \"NO\" (without the quotes).", "sample_inputs": ["3\n6\n3 2\n5 4\n2 4", "3\n3\n2 6\n4 1\n5 3"], "sample_outputs": ["YES", "NO"], "notes": null}, "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}"}, {"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 }"}], "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"} {"nl": {"description": "Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called \"Black Square\" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1,\u2009a2,\u2009a3,\u2009a4. Calculate how many calories Jury needs to destroy all the squares?", "input_spec": "The first line contains four space-separated integers a1, a2, a3, a4 (0\u2009\u2264\u2009a1,\u2009a2,\u2009a3,\u2009a4\u2009\u2264\u2009104). The second line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105), where the \u0456-th character of the string equals \"1\", if on the i-th second of the game the square appears on the first strip, \"2\", if it appears on the second strip, \"3\", if it appears on the third strip, \"4\", if it appears on the fourth strip.", "output_spec": "Print a single integer \u2014 the total number of calories that Jury wastes.", "sample_inputs": ["1 2 3 4\n123214", "1 5 3 2\n11221"], "sample_outputs": ["13", "13"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $$$1 + 3$$$ using the calculator, he gets $$$2$$$ instead of $$$4$$$. But when he tries computing $$$1 + 4$$$, he gets the correct answer, $$$5$$$. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders! So, when he tries to compute the sum $$$a + b$$$ using the calculator, he instead gets the xorsum $$$a \\oplus b$$$ (read the definition by the link: https://en.wikipedia.org/wiki/Exclusive_or).As he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers $$$l$$$ and $$$r$$$, how many pairs of integers $$$(a, b)$$$ satisfy the following conditions: $$$$$$a + b = a \\oplus b$$$$$$ $$$$$$l \\leq a \\leq r$$$$$$ $$$$$$l \\leq b \\leq r$$$$$$However, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of testcases. Then, $$$t$$$ lines follow, each containing two space-separated integers $$$l$$$ and $$$r$$$ ($$$0 \\le l \\le r \\le 10^9$$$).", "output_spec": "Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer to the $$$i$$$-th testcase.", "sample_inputs": ["3\n1 4\n323 323\n1 1000000"], "sample_outputs": ["8\n0\n3439863766"], "notes": "Note$$$a \\oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$.For the first testcase, the pairs are: $$$(1, 2)$$$, $$$(1, 4)$$$, $$$(2, 1)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$, $$$(4, 1)$$$, $$$(4, 2)$$$, and $$$(4, 3)$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val l, r = ni()\n val memo = Array.fill[Long](31, 2, 2, 2, 2)(-1)\n def dfs(i: Int, moreA: Int, lessA: Int, moreB: Int, lessB: Int): Long = {\n if (i == -1) return 1\n if (memo(i)(moreA)(lessA)(moreB)(lessB) == -1) {\n var v = 0L\n REP(2) { a =>\n REP(2) { b =>\n val err = a == 1 && b == 1 ||\n lessA == 0 && (r>>i&1) == 0 && a == 1 ||\n moreA == 0 && (l>>i&1) == 1 && a == 0 ||\n lessB == 0 && (r>>i&1) == 0 && b == 1 ||\n moreB == 0 && (l>>i&1) == 1 && b == 0\n if (!err) v += dfs(i - 1,\n moreA | (if((l>>i&1) == 0 && a == 1) 1 else 0),\n lessA | (if((r>>i&1) == 1 && a == 0) 1 else 0),\n moreB | (if((l>>i&1) == 0 && b == 1) 1 else 0),\n lessB | (if((r>>i&1) == 1 && b == 0) 1 else 0))\n }\n }\n memo(i)(moreA)(lessA)(moreB)(lessB) = v\n }\n memo(i)(moreA)(lessA)(moreB)(lessB)\n }\n out.println(dfs(30, 0, 0, 0, 0))\n }\n }\n}"}], "negative_code": [], "src_uid": "d418db46dd3aa411836774a4cc7f73d7"} {"nl": {"description": "Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of boys and girls in the dancing room.", "output_spec": "In the first line print k \u2014 the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.", "sample_inputs": ["2 1", "2 2"], "sample_outputs": ["2\n1 1\n2 1", "3\n1 1\n1 2\n2 2"], "notes": "NoteIn test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).And in test case 2, we have 2 boys with 2 girls, the answer is 3."}, "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\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 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}"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "You have a simple undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.Let's make a definition.Let $$$v_1$$$ and $$$v_2$$$ be two some nonempty subsets of vertices that do not intersect. Let $$$f(v_{1}, v_{2})$$$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $$$v_1$$$. There are no edges with both endpoints in vertex set $$$v_2$$$. For every two vertices $$$x$$$ and $$$y$$$ such that $$$x$$$ is in $$$v_1$$$ and $$$y$$$ is in $$$v_2$$$, there is an edge between $$$x$$$ and $$$y$$$. Create three vertex sets ($$$v_{1}$$$, $$$v_{2}$$$, $$$v_{3}$$$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $$$f(v_{1}, v_{2})$$$, $$$f(v_{2}, v_{3})$$$, $$$f(v_{3}, v_{1})$$$ are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \\le n \\le 10^{5}$$$, $$$0 \\le m \\le \\text{min}(3 \\cdot 10^{5}, \\frac{n(n-1)}{2})$$$)\u00a0\u2014 the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \\le a_{i} \\lt b_{i} \\le n$$$)\u00a0\u2014 it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.", "output_spec": "If the answer exists, print $$$n$$$ integers. $$$i$$$-th integer means the vertex set number (from $$$1$$$ to $$$3$$$) of $$$i$$$-th vertex. Otherwise, print $$$-1$$$. If there are multiple answers, print any.", "sample_inputs": ["6 11\n1 2\n1 3\n1 4\n1 5\n1 6\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"], "sample_outputs": ["1 2 2 3 3 3", "-1"], "notes": "NoteIn the first example, if $$$v_{1} = \\{ 1 \\}$$$, $$$v_{2} = \\{ 2, 3 \\}$$$, and $$$v_{3} = \\{ 4, 5, 6 \\}$$$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like \"2 3 3 1 1 1\" will be accepted as well. In the second example, it's impossible to make such vertex sets."}, "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, m = nextInt\n val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n\n for (i <- 1 to m) {\n val u, v = nextInt - 1\n// val u = i - 1\n// val v = i\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n val adjs = adjBuilders.map(_.result())\n\n val colors = Array.fill(n)(0)\n val queue = mutable.Queue(0)\n val enqueued = Array.fill(n)(false)\n enqueued(0) = true\n\n while (queue.nonEmpty) {\n val u = queue.dequeue()\n var i = 0\n var has1, has2, has3 = false\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n colors(v) match {\n case 1 => has1 = true\n case 2 => has2 = true\n case 3 => has3 = true\n case _ =>\n }\n i += 1\n }\n if (!has1) colors(u) = 1\n else if (!has2) colors(u) = 2\n else if (!has3) colors(u) = 3\n else colors(u) = -1\n i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (colors(v) == 0 && !enqueued(v)) {\n enqueued(v) = true\n queue += v\n }\n i += 1\n }\n }\n\n val counts = colors.groupBy(identity).map {\n case (c, v) => c -> v.length\n }.withDefaultValue(0)\n\n if (counts(-1) > 0 || counts(0) > 0) out.println(-1)\n else {\n var ok = counts(1) > 0 && counts(2) > 0 && counts(3) > 0\n for (u <- 0 until n) {\n var i = 0\n var c1, c2, c3 = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n colors(v) match {\n case 1 => c1 += 1\n case 2 => c2 += 1\n case 3 => c3 += 1\n case _ => ok = false\n }\n i += 1\n }\n if ((colors(u) == 1 || c1 == counts(1)) &&\n (colors(u) == 2 || c2 == counts(2)) &&\n (colors(u) == 3 || c3 == counts(3))) ()\n else ok = false\n }\n if (ok) out.println(colors.mkString(\" \"))\n else println(-1)\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": "7dea96a7599946a5b5d0b389c7e76651"} {"nl": {"description": "A row of $$$n$$$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $$$\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}$$$ and as $$$\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}$$$.During use, the stamp must completely fit on the given $$$n$$$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture $$$\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}\\color{blue}{\\texttt{B}}\\texttt{W}$$$ could be $$$\\texttt{WWWWW} \\to \\texttt{WW}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}}\\texttt{W} \\to \\color{brown}{\\underline{\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}}}\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}\\texttt{W} \\to \\color{blue}{\\texttt{B}}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}}\\color{blue}{\\texttt{B}}\\texttt{W}$$$. Here $$$\\texttt{W}$$$, $$$\\color{red}{\\texttt{R}}$$$, and $$$\\color{blue}{\\texttt{B}}$$$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the length of the picture. The second line of each test case contains a string $$$s$$$\u00a0\u2014 the picture you need to make. It is guaranteed that the length of $$$s$$$ is $$$n$$$ and that $$$s$$$ only consists of the characters $$$\\texttt{W}$$$, $$$\\texttt{R}$$$, and $$$\\texttt{B}$$$, representing a white, red, or blue cell, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output \"YES\" if it possible to make the picture using the stamp zero or more times, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["12\n5\nBRBBW\n1\nB\n2\nWB\n2\nRW\n3\nBRB\n3\nRBB\n7\nWWWWWWW\n9\nRBWBWRRBW\n10\nBRBRBRBRRB\n12\nBBBRWWRRRWBR\n10\nBRBRBRBRBW\n5\nRBWBW"], "sample_outputs": ["YES\nNO\nNO\nNO\nYES\nYES\nYES\nNO\nYES\nNO\nYES\nNO"], "notes": "NoteThe first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is \"NO\".For the fifth test case, you can use the stamp as follows: $$$\\texttt{WWW} \\to \\texttt{W}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}} \\to \\color{brown}{\\underline{\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}}}\\color{blue}{\\texttt{B}}$$$.For the sixth test case, you can use the stamp as follows: $$$\\texttt{WWW} \\to \\texttt{W}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}} \\to \\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}}\\color{blue}{\\texttt{B}}$$$.For the seventh test case, you don't need to use the stamp at all."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "3f284afb044c8a57a02cd015d06e0ef0"} {"nl": {"description": "A string is called square if it is some string written twice in a row. For example, the strings \"aa\", \"abcabc\", \"abab\" and \"baabaa\" are square. But the strings \"aaa\", \"abaaab\" and \"abcdabc\" are not square.For a given string $$$s$$$ determine if it is square.", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $$$1$$$ and $$$100$$$ inclusive.", "output_spec": "For each test case, output on a separate line: YES if the string in the corresponding test case is square, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["10\na\naa\naaa\naaaa\nabab\nabcabc\nabacaba\nxxyy\nxyyx\nxyxy"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES\nYES\nNO\nNO\nNO\nYES"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "After lessons Nastya decided to read a book. The book contains $$$n$$$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $$$k$$$ as the first page which was not read (i.e. she read all pages from the $$$1$$$-st to the $$$(k-1)$$$-th).The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the number of chapters in the book. There are $$$n$$$ lines then. The $$$i$$$-th of these lines contains two integers $$$l_i$$$, $$$r_i$$$ separated by space ($$$l_1 = 1$$$, $$$l_i \\leq r_i$$$)\u00a0\u2014 numbers of the first and the last pages of the $$$i$$$-th chapter. It's guaranteed that $$$l_{i+1} = r_i + 1$$$ for all $$$1 \\leq i \\leq n-1$$$, and also that every chapter contains at most $$$100$$$ pages. The $$$(n+2)$$$-th line contains a single integer $$$k$$$ ($$$1 \\leq k \\leq r_n$$$)\u00a0\u2014 the index of the marked page. ", "output_spec": "Print a single integer\u00a0\u2014 the number of chapters which has not been completely read so far.", "sample_inputs": ["3\n1 3\n4 7\n8 11\n2", "3\n1 4\n5 9\n10 12\n9", "1\n1 7\n4"], "sample_outputs": ["3", "2", "1"], "notes": "NoteIn the first example the book contains $$$11$$$ pages and $$$3$$$ chapters\u00a0\u2014 $$$[1;3]$$$, $$$[4;7]$$$ and $$$[8;11]$$$. Nastya marked the $$$2$$$-nd page, so she finished in the middle of the $$$1$$$-st chapter. So, all chapters has not been read so far, so the answer is $$$3$$$.The book in the second example contains $$$12$$$ pages and $$$3$$$ chapters too, but Nastya finished reading in the middle of the $$$2$$$-nd chapter, so that the answer is $$$2$$$."}, "positive_code": [{"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"}, {"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 // \u3053\u306e\u30c1\u30e3\u30d7\u30bf\u30fc\u304b\u3089\u5148\u306f\u8aad\u3093\u3067\u3044\u306a\u3044\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"} {"nl": {"description": "Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.", "input_spec": "First line of input contains string s, consisting only of lowercase Latin letters (1\u2009\u2264\u2009|s|\u2009\u2264\u20091000, |s| denotes the length of s). Second line of input contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u200926).", "output_spec": "Print single line with a minimum number of necessary changes, or the word \u00abimpossible\u00bb (without quotes) if it is impossible.", "sample_inputs": ["yandex\n6", "yahoo\n5", "google\n7"], "sample_outputs": ["0", "1", "impossible"], "notes": "NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a',\u2009'h',\u2009'o',\u2009'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6."}, "positive_code": [{"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, w, ans, m, x, c, k, n, j, i: Int = 0\n var a = new Array[Int](26)\n var line: String = in.nextLine()\n n = in.nextInt()\n len = line.length()\n if (len < n) println(\"impossible\")\n else {\n for (i <- 0 to 25) a(i) = 0\n m = 0\n for (i <- 0 to len - 1) a(line(i) - 'a') += 1\n for (i <- 0 to 25) if (a(i) > 0) m += 1\n w = n - m\n if (w<0) w=0\n println(w)\n }\n }\n}"}], "negative_code": [{"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, w, ans, m, x, c, k, n, j, i: Int = 0\n var a = new Array[Int](26)\n var line: String = in.nextLine()\n n = in.nextInt()\n len = line.length()\n if (len < n) println(\"impossible\")\n else {\n for (i <- 0 to 25) a(i) = 0\n m = 0\n for (i <- 0 to len - 1) a(line(i) - 'a') += 1\n for (i <- 0 to 25) if (a(i) > 0) m += 1\n w = n - m\n println(w)\n }\n }\n}"}], "src_uid": "bd5912fe2c5c37658f28f6b159b39645"} {"nl": {"description": "Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.", "input_spec": "The first line contains three integers n, c and d (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 0\u2009\u2264\u2009c,\u2009d\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of fountains, the number of coins and diamonds Arkady has. The next n lines describe fountains. Each of these lines contain two integers bi and pi (1\u2009\u2264\u2009bi,\u2009pi\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the beauty and the cost of the i-th fountain, and then a letter \"C\" or \"D\", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively.", "output_spec": "Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0.", "sample_inputs": ["3 7 6\n10 8 C\n4 3 C\n5 6 D", "2 4 5\n2 5 C\n2 1 D", "3 10 10\n5 5 C\n5 5 C\n10 11 D"], "sample_outputs": ["9", "0", "10"], "notes": "NoteIn the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9.In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins. "}, "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 def readLongs(n: Int) = { val tl = tokenizeLine; 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, d) = readInts(3)\n\n case class Fountain(b: Int, p: Int)\n\n val fontsCBuilder, fontsDBuilder = new mutable.ArrayBuilder.ofRef[Fountain]()\n\n for (_ <- 0 until n) {\n val s = readLine\n val tok = new java.util.StringTokenizer(s)\n val f = Fountain(tok.nextToken.toInt, tok.nextToken.toInt)\n if (s.last == 'C') fontsCBuilder += f else fontsDBuilder += f\n }\n\n val fontsC = fontsCBuilder.result.sortBy(_.p)\n\n val fontsD = fontsDBuilder.result.sortBy(_.p)\n\n var maxForC = 0\n for (fc <- fontsC) {\n if (fc.p <= c && fc.b > maxForC) maxForC = fc.b\n }\n\n var maxForD = 0\n for (fd <- fontsD) {\n if (fd.p <= d && fd.b > maxForD) maxForD = fd.b\n }\n\n val resCD = if (maxForC > 0 && maxForD > 0) maxForC + maxForD else 0\n\n def solve(fonts: Array[Fountain], limit: Int): Int = {\n var left = 0\n var right = fonts.length - 1\n var maxLeft = 0\n var res = 0\n\n while (left < right) {\n val rightP = fonts(right).p\n val rightB = fonts(right).b\n while (left < right && fonts(left).p + rightP <= limit) {\n if (fonts(left).b > maxLeft) maxLeft = fonts(left).b\n left += 1\n }\n if (rightP <= limit && maxLeft > 0 && rightB + maxLeft > res) res = rightB + maxLeft\n right -= 1\n }\n\n left = 1\n maxLeft = 0\n while (left <= right) {\n if (fonts(left - 1).b > maxLeft) maxLeft = fonts(left - 1).b\n if (fonts(left).b + maxLeft > res) res = fonts(left).b + maxLeft\n left += 1\n }\n\n res\n }\n\n val resCC = solve(fontsC, c)\n val resDD = solve(fontsD, d)\n\n println(resCD max resCC max resDD)\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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, d) = readInts(3)\n\n case class Fountain(id: Int, b: Int, p: Int)\n\n val fontsCBuilder, fontsDBuilder = new mutable.ArrayBuilder.ofRef[Fountain]()\n\n for (i <- 0 until n) {\n val s = readLine\n val tok = new java.util.StringTokenizer(s)\n val f = Fountain(i, tok.nextToken.toInt, tok.nextToken.toInt)\n if (s.last == 'C') fontsCBuilder += f else fontsDBuilder += f\n }\n\n val fontsC = fontsCBuilder.result.sortBy(_.p)\n\n val fontsD = fontsDBuilder.result.sortBy(_.p)\n\n var maxForC = 0\n for (fc <- fontsC) {\n if (fc.p <= c && fc.b > maxForC) maxForC = fc.b\n }\n\n var maxForD = 0\n for (fd <- fontsD) {\n if (fd.p <= d && fd.b > maxForD) maxForD = fd.b\n }\n\n val resCD = if (maxForC > 0 && maxForD > 0) maxForC + maxForD else 0\n\n def solve(fonts: Array[Fountain], limit: Int): Int = {\n var left = 0\n var right = fonts.length - 1\n var maxLeft = 0\n var res = 0\n\n while (left < right) {\n val rightP = fonts(right).p\n while (left < right && fonts(left).p + rightP <= limit) {\n if (fonts(left).b > maxLeft) maxLeft = fonts(left).b\n left += 1\n }\n if (rightP <= limit && rightP + maxLeft > res) res = rightP + maxLeft\n right -= 1\n }\n\n left = 1\n maxLeft = 0\n while (left <= right) {\n if (fonts(left - 1).b > maxLeft) maxLeft = fonts(left - 1).b\n if (fonts(left).b + maxLeft > res) res = fonts(left).b + maxLeft\n left += 1\n }\n\n res\n }\n\n val resCC = solve(fontsC, c)\n val resDD = solve(fontsD, d)\n\n println(resCD max resCC max resDD)\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, c, d) = readInts(3)\n\n case class Fountain(id: Int, b: Int, p: Int)\n\n val fontsCBuilder, fontsDBuilder = new mutable.ArrayBuilder.ofRef[Fountain]()\n\n for (i <- 0 until n) {\n val s = readLine\n val tok = new java.util.StringTokenizer(s)\n val f = Fountain(i, tok.nextToken.toInt, tok.nextToken.toInt)\n if (s.last == 'C') fontsCBuilder += f else fontsDBuilder += f\n }\n\n val fontsC = fontsCBuilder.result.sortBy(_.p)\n\n val fontsD = fontsDBuilder.result.sortBy(_.p)\n\n var maxForC = 0\n for (fc <- fontsC) {\n if (fc.p <= c && fc.b > maxForC) maxForC = fc.b\n }\n\n var maxForD = 0\n for (fd <- fontsD) {\n if (fd.p <= d && fd.b > maxForD) maxForD = fd.b\n }\n\n val resCD = if (maxForC > 0 && maxForD > 0) maxForC + maxForD else 0\n\n def solve(fonts: Array[Fountain], limit: Int): Int = {\n var left = 0\n var right = fonts.length - 1\n var maxLeft = 0\n var res = 0\n\n while (left < right) {\n val rightP = fonts(right).p\n val rightB = fonts(right).b\n while (left < right && fonts(left).p + rightP <= limit) {\n if (fonts(left).b > maxLeft) maxLeft = fonts(left).b\n left += 1\n }\n if (rightP <= limit && rightB + maxLeft > res) res = rightB + maxLeft\n right -= 1\n }\n\n left = 1\n maxLeft = 0\n while (left <= right) {\n if (fonts(left - 1).b > maxLeft) maxLeft = fonts(left - 1).b\n if (fonts(left).b + maxLeft > res) res = fonts(left).b + maxLeft\n left += 1\n }\n\n res\n }\n\n val resCC = solve(fontsC, c)\n val resDD = solve(fontsD, d)\n\n println(resCD max resCC max resDD)\n}\n"}], "src_uid": "89c54eb60bd0adcbe8892c922d86b0d8"} {"nl": {"description": "Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \\cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible.", "input_spec": "First line contains a single integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \\leq a_i \\leq 10^9, 0 \\leq b_i, c_i \\leq 1)$$$ \u00a0\u2014 the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \\leq u, v \\leq n, \\text{ } u \\ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.", "output_spec": "Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible.", "sample_inputs": ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"], "sample_outputs": ["4", "24000", "-1"], "notes": "NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \\cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \\cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \\cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially."}, "positive_code": [{"source_code": "\n//package codeforces.contests._1363\n\nobject TreeShuffling {\n\n\n type Graph[T] = Array[List[T]]\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val count = Array.ofDim[Int](n + 1, 2) // zeroes and ones for each node\n\n val cost = new Array[Int](n + 1)\n (1 to n).foreach { idx =>\n val Array(c, i, f) = io.StdIn.readLine.split(\" \").map(_.toInt)\n if (i != f) {\n if (i == 0) count(idx)(0) = 1 else count(idx)(1) = 1\n }\n cost(idx) = c\n }\n\n val graph: Graph[Int] = {\n val arr = Array.fill[List[Int]](n + 1)(Nil)\n (1 until n).foreach { _ =>\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(x) ::= y\n arr(y) ::= x\n }\n arr\n }\n\n var total: Long = 0L\n\n val parent = new Array[Int](n + 1)\n val visited = new Array[Boolean](n + 1)\n\n @scala.annotation.tailrec\n def iterativeDFS(stack: List[Int]): Unit = {\n if (stack.nonEmpty) {\n val i = stack.head\n val p = parent(i)\n\n if (!visited(i)) {\n visited(i) = true\n val uStack = graph(i).foldLeft(stack)((acc, c) => if (c == p) acc else {\n cost(c) = cost(c) min cost(i)\n parent(c) = i\n c :: acc\n })\n iterativeDFS(uStack)\n } else {\n //node is done, update parent\n val toRemove = count(i)(0) min count(i)(1)\n\n total += 2L * toRemove * cost(i)\n count(p)(0) += count(i)(0) - toRemove\n count(p)(1) += count(i)(1) - toRemove\n\n iterativeDFS(stack.tail)\n }\n }\n }\n\n println {\n iterativeDFS(List(1))\n val zeroes = count(0)(0)\n val ones = count(0)(1)\n if (zeroes == 0 && ones == 0) total else -1\n }\n }\n\n}"}], "negative_code": [{"source_code": "\n//package codeforces.contests._1363\n\nobject TreeShuffling {\n\n\n type Graph[T] = Array[List[T]]\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n\n val count = Array.ofDim[Int](n + 1, 2) // zeroes and ones for each node\n\n val cost = new Array[Int](n + 1)\n (1 to n).foreach { idx =>\n val Array(c, i, f) = io.StdIn.readLine.split(\" \").map(_.toInt)\n if (i != f) {\n if (i == 0) count(idx)(0) = 1 else count(idx)(1) = 1\n }\n cost(idx) = c\n }\n\n val graph: Graph[Int] = {\n val arr = Array.fill[List[Int]](n + 1)(Nil)\n (1 until n).foreach { _ =>\n val Array(x, y) = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(x) ::= y\n arr(y) ::= x\n }\n arr\n }\n\n var total: Long = 0L\n\n val parent = new Array[Int](n + 1)\n val visited = new Array[Boolean](n + 1)\n\n @scala.annotation.tailrec\n def iterativeDFS(stack: List[Int]): Unit = {\n if (stack.nonEmpty) {\n val i = stack.head\n val p = parent(i)\n\n if (!visited(i)) {\n visited(i) = true\n val uStack = graph(i).foldLeft(stack)((acc, c) => if (c == p) acc else {\n cost(c) = cost(c) min cost(i)\n parent(c) = i\n c :: acc\n })\n iterativeDFS(uStack)\n } else {\n //node is done, update parent\n val toRemove = count(i)(0) min count(i)(1)\n\n total += 2 * toRemove * cost(i)\n count(p)(0) += count(i)(0) - toRemove\n count(p)(1) += count(i)(1) - toRemove\n\n iterativeDFS(stack.tail)\n }\n }\n }\n\n println {\n iterativeDFS(List(1))\n val zeroes = count(0)(0)\n val ones = count(0)(1)\n if (zeroes == 0 && ones == 0) total else -1\n }\n }\n\n}"}], "src_uid": "4dce15ff1446b5af2c5b49ee2d30bbb8"} {"nl": {"description": "Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x. Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.", "input_spec": "The first line of the input contains three integers n, m, k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7109,\u20091\u2009\u2264\u2009m,\u2009k\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers x and s (2\u2009\u2264\u2009x\u2009\u2264\u20092\u00b7109,\u20091\u2009\u2264\u2009s\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains m integers ai (1\u2009\u2264\u2009ai\u2009<\u2009x)\u00a0\u2014 the number of seconds it will take to prepare one potion if the i-th spell of the first type is used. The fourth line contains m integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the number of manapoints to use the i-th spell of the first type. There are k integers ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) in the fifth line\u00a0\u2014 the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci\u2009\u2264\u2009cj if i\u2009<\u2009j. The sixth line contains k integers di (1\u2009\u2264\u2009di\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di\u2009\u2264\u2009dj if i\u2009<\u2009j.", "output_spec": "Print one integer\u00a0\u2014 the minimum time one has to spent in order to prepare n potions.", "sample_inputs": ["20 3 2\n10 99\n2 4 3\n20 10 40\n4 15\n10 80", "20 3 2\n10 99\n2 4 3\n200 100 400\n4 15\n100 800"], "sample_outputs": ["20", "200"], "notes": "NoteIn the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10\u2009+\u200980\u2009=\u200990, and the preparation time is 4\u00b75\u2009=\u200920 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each).In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20\u00b710\u2009=\u2009200."}, "positive_code": [{"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 Array(x, s) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt)\n val b = in.next().split(' ').map(_.toInt)\n val c = in.next().split(' ').map(_.toInt)\n val d = in.next().split(' ').map(_.toInt)\n\n def findNotMoreCount(x: Int, left: Int = -1, right: Int = k): Int = {\n if (left == -1 && d.head > x) 0\n else if (left == -1) findNotMoreCount(x, 0, right)\n else if (right - left == 1) c(left)\n else {\n val middle = left + (right - left) / 2\n if (d(middle) > x)\n findNotMoreCount(x, left, middle)\n else\n findNotMoreCount(x, middle, right)\n }\n }\n\n val both = a.zip(b).filter{\n case(ai, bi) => bi <= s && ai < x\n }.map{\n case(ai, bi) => (n - findNotMoreCount(s - bi)).toLong * ai\n }\n\n val zero = (n - findNotMoreCount(s)).toLong * x\n\n if (both.isEmpty)\n println(zero)\n else\n println(Math.min(zero, both.min))\n\n}"}], "negative_code": [{"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 Array(x, s) = in.next().split(' ').map(_.toInt)\n val a = in.next().split(' ').map(_.toInt)\n val b = in.next().split(' ').map(_.toInt)\n val c = in.next().split(' ').map(_.toInt)\n val d = in.next().split(' ').map(_.toInt)\n\n def findNotMoreCount(x: Int, left: Int = -1, right: Int = k): Int = {\n if (left == -1 && d.head > x) 0\n else if (left == -1) findNotMoreCount(x, 0, right)\n else if (right - left == 1) c(left)\n else {\n val middle = left + (right - left) / 2\n if (d(middle) > x)\n findNotMoreCount(x, left, middle)\n else\n findNotMoreCount(x, middle, right)\n }\n }\n\n val both = a.zip(b).filter{\n case(ai, bi) => bi <= s && ai < x\n }.map{\n case(ai, bi) => (n - findNotMoreCount(s - bi)) * ai\n }\n\n val zero = (n - findNotMoreCount(s)) * x\n\n if (both.isEmpty)\n println(zero)\n else\n println(Math.min(zero, both.min))\n\n}"}], "src_uid": "2f9f2bdf059e5ab9c64e7b5f27cba0cb"} {"nl": {"description": "Vasya has an array of integers of length n.Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13,\u200913,\u20097,\u20097,\u20097,\u20092,\u20092,\u20092], then after one operation it becomes [13,\u200913,\u20092,\u20092,\u20092].Compute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000) \u2014 the length of the array. The second line contains a sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 Vasya's array.", "output_spec": "Print the number of operations Vasya should make to remove all elements from the array.", "sample_inputs": ["4\n2 5 5 2", "5\n6 3 4 1 5", "8\n4 4 4 2 2 100 100 100", "6\n10 10 50 10 50 50"], "sample_outputs": ["2", "5", "3", "4"], "notes": "NoteIn the first example, at first Vasya removes two fives at the second and third positions. The array becomes [2,\u20092]. In the second operation Vasya removes two twos at the first and second positions. After that the array becomes empty.In the second example Vasya has to perform five operations to make the array empty. In each of them he removes the first element from the array.In the third example Vasya needs three operations. In the first operation he removes all integers 4, in the second \u2014 all integers 100, in the third \u2014 all integers 2.In the fourth example in the first operation Vasya removes the first two integers 10. After that the array becomes [50,\u200910,\u200950,\u200950]. Then in the second operation Vasya removes the two rightmost integers 50, so that the array becomes [50,\u200910]. In the third operation he removes the remaining 50, and the array becomes [10] after that. In the last, fourth operation he removes the only remaining 10. The array is empty after that."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1,\u2009a2,\u2009...,\u2009an, where ai denotes the distance of the i-th mark from the origin (a1\u2009=\u20090, an\u2009=\u2009l).Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj\u2009-\u2009ai\u2009=\u2009d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x\u2009<\u2009y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.", "input_spec": "The first line contains four positive space-separated integers n, l, x, y (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 2\u2009\u2264\u2009l\u2009\u2264\u2009109, 1\u2009\u2264\u2009x\u2009<\u2009y\u2009\u2264\u2009l) \u2014 the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009=\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an\u2009=\u2009l), where ai shows the distance from the i-th mark to the origin.", "output_spec": "In the first line print a single non-negative integer v \u2014 the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1,\u2009p2,\u2009...,\u2009pv (0\u2009\u2264\u2009pi\u2009\u2264\u2009l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.", "sample_inputs": ["3 250 185 230\n0 185 250", "4 250 185 230\n0 20 185 250", "2 300 185 230\n0 300"], "sample_outputs": ["1\n230", "0", "2\n185 230"], "notes": "NoteIn the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given a string s consisting only of characters 0 and 1. A substring [l,\u2009r] of s is a string slsl\u2009+\u20091sl\u2009+\u20092... sr, and its length equals to r\u2009-\u2009l\u2009+\u20091. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.", "input_spec": "The first line contains n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000) \u2014 the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.", "output_spec": "If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.", "sample_inputs": ["8\n11010111", "3\n111"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first example you can choose the substring [3,\u20096]. It is balanced, and its length is 4. Choosing the substring [2,\u20095] is also possible.In the second example it's impossible to find a non-empty balanced substring."}, "positive_code": [{"source_code": "object MyClass {\n def add(x:Int, y:Int) = x + y;\n\n def main(args: Array[String]) {\n val indices = new Array[Int](200005);\n var i = 0;\n for (i <- 0 to 200004) {\n indices(i) = -1;\n }\n \n var lines = io.Source.stdin.getLines;\n var n = lines.next.toInt;\n var bits = lines.next;\n \n var o = 0;\n var z = 0;\n for (i <- 0 to n - 1) {\n if (bits(i) == '0') o+=1;\n else z+=1;\n \n indices(o - z + 100000) = i;\n }\n \n o = 0;\n z = 0;\n var Max = 0;\n \n for (i <- 0 to n - 1) {\n var tmp = indices(o - z + 100000) - i + 1;\n if (tmp > Max) Max = tmp;\n \n if (bits(i) == '0') o+=1;\n else z+=1;\n }\n \n print(Max);\n }\n \n }\n"}], "negative_code": [], "src_uid": "08fa04303060d38d6cd0f3a321a527ad"} {"nl": {"description": "$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \\leq i \\leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \\leq j \\leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \\ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \\ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \\leq i \\leq n$$$ and $$$1 \\leq j \\leq m$$$. You are given the numbers $$$b_1, \\ldots, b_n$$$ and $$$g_1, \\ldots, g_m$$$, determine this number. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$, separated with space\u00a0\u2014 the number of boys and girls, respectively ($$$2 \\leq n, m \\leq 100\\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \\ldots, b_n$$$, separated by spaces\u00a0\u2014 $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \\leq b_i \\leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \\ldots, g_m$$$, separated by spaces\u00a0\u2014 $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \\leq g_j \\leq 10^8$$$).", "output_spec": "If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.", "sample_inputs": ["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"], "sample_outputs": ["12", "-1", "4"], "notes": "NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a permutation $$$a_1,a_2,\\ldots,a_n$$$ of integers from $$$0$$$ to $$$n - 1$$$. Your task is to find how many permutations $$$b_1,b_2,\\ldots,b_n$$$ are similar to permutation $$$a$$$. Two permutations $$$a$$$ and $$$b$$$ of size $$$n$$$ are considered similar if for all intervals $$$[l,r]$$$ ($$$1 \\le l \\le r \\le n$$$), the following condition is satisfied: $$$$$$\\operatorname{MEX}([a_l,a_{l+1},\\ldots,a_r])=\\operatorname{MEX}([b_l,b_{l+1},\\ldots,b_r]),$$$$$$ where the $$$\\operatorname{MEX}$$$ of a collection of integers $$$c_1,c_2,\\ldots,c_k$$$ is defined as the smallest non-negative integer $$$x$$$ which does not occur in collection $$$c$$$. For example, $$$\\operatorname{MEX}([1,2,3,4,5])=0$$$, and $$$\\operatorname{MEX}([0,1,2,4,5])=3$$$.Since the total number of such permutations can be very large, you will have to print its remainder modulo $$$10^9+7$$$.In this problem, a permutation of size $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n-1$$$ in arbitrary order. For example, $$$[1,0,2,4,3]$$$ is a permutation, while $$$[0,1,1]$$$ is not, since $$$1$$$ appears twice in the array. $$$[0,1,3]$$$ is also not a permutation, since $$$n=3$$$ and there is a $$$3$$$ in the array.", "input_spec": "Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the size of permutation $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$0 \\le a_i \\lt n$$$)\u00a0\u2014 the elements of permutation $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer, the number of permutations similar to permutation $$$a$$$, taken modulo $$$10^9+7$$$.", "sample_inputs": ["5\n\n5\n\n4 0 3 2 1\n\n1\n\n0\n\n4\n\n0 1 2 3\n\n6\n\n1 2 4 0 5 3\n\n8\n\n1 3 7 2 5 0 6 4"], "sample_outputs": ["2\n1\n1\n4\n72"], "notes": "NoteFor the first test case, the only permutations similar to $$$a=[4,0,3,2,1]$$$ are $$$[4,0,3,2,1]$$$ and $$$[4,0,2,3,1]$$$.For the second and third test cases, the given permutations are only similar to themselves.For the fourth test case, there are $$$4$$$ permutations similar to $$$a=[1,2,4,0,5,3]$$$: $$$[1,2,4,0,5,3]$$$; $$$[1,2,5,0,4,3]$$$; $$$[1,4,2,0,5,3]$$$; $$$[1,5,2,0,4,3]$$$. "}, "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n val q = tokenizer.nextToken().toInt\r\n for (i <- 0 until q) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken.toInt\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val C = new Array[Int](n)\r\n val A = new Array[Int](n)\r\n for (j <- 0 until n){\r\n val el = tokenizer.nextToken().toInt\r\n C(j) = el\r\n A(el) = j\r\n\r\n }\r\n val B = C.toList\r\n var l = B.indexOf(0)\r\n var r = l\r\n var sl = 0\r\n var pr: Long = 1\r\n for (k <- 1 until n) {\r\n if ((l > 0) || (r l) && (c < r)) {\r\n pr = pr * sl % 1000000007\r\n sl=sl-1\r\n }\r\n if (c r) {\r\n sl += c - r - 1\r\n r = c\r\n }\r\n }\r\n else {\r\n pr = pr * sl %1000000007\r\n sl-=1\r\n }\r\n\r\n }\r\n output.println(pr)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "a58ad54eaf4912f530a7d25a503640d3"} {"nl": {"description": "Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move: exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$; exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$; exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$; exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \\le u \\le x_2$$$ and $$$y_1 \\le v \\le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \\le u \\le x_2$$$, $$$y_1 \\le v \\le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of testcases. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \\le a,b,c,d \\le 10^8$$$, $$$a+b+c+d \\ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \\le x_1\\le x \\le x_2 \\le 10^8$$$, $$$-10^8 \\le y_1 \\le y \\le y_2 \\le 10^8$$$).", "output_spec": "For each test case, output \"YES\" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).", "sample_inputs": ["6\n3 2 2 2\n0 0 -2 -2 2 2\n3 1 4 1\n0 0 -1 -1 1 1\n1 1 1 1\n1 1 1 1 1 1\n0 0 0 1\n0 0 0 0 0 1\n5 1 1 1\n0 0 -100 -100 0 100\n1 1 5 1\n0 0 -100 -100 100 0"], "sample_outputs": ["Yes\nNo\nNo\nYes\nYes\nYes"], "notes": "NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\\rightarrow (-1,0) \\rightarrow (-2,0)\\rightarrow (-2,1) \\rightarrow (-2,2)\\rightarrow (-1,2)\\rightarrow(0,2)\\rightarrow (0,1)\\rightarrow (0,0) \\rightarrow (-1,0)$$$$$$"}, "positive_code": [{"source_code": "object A extends App {\n case class Path(a: Int, b: Int, c: Int, d: Int)\n case class Limit(x: Int, y: Int, x1: Int, y1: Int, x2: Int, y2: Int)\n case class Case(path: Path, limit: Limit)\n\n implicit def array2path(arr: Array[Int]): Path = arr match {\n case Array(a, b, c, d) => Path(a, b, c, d)\n case _ => throw new IllegalArgumentException\n }\n\n implicit def array2limit(arr: Array[Int]): Limit = arr match {\n case Array(x, y, x1, y1, x2, y2) => Limit(x, y, x1, y1, x2, y2)\n case _ => throw new IllegalArgumentException\n }\n\n private def isSatisfied: PartialFunction[Case, Boolean] = {\n case Case(Path(a, b, c, d), Limit(x, y, x1, y1, x2, y2)) =>\n val dx = b - a\n val dy = d - c\n\n if (x == x1 && x == x2 && a != 0 && b != 0) false\n else if (y == y1 && y == y2 && d != 0 && c != 0) false\n else (dx <= 0 && x + dx >= x1 || dx >= 0 && x + dx <= x2) &&\n (dy <= 0 && y + dy >= y1 || dy >= 0 && y + dy <= y2)\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[Case] = (0 until t).foldLeft(List.empty[Case]) { case (cases, _) =>\n val path: Path = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val limit: Limit = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n Case(path, limit) :: cases\n }.reverse\n\n val output: List[String] = input.map(isSatisfied).map(if (_) \"YES\" else \"NO\")\n\n output.foreach(println)\n}"}], "negative_code": [], "src_uid": "7224ffd4776af4129739e1b28f696050"} {"nl": {"description": "Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n\u2009+\u20091. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n\u2009+\u20091 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.", "input_spec": "The first line of the input contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009t\u2009\u2264\u2009109)\u00a0\u2014 the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.", "output_spec": "Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.", "sample_inputs": ["6 1\n10.245", "6 2\n10.245", "3 100\n9.2"], "sample_outputs": ["10.25", "10.3", "9.2"], "notes": "NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all."}, "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"}, {"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"}], "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"} {"nl": {"description": "One day, little Vasya found himself in a maze consisting of (n\u2009+\u20091) rooms, numbered from 1 to (n\u2009+\u20091). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n\u2009+\u20091)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), someone can use the first portal to move from it to room number (i\u2009+\u20091), also someone can use the second portal to move from it to room number pi, where 1\u2009\u2264\u2009pi\u2009\u2264\u2009i.In order not to get lost, Vasya decided to act as follows. Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1. Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n\u2009+\u20091) in the end.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103)\u00a0\u2014 the number of rooms. The second line contains n integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.", "output_spec": "Print a single number \u2014 the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["2\n1 2", "4\n1 1 2 3", "5\n1 1 1 1 1"], "sample_outputs": ["4", "20", "62"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "7bb5df614d1fc8323eba51d04ee7bf2a"} {"nl": {"description": "There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \\dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.", "input_spec": "The first line contains single integer $$$n$$$ $$$(1 \\le n \\le 1\\,000)$$$\u00a0\u2014 the number of keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^{9})$$$\u00a0\u2014 the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.", "output_spec": "Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.", "sample_inputs": ["4\n10 13 12 8", "5\n7 5 6 4 8"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist."}, "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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}], "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"} {"nl": {"description": "Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with \"heavy\" and ends with \"metal\". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.", "input_spec": "Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.", "output_spec": "Print exactly one number \u2014 the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["heavymetalisheavymetal", "heavymetalismetal", "trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou"], "sample_outputs": ["3", "2", "3"], "notes": "NoteIn the first sample the string \"heavymetalisheavymetal\" contains powerful substring \"heavymetal\" twice, also the whole string \"heavymetalisheavymetal\" is certainly powerful.In the second sample the string \"heavymetalismetal\" contains two powerful substrings: \"heavymetal\" and \"heavymetalismetal\"."}, "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": "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}"}, {"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"} {"nl": {"description": "Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\\ldots,a_n$$$ and $$$b_1,b_2,\\ldots,b_m$$$.For each $$$i$$$ ($$$1\\le i\\le n$$$), you're asked to choose a $$$j$$$ ($$$1\\le j\\le m$$$) and let $$$c_i=a_i\\& b_j$$$, where $$$\\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \\ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\\le n,m\\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$0\\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\\ldots,b_m$$$ ($$$0\\le b_i < 2^9$$$).", "output_spec": "Print one integer: the minimum possible $$$c_1 | c_2 | \\ldots | c_n$$$.", "sample_inputs": ["4 2\n2 6 4 0\n2 4", "7 6\n1 9 1 9 8 1 0\n1 1 4 5 1 4", "8 5\n179 261 432 162 82 43 10 38\n379 357 202 184 197"], "sample_outputs": ["2", "0", "147"], "notes": "NoteFor the first example, we have $$$c_1=a_1\\& b_2=0$$$, $$$c_2=a_2\\& b_1=2$$$, $$$c_3=a_3\\& b_1=0$$$, $$$c_4 = a_4\\& b_1=0$$$.Thus $$$c_1 | c_2 | c_3 |c_4 =2$$$, and this is the minimal answer we can get."}, "positive_code": [{"source_code": "object C extends App {\n import scala.io.StdIn._\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val an = readLine().split(\" \").map(_.toInt)\n val bm = readLine().split(\" \").map(_.toInt)\n\n val ans = an\n .foldLeft(1 +: Array.fill(511)(0)) { (xs, a) =>\n xs.zipWithIndex.foldLeft(Array.fill(512)(0)) {\n case (ys, (0, _)) => ys\n case (ys, (1, i)) =>\n bm.foreach(b => ys(i | a & b) = 1) // (i | a & b) >= i\n ys\n }\n }\n .indexWhere(_ == 1)\n\n println(ans)\n}\n"}], "negative_code": [], "src_uid": "3da5075048a127319ffa8913859d2aa7"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times: Select an index $$$i$$$ ($$$1\\leq i\\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i.\u00a0e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\\max(a_1, a_2, \\ldots, a_n) \\cdot \\max(b_1, b_2, \\ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero). ", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\\le n\\le 100$$$) \u2014 the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10\\,000$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le 10\\,000$$$) where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.", "output_spec": "For each test case, print a single integer, the minimum possible value of $$$\\max(a_1, a_2, \\ldots, a_n) \\cdot \\max(b_1, b_2, \\ldots, b_n)$$$ you can get after applying such operation any number of times.", "sample_inputs": ["3\n\n6\n\n1 2 6 5 1 2\n\n3 4 3 2 2 5\n\n3\n\n3 3 3\n\n3 3 3\n\n2\n\n1 2\n\n2 1"], "sample_outputs": ["18\n9\n2"], "notes": "NoteIn the first test, you can apply the operations at indices $$$2$$$ and $$$6$$$, then $$$a = [1, 4, 6, 5, 1, 5]$$$ and $$$b = [3, 2, 3, 2, 2, 2]$$$, $$$\\max(1, 4, 6, 5, 1, 5) \\cdot \\max(3, 2, 3, 2, 2, 2) = 6 \\cdot 3 = 18$$$.In the second test, no matter how you apply the operations, $$$a = [3, 3, 3]$$$ and $$$b = [3, 3, 3]$$$ will always hold, so the answer is $$$\\max(3, 3, 3) \\cdot \\max(3, 3, 3) = 3 \\cdot 3 = 9$$$.In the third test, you can apply the operation at index $$$1$$$, then $$$a = [2, 2]$$$, $$$b = [1, 1]$$$, so the answer is $$$\\max(2, 2) \\cdot \\max(1, 1) = 2 \\cdot 1 = 2$$$."}, "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 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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.\u00a0e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n\u2009\u2264\u2009k) values b1,\u2009b2,\u2009...,\u2009bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.\u00a0e. n\u2009<\u2009k. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant.", "input_spec": "The first line contains two integers k and n (1\u2009\u2264\u2009n\u2009\u2264\u2009k\u2009\u2264\u20092\u2009000) \u2014 the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,\u2009a2,\u2009...,\u2009ak (\u2009-\u20092\u2009000\u2009\u2264\u2009ai\u2009\u2264\u20092\u2009000) \u2014 jury's marks in chronological order. The third line contains n distinct integers b1,\u2009b2,\u2009...,\u2009bn (\u2009-\u20094\u2009000\u2009000\u2009\u2264\u2009bj\u2009\u2264\u20094\u2009000\u2009000) \u2014 the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.", "output_spec": "Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print \"0\" (without quotes).", "sample_inputs": ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"], "sample_outputs": ["3", "1"], "notes": "NoteThe answer for the first example is 3 because initially the participant could have \u2009-\u200910, 10 or 15 points.In the second example there is only one correct initial score equaling to 4\u2009002\u2009000."}, "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(k, n) = readInts(2)\n val as = readInts(k)\n val bs = readInts(n)\n\n val aRunning = as.scan(0)(_ + _).drop(1)\n val bMax = bs.max\n val res = mutable.Set.empty[Int]\n\n for (i <- 0 until k) {\n\n val aSum = aRunning(i)\n val score0 = bMax - aSum\n var score = score0\n val availableBs = mutable.Set.empty[Int] ++ bs\n\n var j = 0\n while (j < k && availableBs.nonEmpty) {\n score += as(j)\n availableBs -= score\n j += 1\n }\n\n if (availableBs.isEmpty) res += score0\n }\n\n println(res.size)\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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, n) = readInts(2)\n val as = readInts(k)\n val bs = readInts(n)\n //val as = mutable.Set.empty[Int]\n val cnts = Array.fill(10000){ 0 }\n for (a <- as) cnts(2000 + a) += 1\n\n def has(d: Int): Boolean = {\n d >= 0 && d < cnts.length && cnts(d) > 0\n }\n\n val used = new mutable.BitSet(n)\n\n for (i <- 0 until n) if (!used(i)) {\n var j = 0\n while (j < n) {\n if (i != j && !used(j)) {\n val d = bs(i) - bs(j)\n if (has(2000 + d)) {\n //println(i, j, d)\n cnts(2000 + d) -= 1\n used += j\n }\n }\n j += 1\n }\n }\n\n val res = if (used.size == n - 1) as.size - 1 else 0\n\n println(res)\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(k, n) = readInts(2)\n val as = readInts(k)\n val bs = readInts(n)\n //val as = mutable.Set.empty[Int]\n val cnts = Array.fill(10000){ 0 }\n for (a <- as) cnts(2000 + a) += 1\n\n def has(d: Int): Boolean = {\n d >= 0 && d < cnts.length && cnts(d) > 0\n }\n\n val used = new mutable.BitSet(n)\n\n for (i <- 0 until n) if (!used(i)) {\n var j = 0\n while (j < n) {\n if (i != j && !used(j)) {\n val d = bs(i) - bs(j)\n if (has(2000 + d)) {\n //println(i, j, d)\n cnts(2000 + d) -= 1\n used += j\n }\n }\n j += 1\n }\n }\n\n val res = if (used.size == n - 1) as.count(_ != 0) - n + 1 else 0\n\n println(res)\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(k, n) = readInts(2)\n val as = readInts(k)\n val bs = readInts(n)\n //val as = mutable.Set.empty[Int]\n val cnts = Array.fill(10000){ 0 }\n for (a <- as) cnts(2000 + a) += 1\n\n def has(d: Int): Boolean = {\n d >= 0 && d < cnts.length && cnts(d) > 0\n }\n\n val used = new mutable.BitSet(n)\n\n for (i <- 0 until n) if (!used(i)) {\n var j = 0\n while (j < n) {\n if (i != j && !used(j)) {\n val d = bs(i) - bs(j)\n if (has(2000 + d)) {\n println(i, j, d)\n cnts(2000 + d) -= 1\n used += j\n }\n }\n j += 1\n }\n }\n\n val res = if (used.size == n - 1) as.size - 1 else 0\n\n println(res)\n}\n"}], "src_uid": "6e5b5d357e01d86e1a6dfe7957f57876"} {"nl": {"description": "Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. ", "input_spec": "The single line contains two integers, n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u20091000).", "output_spec": "Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value. If there are multiple suitable tables, you are allowed to print any of them.", "sample_inputs": ["2 4", "4 7"], "sample_outputs": ["1 3\n3 1", "2 1 0 4\n4 0 2 1\n1 3 3 0\n0 3 2 2"], "notes": "NoteIn the first sample the sum in the first row is 1\u2009+\u20093\u2009=\u20094, in the second row \u2014 3\u2009+\u20091\u2009=\u20094, in the first column \u2014 1\u2009+\u20093\u2009=\u20094 and in the second column \u2014 3\u2009+\u20091\u2009=\u20094. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements."}, "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": "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"}, {"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"} {"nl": {"description": "After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of m\u2009+\u2009n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s|\u2009=\u2009m\u2009+\u2009n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts.", "input_spec": "The first line of the input contains two integers n and k (0\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u200926). The second line contains a string t (|t|\u2009=\u2009m,\u20091\u2009\u2264\u2009m\u2009\u2264\u20091\u2009000\u2009000) consisting of only first k lowercase English letters.", "output_spec": "Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109\u2009+\u20097. Please note, that you are not asked to maximize the remainder modulo 109\u2009+\u20097! The goal is to maximize the initial value and then print the remainder.", "sample_inputs": ["1 3\nac", "0 2\naaba"], "sample_outputs": ["8", "10"], "notes": "NoteIn the first sample, the optimal labeling gives 8 different subsequences: \"\" (the empty string), \"a\", \"c\", \"b\", \"ac\", \"ab\", \"cb\", and \"acb\". In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: \"\" (the empty string), \"a\", \"b\", \"aa\", \"ab\", \"ba\", \"aaa\", \"aab\", \"aba\", and \"aaba\". Note that some strings, including \"aa\", can be obtained with multiple sequences of tiles, but are only counted once."}, "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, k) = readInts(2)\n val t = readLine.map(_ - 'a')\n val MOD = 1000000007L\n\n var res = 1L\n\n val lastPos = Array.fill(k){ -1 }\n var dp = Array.fill(k){ 0L }\n\n var pos = 0\n\n for (c <- t) {\n lastPos(c) = pos\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n pos += 1\n }\n\n val pq = mutable.PriorityQueue.empty(Ordering.by(lastPos).reverse)\n pq ++= 0 until k\n\n var i = 0\n var prev = -1\n while (i < n) {\n i += 1\n val c = pq.dequeue()\n lastPos(c) = pos\n pq += c\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n prev = c\n pos += 1\n }\n\n println(res % MOD)\n}\n"}], "negative_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, k) = readInts(2)\n val t = readLine.map(_ - 'a')\n val MOD = 1000000007L\n\n var res = 1L\n\n val cnt = Array.fill(k){ 0 }\n var dp = Array.fill(k){ 0L }\n\n for (c <- t) {\n cnt(c) += 1\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n }\n\n val pq = mutable.TreeSet.empty[Int](Ordering.by(cnt))\n (0 until k).foreach(i => pq.add(i))\n\n var i = 0\n while (i < n) {\n i += 1\n val c = pq.head\n pq.remove(c)\n cnt(c) -= 1\n pq += c\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n }\n\n println(res % MOD)\n}\n"}, {"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, k) = readInts(2)\n val t = readLine.map(_ - 'a')\n val MOD = 1000000007L\n\n var res = 1L\n\n val cnts = Array.fill(k){ 0 }\n var dp = Array.fill(k){ 0L }\n\n for (c <- t) {\n cnts(c) += 1\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n }\n\n val pq = mutable.PriorityQueue.empty(Ordering.by(cnts).reverse)\n pq ++= 0 until k\n\n var i = 0\n var prev = -1\n while (i < n) {\n i += 1\n val c = {\n val _c = pq.dequeue()\n if (_c == prev && pq.nonEmpty && cnts(pq.head) == cnts(_c)) {\n val c2 = pq.dequeue()\n pq += _c\n c2\n } else _c\n }\n cnts(c) -= 1\n pq += c\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n prev = c\n }\n\n println(res % MOD)\n}\n"}, {"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, k) = readInts(2)\n val t = readLine.map(_ - 'a')\n val MOD = 1000000007L\n\n var res = 1L\n\n val cnt = Array.fill(k){ 0 }\n var dp = Array.fill(k){ 0L }\n\n for (c <- t) {\n cnt(c) += 1\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n }\n\n val pq = mutable.PriorityQueue.empty(Ordering.by(cnt).reverse)\n pq ++= 0 until k\n\n var i = 0\n while (i < n) {\n i += 1\n val c = pq.dequeue()\n cnt(c) -= 1\n pq += c\n val x = (MOD + res - dp(c)) % MOD\n dp(c) = (dp(c) + x) % MOD\n res = (res + x) % MOD\n }\n\n println(res % MOD)\n}\n"}], "src_uid": "13574507efa5089f3420cf002c3f8077"} {"nl": {"description": "You are given a positive integer $$$n$$$. In one move, you can increase $$$n$$$ by one (i.e. make $$$n := n + 1$$$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \\le n \\le 10^{18}$$$; $$$1 \\le s \\le 162$$$).", "output_spec": "For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.", "sample_inputs": ["5\n2 1\n1 1\n500 4\n217871987498122 10\n100000000000000001 1"], "sample_outputs": ["8\n0\n500\n2128012501878\n899999999999999999"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1,\u2009x2,\u2009...,\u2009xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.", "input_spec": "The first line of input contains three space-separated integers n,\u2009a,\u2009b\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009109). The second line of input contains n space-separated integers x1,\u2009x2,\u2009...,\u2009xn\u00a0(1\u2009\u2264\u2009xi\u2009\u2264\u2009109).", "output_spec": "Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.", "sample_inputs": ["5 1 4\n12 6 11 9 1", "3 1 2\n1 2 3", "1 1 1\n1"], "sample_outputs": ["0 2 3 1 1", "1 0 1", "0"], "notes": null}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, a, b) = readLine().split(' ').map(_.toInt)\n val in = readLine().split(' ').map(_.toLong)\n val ans = in.map(x => x - ((x * a) / b) * b / a - (if (((x * a) / b * b) % a != 0) 1 else 0))\n for (i <- 0 until n - 1) {\n print(ans(i) + \" \")\n }\n println(ans.last)\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a else gcd(b, a % b)\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, a, b) = readLine().split(' ').map(_.toInt)\n val in = readLine().split(' ').map(_.toLong)\n val ans = in.map(x => x - ((x * a) / b) * b / a)\n for (i <- 0 until n - 1) {\n print(ans(i) + \" \")\n }\n println(ans.last)\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a else gcd(b, a % b)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, a, b) = readLine().split(' ').map(_.toInt)\n val in = readLine().split(' ').map(_.toLong)\n val ans = in.map(x => x % (b / gcd(a, b)))\n for (i <- 0 until n - 1) {\n print(ans(i) + \" \")\n }\n println(ans.last)\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a else gcd(b, a % b)\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val Array(n, a, b) = readLine().split(' ').map(_.toInt)\n val in = readLine().split(' ').map(_.toLong)\n val ans = in.map(x => (x * a) % b)\n for (i <- 0 until n - 1) {\n print(ans(i) + \" \")\n }\n println(ans.last)\n }\n}\n"}], "src_uid": "3c63e2e682d3c8051c3cecc3fa9c4e8c"} {"nl": {"description": "Haha, try to solve this, SelectorUnlimited!\u2014 antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array $$$a$$$ of $$$n$$$ non-negative integers indexed from $$$1$$$ to $$$n$$$. The tellee starts with some non-negative number $$$d$$$ and performs one of the two operations for each $$$i = 1, 2, \\ldots, n$$$, in the increasing order of $$$i$$$. The possible operations are: replace their current number $$$d$$$ with $$$d + a_i$$$ replace their current number $$$d$$$ with $$$d \\oplus a_i$$$ (hereinafter $$$\\oplus$$$ denotes the bitwise XOR operation)Notice that the chosen operation may be different for different $$$i$$$ and for different tellees.One time, Alice decided to start with $$$d = x$$$ and Bob started with $$$d = x + 3$$$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $$$i$$$.You learnt that either Alice or Bob ended up with number $$$y$$$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $$$y$$$, find out who (Alice or Bob) could get the number $$$y$$$ after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.", "input_spec": "On the first line of the input, you are given one number $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The following $$$2 \\cdot t$$$ lines contain test cases. The first line of each test case contains three numbers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \\le n \\le 10^5$$$, $$$0 \\le x \\le 10^9$$$, $$$0 \\le y \\le 10^{15}$$$)\u00a0\u2014 the length of array $$$a$$$, Alice's initial number (Bob's initial number is therefore $$$x+3$$$), and the number that one of the two friends got in the end. The second line of each test case contains $$$n$$$ numbers\u00a0\u2014 the array $$$a$$$ ($$$0 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the name of the friend who could get the number $$$y$$$: \"Alice\" or \"Bob\".", "sample_inputs": ["4\n\n1 7 9\n\n2\n\n2 0 2\n\n1 3\n\n4 0 1\n\n1 2 3 4\n\n2 1000000000 3000000000\n\n1000000000 1000000000"], "sample_outputs": ["Alice\nAlice\nBob\nAlice"], "notes": "NoteIn the first test case, Alice could get $$$9$$$ using the following operations: $$$7 + 2 = 9$$$.In the second test case, Alice could get $$$2$$$ using this operations: $$$(0 + 1) \\oplus 3 = 2$$$.In the third test case, Bob started with $$$x+3 = 0+3=3$$$ and could get $$$1$$$ this way: $$$(((3 + 1) + 2) \\oplus 3) \\oplus 4 = 1$$$."}, "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\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"}, {"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"} {"nl": {"description": "Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left. An 'R' indicates he should move one unit right. A 'U' indicates he should move one unit up. A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.", "input_spec": "The first and only line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the instructions Memory is given.", "output_spec": "If there is a string satisfying the conditions, output a single integer\u00a0\u2014 the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.", "sample_inputs": ["RRU", "UDUR", "RUUR"], "sample_outputs": ["-1", "1", "2"], "notes": "NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to \"LDUR\". This string uses 1 edit, which is the minimum possible. It also ends at the origin."}, "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"}, {"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"}], "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"} {"nl": {"description": "Kuroni has $$$n$$$ daughters. As gifts for them, he bought $$$n$$$ necklaces and $$$n$$$ bracelets: the $$$i$$$-th necklace has a brightness $$$a_i$$$, where all the $$$a_i$$$ are pairwise distinct (i.e. all $$$a_i$$$ are different), the $$$i$$$-th bracelet has a brightness $$$b_i$$$, where all the $$$b_i$$$ are pairwise distinct (i.e. all $$$b_i$$$ are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$ and a bracelet with brightness $$$y_i$$$, then the sums $$$x_i + y_i$$$ should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are $$$a = [1, 7, 5]$$$ and $$$b = [6, 1, 2]$$$, then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of $$$a_3 + b_1 = 11$$$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $$$a_1 + b_3 = 3$$$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of $$$a_1 + b_1 = 7$$$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $$$a_3 + b_3 = 7$$$. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u00a0\u2014 the number of daughters, necklaces and bracelets. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$) \u00a0\u2014 the brightnesses of the necklaces. The third line of each test case contains $$$n$$$ distinct integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 1000$$$) \u00a0\u2014 the brightnesses of the bracelets.", "output_spec": "For each test case, print a line containing $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$, representing that the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$. In the next line print $$$n$$$ integers $$$y_1, y_2, \\dots, y_n$$$, representing that the $$$i$$$-th daughter receives a bracelet with brightness $$$y_i$$$. The sums $$$x_1 + y_1, x_2 + y_2, \\dots, x_n + y_n$$$ should all be distinct. The numbers $$$x_1, \\dots, x_n$$$ should be equal to the numbers $$$a_1, \\dots, a_n$$$ in some order, and the numbers $$$y_1, \\dots, y_n$$$ should be equal to the numbers $$$b_1, \\dots, b_n$$$ in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.", "sample_inputs": ["2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2"], "sample_outputs": ["1 8 5\n8 4 5\n5 1 7\n6 2 1"], "notes": "NoteIn the first test case, it is enough to give the $$$i$$$-th necklace and the $$$i$$$-th bracelet to the $$$i$$$-th daughter. The corresponding sums are $$$1 + 8 = 9$$$, $$$8 + 4 = 12$$$, and $$$5 + 5 = 10$$$.The second test case is described in the statement."}, "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 val n = readInt()\n val a = readArrayInt().sortWith(_ > _)\n val b = readArrayInt().sortWith(_ > _)\n\n a.map(p => print(s\"$p \"))\n println()\n b.map(p => print(s\"$p \"))\n println()\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}"}], "negative_code": [], "src_uid": "5c6af8ced2c4b8999abccfac5c4d0057"} {"nl": {"description": "You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment \u2014 is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \\dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} < t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 > 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 300$$$) \u2014 the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \\le n_i \\le 300$$$) \u2014 the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.", "output_spec": "If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line \"NO\" for this query. Otherwise in the first line of the answer to this query print \"YES\", on the second line print $$$k_i$$$ \u2014 the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \\dots, t_{i, k_i}$$$ \u2014 your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.", "sample_inputs": ["4\n6\n654321\n4\n1337\n2\n33\n4\n2122"], "sample_outputs": ["YES\n3\n6 54 321\nYES\n3\n1 3 37\nNO\nYES\n2\n21 22"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\\mathrm{gcd}(\\mathrm{sum}(S_1), \\mathrm{sum}(S_2)) > 1$$$ Here $$$\\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.", "input_spec": "The only line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 45\\,000$$$)", "output_spec": "If such partition doesn't exist, print \"No\" (quotes for clarity). Otherwise, print \"Yes\" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitions\u00a0\u2014 print any of them.", "sample_inputs": ["1", "3"], "sample_outputs": ["No", "Yes\n1 2\n2 1 3"], "notes": "NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is \"No\".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\\mathrm{gcd}(2, 4) = 2 > 1$$$, hence that is one of the possible answers."}, "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 = ni()\n val S = N.toLong * (N + 1) / 2\n\n def find: Option[Int] = {\n rep(N - 1, 2) { m =>\n if (S % m == 0) return Some(m)\n }\n None\n }\n\n find match {\n case None =>\n out.println(\"No\")\n\n case Some(m) =>\n out.println(\"Yes\")\n out.println(s\"1 $m\")\n\n out.print(s\"${N - 1} \")\n out.println(map(N)(identity).map(_+1).filterNot(_ == m).mkString(\" \"))\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\n }\n\n def gcd(a: Int, b: Int): Int = {\n val r = a % b\n if (r == 0) b\n else gcd(b, r)\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": [], "src_uid": "bb7bace930d5c5f231bfc2061576ec45"} {"nl": {"description": "A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters \u00ab+\u00bb and \u00ab1\u00bb into this sequence. For example, sequences \u00ab(())()\u00bb, \u00ab()\u00bb and \u00ab(()(()))\u00bb are regular, while \u00ab)(\u00bb, \u00ab(()\u00bb and \u00ab(()))(\u00bb are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?", "input_spec": "Input consists of a single line with non-empty string of \u00ab(\u00bb and \u00ab)\u00bb characters. Its length does not exceed 106.", "output_spec": "Output the maximum possible length of a regular bracket sequence.", "sample_inputs": ["(()))(", "((()())"], "sample_outputs": ["4", "6"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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}"}], "negative_code": [], "src_uid": "2ce2d0c4ac5e630bafad2127a1b589dd"} {"nl": {"description": "Consider a table of size $$$n \\times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 115$$$) \u2014 the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \\ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.", "output_spec": "Output two integers $$$r$$$ and $$$c$$$ ($$$1 \\le r \\le n$$$, $$$1 \\le c \\le m$$$) separated by a space \u2014 the row and column numbers of the center of the black square.", "sample_inputs": ["5 6\nWWBBBW\nWWBBBW\nWWBBBW\nWWWWWW\nWWWWWW", "3 3\nWWW\nBWW\nWWW"], "sample_outputs": ["2 4", "2 1"], "notes": null}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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}"}, {"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"}], "negative_code": [], "src_uid": "524273686586cdeb7827ffc1ad59d85a"} {"nl": {"description": "Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.", "input_spec": "The first line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20091000), consisting of lowercase English characters only. The second line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000).", "output_spec": "On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.", "sample_inputs": ["banana\n4", "banana\n3", "banana\n2"], "sample_outputs": ["2\nbaan", "3\nnab", "-1"], "notes": "NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters \"nab\". She can take characters \"nab\" from the first sheet, \"na\" from the second, and \"a\" from the third, and arrange them to from \"banana\"."}, "positive_code": [{"source_code": "object A extends App {\n\n def readString = Console.readLine\n\n val s = readString\n val n = readString.toInt\n \n def check(m: Int) : String = {\n val sb = new StringBuilder()\n var len = 0\n for (c <- chars) {\n val need = counts(c)\n val add = (need - 1) / m + 1\n len += add\n sb ++= (c.toString * add)\n }\n if (len <= n) {\n if (len < n) {\n sb ++= (\"a\" * (n - len))\n }\n sb.toString\n } else \"\"\n }\n \n val chars = s.distinct\n val groups = s.groupBy(identity)\n val counts = groups.map(cs => (cs._1, cs._2.length))\n \n if (chars.size > n) {\n println(-1)\n } else {\n var lo = 1\n var hi = 1000\n var best = \"\"\n var bestM = 0\n while (lo <= hi) {\n val mid = lo + (hi - lo) / 2\n val str = check(mid)\n //println(lo, hi, mid, str)\n if (str == \"\") {\n lo = mid + 1 \n } else {\n hi = mid - 1\n best = str\n bestM = mid\n }\n }\n println(bestM)\n\tprintln(best)\n }\n}"}], "negative_code": [], "src_uid": "f16f00edbc0c2e984caa04f71ae0324e"} {"nl": {"description": "Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter \"X\". Valera's teacher thinks that the letters on the piece of paper form an \"X\", if: on both diagonals of the square paper all letters are the same; all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009<\u2009300; n is odd). Each of the next n lines contains n small English letters \u2014 the description of Valera's paper.", "output_spec": "Print string \"YES\", if the letters on the paper form letter \"X\". Otherwise, print string \"NO\". Print the strings without quotes.", "sample_inputs": ["5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox", "3\nwsw\nsws\nwsw", "3\nxpx\npxp\nxpe"], "sample_outputs": ["NO", "YES", "NO"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \\le n \\le 10^9$$$, $$$1 \\le s \\le n$$$, $$$1 \\le k \\le \\min(n-1, 1000)$$$)\u00a0\u2014 respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \\ldots, a_k$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.", "sample_inputs": ["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"], "sample_outputs": ["2\n0\n4\n0\n2"], "notes": "NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val t = readInt\n Stream.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1() {\n val Array(n, s, k) = readLine.split(\" \").map(_.toLong)\n val a = readLine.split(\" \").map(_.toLong)\n val x = Array.ofDim[Int](2000)\n a.foreach((z) => {\n val i = math.abs(s - z)\n if (i < 2000) { \n x(i.toInt) = x(i.toInt) + 1\n }\n })\n val ans = if (x(0) == 0) 0 else x.zipWithIndex.indexWhere{\n case (v, i) => i != 0 && (if (s - i <= 0 || s + i > n) v < 1 else v < 2)\n }\n println(ans)\n }\n}"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) {\n val t = readInt\n Stream.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1() {\n val Array(n, s, k) = readLine.split(\" \").map(_.toLong)\n val a = readLine.split(\" \").map(_.toLong)\n val x = Array.ofDim[Int](2000)\n a.foreach((z) => {\n val i = math.abs(s - z)\n if (i < 2000) { \n x(i.toInt) = x(i.toInt) + 1\n }\n })\n val ans = if (x(0) == 0) 0 else x.zipWithIndex.indexWhere{\n case (v, i) => i != 0 && (if (s - i <= 0) v < 1 else v < 2)\n }\n println(ans)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val t = readInt\n Stream.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1() {\n val Array(n, s, k) = readLine.split(\" \").map(_.toLong)\n val a = readLine.split(\" \").map(_.toLong)\n val x = (List.tabulate(1000)((x) => s + x) ++ List.tabulate(1000)((x) => s - x).filter((i) => i > 0)).toSet\n val eset = a.foldLeft(x){\n case (set, i) => if (-1000 <= s - i && s - i < 1000) {\n set - i.toInt\n } else set\n }.map((x) => math.abs(s - x))\n println(eset.min)\n }\n}"}, {"source_code": "object Main {\n def main(args: Array[String]) {\n val t = readInt\n Stream.fill(t)(f1).foldLeft(()){ case _ => () }\n }\n\n def f1() {\n val Array(n, s, k) = readLine.split(\" \").map(_.toLong)\n val a = readLine.split(\" \").map(_.toLong)\n val x = (List.tabulate(1000)((x) => s + x.toLong) ++ List.tabulate(1000)((x) => s - x.toLong).filter((i) => i > 0)).toSet\n val eset = a.foldLeft(x){\n case (set, i) => if (-1000 <= s - i && s - i < 1000) {\n set - i\n } else set\n }.map((x) => math.abs(s - x))\n println(eset.min)\n }\n}"}], "src_uid": "faae9c0868b92b2355947c9adcaefb43"} {"nl": {"description": "You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' \u2014 colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: \"RGBRGBRG\", \"GB\", \"R\", \"GRBGRBG\", \"BRGBRGB\". The following garlands are not nice: \"RR\", \"RGBG\".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' \u2014 colors of lamps in the garland.", "output_spec": "In the first line of the output print one integer $$$r$$$ \u2014 the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ \u2014 a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.", "sample_inputs": ["3\nBRB", "7\nRGBGRBB"], "sample_outputs": ["1\nGRB", "3\nRGBRGBR"], "notes": null}, "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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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"} {"nl": {"description": "Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.", "input_spec": "The first line of input will contain three integers n, m and k (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000, 0\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of vertices and edges in the graph, and the number of vertices that are homes of the government. The next line of input will contain k integers c1,\u2009c2,\u2009...,\u2009ck (1\u2009\u2264\u2009ci\u2009\u2264\u2009n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.", "output_spec": "Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.", "sample_inputs": ["4 1 2\n1 3\n1 2", "3 3 1\n2\n1 2\n1 3\n2 3"], "sample_outputs": ["2", "0"], "notes": "NoteFor the first sample test, the graph looks like this: Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this: We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple."}, "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\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}"}, {"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"} {"nl": {"description": "You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x\u2009/\u2009y.Your favorite rational number in the [0;1] range is p\u2009/\u2009q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p\u2009/\u2009q?", "input_spec": "The first line contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u20091000)\u00a0\u2014 the number of test cases. Each of the next t lines contains four integers x, y, p and q (0\u2009\u2264\u2009x\u2009\u2264\u2009y\u2009\u2264\u2009109; 0\u2009\u2264\u2009p\u2009\u2264\u2009q\u2009\u2264\u2009109; y\u2009>\u20090; q\u2009>\u20090). It is guaranteed that p\u2009/\u2009q is an irreducible fraction. Hacks. For hacks, an additional constraint of t\u2009\u2264\u20095 must be met.", "output_spec": "For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.", "sample_inputs": ["4\n3 10 1 2\n7 14 3 8\n20 70 2 7\n5 6 1 1"], "sample_outputs": ["4\n10\n0\n-1"], "notes": "NoteIn the first example, you have to make 4 successful submissions. Your success rate will be equal to 7\u2009/\u200914, or 1\u2009/\u20092.In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9\u2009/\u200924, or 3\u2009/\u20098.In the third example, there is no need to make any new submissions. Your success rate is already equal to 20\u2009/\u200970, or 2\u2009/\u20097.In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $$$n$$$ bosses in this tower, numbered from $$$1$$$ to $$$n$$$. The type of the $$$i$$$-th boss is $$$a_i$$$. If the $$$i$$$-th boss is easy then its type is $$$a_i = 0$$$, otherwise this boss is hard and its type is $$$a_i = 1$$$.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.For example: suppose $$$n = 8$$$, $$$a = [1, 0, 1, 1, 0, 1, 1, 1]$$$. Then the best course of action is the following: your friend kills two first bosses, using one skip point for the first boss; you kill the third and the fourth bosses; your friend kills the fifth boss; you kill the sixth and the seventh bosses; your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of bosses. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th boss. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.", "sample_inputs": ["6\n8\n1 0 1 1 0 1 1 1\n5\n1 1 1 1 0\n7\n1 1 1 1 0 0 1\n6\n1 1 1 1 1 1\n1\n1\n1\n0"], "sample_outputs": ["2\n2\n2\n2\n1\n0"], "notes": null}, "positive_code": [{"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 { u =>\n val n = readInt\n val a = readLine.split(\" \").map(_.toInt)\n val dp = Array.ofDim[Int](n+1, 2)\n dp(1)(0) = a(0)\n dp(1)(1) = a(0)\n if(n >= 2) {\n dp(2)(0) = dp(1)(0) + a(1)\n dp(2)(1) = dp(1)(0)\n }\n for(k <- 3 to n) {\n dp(k)(0) = min(dp(k-1)(1) + a(k - 1), dp(k-2)(1) + a(k-1) + a(k-2))\n dp(k)(1) = min(dp(k-1)(0), dp(k-2)(0))\n }\n println(min(dp(n)(0), dp(n)(1)))\n }\n }\n}\n"}], "negative_code": [], "src_uid": "d34ffd75ef82111d1077db4b033d5195"} {"nl": {"description": "There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1\\le t\\le 2\\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$2\\le n\\le 2\\cdot{10}^{5}$$$) \u2014 the size of the chessboard. The second line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to an enemy pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. The third line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to a Gregor's pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. It is guaranteed that the sum of $$$n$$$ across all test cases is less than $$$2\\cdot{10}^{5}$$$.", "output_spec": "For each test case, print one integer: the maximum number of Gregor's pawns which can reach the $$$1$$$-st row.", "sample_inputs": ["4\n3\n000\n111\n4\n1111\n1111\n3\n010\n010\n5\n11001\n00000"], "sample_outputs": ["3\n4\n0\n0"], "notes": "NoteIn the first example, Gregor can simply advance all $$$3$$$ of his pawns forward. Thus, the answer is $$$3$$$.In the second example, Gregor can guarantee that all $$$4$$$ of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this \"game\"! In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly $$$0$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "You are given a permutation of n numbers p1,\u2009p2,\u2009...,\u2009pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l\u2009\u2264\u2009r) and reverse the order of the elements pl,\u2009pl\u2009+\u20091,\u2009...,\u2009pr. Your task is to find the expected value of the number of inversions in the resulting permutation.", "input_spec": "The first line of input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u2009109). The next line contains n integers p1,\u2009p2,\u2009...,\u2009pn \u2014 the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem G1 (3 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u20096, 1\u2009\u2264\u2009k\u2009\u2264\u20094 will hold. In subproblem G2 (5 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u200930, 1\u2009\u2264\u2009k\u2009\u2264\u2009200 will hold. In subproblem G3 (16 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u2009109 will hold. ", "output_spec": "Output the answer with absolute or relative error no more than 1e\u2009-\u20099.", "sample_inputs": ["3 1\n1 2 3", "3 4\n1 3 2"], "sample_outputs": ["0.833333333333333", "1.458333333333334"], "notes": "NoteConsider the first sample test. We will randomly pick an interval of the permutation (1,\u20092,\u20093) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability we will inverse the first two elements' order and obtain the permutation (2,\u20091,\u20093) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1,\u20093,\u20092) with one inversion. Finally, with probability the randomly picked interval will contain all elements, leading to the permutation (3,\u20092,\u20091) with 3 inversions. Hence, the expected number of inversions is equal to ."}, "positive_code": [{"source_code": "import scala.collection._\n\nobject G extends App {\n\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 ps = readInts(n)\n var inversions = 0d\n var combinations = 0d\n\n def solve(arr0: Array[Int], depth: Int): Unit = {\n if (depth == 0) {\n combinations += 1d\n for (i <- 0 until n) {\n for (j <- 0 until i) if (arr0(j) > arr0(i)) inversions += 1d\n }\n } else {\n for (l <- 0 until n) {\n for (r <- l until n) {\n val arr = arr0.clone\n val mid = (r - l) / 2\n for (i <- 0 to mid) {\n val tmp = arr(l + i)\n arr(l + i) = arr(r - i)\n arr(r - i) = tmp\n }\n solve(arr, depth - 1)\n }\n }\n }\n }\n \n solve(ps, k)\n println(inversions / combinations)\n}\n"}], "negative_code": [], "src_uid": "0496f5b6c7c159e4448f5b04c45a411b"} {"nl": {"description": "Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.", "input_spec": "Same as the easy version, but the limits have changed: 1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009400\u2009000.", "output_spec": "Same as the easy version.", "sample_inputs": ["4 100\n1 2 2 1", "4 1\n1 2 2 1", "4 2\n1 2 3 1"], "sample_outputs": ["2", "3", "3"], "notes": null}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable\n\nobject A 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 read()\n val a = (1 to n).map(_ => int()).toArray\n val ab = Array.fill(n+1)(mutable.ArrayBuilder.make[Int])\n for {\n i <- 0 until n\n } ab(a(i)) += i\n val pos = ab.map(_.result().iterator)\n\n val set = new mutable.HashSet[Int]()\n val pq = new mutable.PriorityQueue[(Int, Int)]\n\n def addToPQ(i : Int, v: Int) = {\n val it = pos(v)\n var q = -1\n while (it.hasNext && q <= i) q = it.next\n if (q == -1 || q <= i) q = INF\n pq += ((q, v))\n }\n\n var ans = 0\n (0 until n).foreach { i =>\n val v = a(i)\n if (!set.contains(v)) {\n if (set.size == k)\n set.remove(pq.dequeue._2)\n set.add(v)\n ans += 1\n }\n addToPQ(i, v)\n }\n\n println(ans)\n}\n"}], "negative_code": [], "src_uid": "a9d6e888fdd10b4e6f2404f2b99ca5ef"} {"nl": {"description": "Given two integers $$$n$$$ and $$$x$$$, construct an array that satisfies the following conditions: for any element $$$a_i$$$ in the array, $$$1 \\le a_i<2^n$$$; there is no non-empty subsegment with bitwise XOR equal to $$$0$$$ or $$$x$$$, its length $$$l$$$ should be maximized. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.", "input_spec": "The only line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 18$$$, $$$1 \\le x<2^{18}$$$).", "output_spec": "The first line should contain the length of the array $$$l$$$. If $$$l$$$ is positive, the second line should contain $$$l$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\dots$$$, $$$a_l$$$ ($$$1 \\le a_i < 2^n$$$)\u00a0\u2014 the elements of the array $$$a$$$. If there are multiple solutions, print any of them.", "sample_inputs": ["3 5", "2 4", "1 1"], "sample_outputs": ["3\n6 1 3", "3\n1 3 1", "0"], "notes": "NoteIn the first example, the bitwise XOR of the subsegments are $$$\\{6,7,4,1,2,3\\}$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, X = ni()\n val cum = ArrayBuffer[Int]()\n cum += 0\n val used = Array.ofDim[Boolean](1 << 18)\n TO(1, (1 << N) - 1) { i =>\n if (!used(X^i) && i != X) {\n used(i) = true\n cum += i\n }\n }\n debug(cum.mkString(\" \"))\n\n val ans = Array.ofDim[Int](cum.length - 1)\n REP(ans.length) { i =>\n ans(i) = cum(i + 1) ^ cum(i)\n }\n out.println(ans.length)\n out.println(ans.mkString(\" \"))\n }\n}"}], "negative_code": [], "src_uid": "16c2969b3532c912221825af6040b5c7"} {"nl": {"description": "Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \\le i \\le n)$$$, $$$\\sum\\limits_{j = 1}^{i}w_j \\ne x$$$.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 100$$$; $$$1 \\le x \\le 10^4$$$)\u00a0\u2014 the number of gold pieces that Phoenix has and the weight to avoid, respectively. The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \\le w_i \\le 100)$$$\u00a0\u2014 the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.", "output_spec": "For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.", "sample_inputs": ["3\n3 2\n3 2 1\n5 3\n1 2 3 4 8\n1 5\n5"], "sample_outputs": ["YES\n3 2 1\nYES\n8 1 2 3 4\nNO"], "notes": "NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode."}, "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 ws = nextInts(n)\n\n var sum = 0\n val res = Array.ofDim[Int](n)\n var ok = true\n var i = 0\n while (i < n) {\n if (sum + ws(i) == x) {\n if (i == n - 1) {\n ok = false\n i = n\n } else {\n res(i) = i + 1\n res(i + 1) = i\n sum += ws(i)\n sum += ws(i + 1)\n i += 2\n }\n } else {\n res(i) = i\n sum += ws(i)\n i += 1\n }\n }\n\n if (ok) {\n out.println(\"YES\")\n out.println(res.map(ws).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"}], "negative_code": [], "src_uid": "85383c9e802348a3153e7f98ce278f09"} {"nl": {"description": "Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $$$\\ell$$$ letters long. So, the scientists decided to write each word of this language as an integer from $$$0$$$ to $$$2^{\\ell} - 1$$$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $$$1001_2$$$ and $$$1100_2$$$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $$$x$$$ and $$$y$$$ as $$$d(x, y)$$$.Let the word have $$$n$$$ forms, the $$$i$$$-th of which is described with an integer $$$x_i$$$. All the $$$x_i$$$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $$$y$$$. Then, closeness of the word $$$y$$$ is equal to the sum of distances to each of the word forms, i.\u00a0e. the sum $$$d(x_i, y)$$$ over all $$$1 \\le i \\le n$$$.The initial form is the word $$$y$$$ with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the $$$n$$$ given forms.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The following are descriptions of the test cases. The first line contains two integers $$$n$$$ and $$$\\ell$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le \\ell \\le 30$$$) \u2014 the amount of word forms, and the number of letters in one word. The second line contains $$$n$$$ integers $$$x_i$$$ ($$$0 \\le x_i \\le 2^\\ell - 1$$$) \u2014 word forms. The integers are not necessarily different.", "output_spec": "For each test, print a single integer, the initial form of the word, i.\u00a0e. such $$$y$$$ ($$$0 \\le y \\le 2^\\ell - 1$$$) that the sum $$$d(x_i, y)$$$ over all $$$1 \\le i \\le n$$$ is minimal possible. Note that $$$y$$$ can differ from all the integers $$$x_i$$$. If there are multiple ways to restore the initial form, print any.", "sample_inputs": ["7\n3 5\n18 9 21\n3 5\n18 18 18\n1 1\n1\n5 30\n1 2 3 4 5\n6 10\n99 35 85 46 78 55\n2 1\n0 1\n8 8\n5 16 42 15 83 65 78 42"], "sample_outputs": ["17\n18\n1\n1\n39\n0\n2"], "notes": "NoteIn the first test case, the words can be written as $$$x_1 = 10010_2$$$, $$$x_2 = 01001_2$$$ and $$$x_3 = 10101_2$$$ in binary. Let $$$y = 10001_2$$$. Then, $$$d(x_1, y) = 2$$$ (the difference is in the fourth and the fifth positions), $$$d(x_2, y) = 2$$$ (the difference is in the first and the second positions), $$$d(x_3, y) = 1$$$ (the difference is in the third position). So, the closeness is $$$2 + 2 + 1 = 5$$$. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to $$$18$$$ ($$$10010_2$$$ in binary), so the initial form is also $$$18$$$. It's easy to see that closeness is equal to zero in this case."}, "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 c: Long)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 for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n val arr = new Array[Int](n+1)\n val cnt = new Array[Int](35)\n for (i <- 0 to 30) {\n cnt(i) = 0\n }\n for (i <- 1 to n) {\n arr(i) = readInt()\n var po = 0\n while (arr(i) > 0) {\n if (arr(i) % 2 == 1) {\n cnt(po) += 1\n }\n arr(i) /= 2\n po += 1\n }\n }\n var ans = 0L\n for (i <- (0 to 29).reverse) {\n if (cnt(i) >= n-cnt(i)) {\n ans += 1L\n }\n if (i > 0)\n ans *= 2L\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}"}], "negative_code": [], "src_uid": "84c88932e107e1d1f80b44aec88134e4"} {"nl": {"description": "After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1\u2009\u2264\u2009si\u2009\u2264\u20094), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of groups of schoolchildren. The second line contains a sequence of integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u20094). The integers are separated by a space, si is the number of children in the i-th group.", "output_spec": "Print the single number \u2014 the minimum number of taxis necessary to drive all children to Polycarpus.", "sample_inputs": ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars."}, "positive_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) = ( (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\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": "/*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": "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 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 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": "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": "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"}, {"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 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": "/**\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.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": "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": "\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}"}, {"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 //\u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0441\u043e\u0431\u0440\u0430\u043d\u043d\u044b\n val fFour = counts(4)\n\n //\u0447\u0438\u0441\u043b\u043e \u0441\u043a\u043e\u043c\u0431\u0435\u043d\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 3 \u0438 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 // \u043a\u043e\u043c\u0431\u0438\u043d\u0438\u0440\u0443\u0435\u043c 2 \u0441 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": "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": "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\u00e1s 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.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": "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": "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": "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}"}], "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 //\u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0441\u043e\u0431\u0440\u0430\u043d\u043d\u044b\n val fFour = counts(4)\n\n //\u0447\u0438\u0441\u043b\u043e \u0441\u043a\u043e\u043c\u0431\u0435\u043d\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 3 \u0438 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 // \u043a\u043e\u043c\u0431\u0438\u043d\u0438\u0440\u0443\u0435\u043c 2 \u0441 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 //\u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0441\u043e\u0431\u0440\u0430\u043d\u043d\u044b\n val fFour = counts(4)\n\n //\u0447\u0438\u0441\u043b\u043e \u0441\u043a\u043e\u043c\u0431\u0435\u043d\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 3 \u0438 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 // \u043a\u043e\u043c\u0431\u0438\u043d\u0438\u0440\u0443\u0435\u043c 2 \u0441 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 //\u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0441\u043e\u0431\u0440\u0430\u043d\u043d\u044b\n val fFour = counts(4)\n\n //\u0447\u0438\u0441\u043b\u043e \u0441\u043a\u043e\u043c\u0431\u0435\u043d\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 3 \u0438 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 // \u043a\u043e\u043c\u0431\u0438\u043d\u0438\u0440\u0443\u0435\u043c 2 \u0441 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 //\u0447\u0435\u0442\u0432\u0435\u0440\u043a\u0438 \u0441\u043e\u0431\u0440\u0430\u043d\u043d\u044b\n val fFour = counts(4)\n\n //\u0447\u0438\u0441\u043b\u043e \u0441\u043a\u043e\u043c\u0431\u0435\u043d\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 3 \u0438 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 // \u043a\u043e\u043c\u0431\u0438\u043d\u0438\u0440\u0443\u0435\u043c 2 \u0441 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\u00e1s 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"} {"nl": {"description": "She is skilled in all kinds of magics, and is keen on inventing new one.\u2014Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has $$$n$$$ magical tokens. Their magical power can be represented with positive integers $$$a_1, a_2, \\ldots, a_n$$$. Patchouli may perform the following two operations on the tokens. Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens. Reduction: Patchouli chooses a token with an even value of magical power $$$x$$$, removes it and creates a new token with magical power equal to $$$\\frac{x}{2}$$$. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$) \u2014 the number of test cases. The description of the test cases follows. For each test case, the first line contains one integer $$$n$$$ ($$$1 \\leq n\\leq 2\\cdot 10^5$$$) \u2014 the initial number of tokens. The second line contains $$$n$$$ intergers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 the initial magical power of the $$$n$$$ tokens. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer \u2014 the minimum number of operations Patchouli needs to make all tokens have an odd value of magical power. It can be shown that under such restrictions the required sequence of operations exists. ", "sample_inputs": ["4\n\n2\n\n1 9\n\n3\n\n1 1 2\n\n3\n\n2 4 8\n\n3\n\n1049600 33792 1280"], "sample_outputs": ["0\n1\n3\n10"], "notes": "NoteTest case 1:$$$a$$$ consists solely of odd numbers initially.Test case 2:Choose the tokens with magical power of $$$1$$$ and $$$2$$$ and perform Fusion. Now $$$a=[1,3]$$$, both are odd numbers.Test case 3:Choose the tokens with magical power of $$$2$$$ and $$$8$$$ and perform Fusion. Now $$$a=[4,10]$$$.Choose the token with magical power of $$$10$$$ and perform Reduction. Now $$$a=[4,5]$$$.Choose the tokens with magical power of $$$4$$$ and $$$5$$$ and perform Fusion. Now $$$a=[9]$$$, and $$$9$$$ is an odd number.It can be shown that you can not make all the magical powers odd numbers in less than $$$3$$$ moves, so the answer is $$$3$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Mark is asked to take a group photo of $$$2n$$$ people. The $$$i$$$-th person has height $$$h_i$$$ units.To do so, he ordered these people into two rows, the front row and the back row, each consisting of $$$n$$$ people. However, to ensure that everyone is seen properly, the $$$j$$$-th person of the back row must be at least $$$x$$$ units taller than the $$$j$$$-th person of the front row for each $$$j$$$ between $$$1$$$ and $$$n$$$, inclusive.Help Mark determine if this is possible.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1\\leq t\\leq 100$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains two positive integers $$$n$$$ and $$$x$$$ ($$$1\\leq n\\leq 100$$$, $$$1\\leq x\\leq 10^3$$$) \u2014 the number of people in each row and the minimum difference Mark wants. The second line of each test case contains $$$2n$$$ positive integers $$$h_1,h_2,\\ldots,h_{2n}$$$ ($$$1\\leq h_i\\leq 10^3$$$) \u2014 the height of each person in units. Note that the sum of $$$n$$$ over all test cases is not bounded.", "output_spec": "For each test case, print a single line containing \"YES\" if Mark could arrange people satisfying his condition and \"NO\" otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answers).", "sample_inputs": ["3\n\n3 6\n\n1 3 9 10 12 16\n\n3 1\n\n2 5 2 2 2 5\n\n1 2\n\n8 6"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteIn the first test case, one possible order is to have the third, fifth, and sixth person on the back row and the second, first, and fourth on the front row. The heights of the people will look like this. Back$$$9$$$$$$12$$$$$$16$$$Front$$$3$$$$$$1$$$$$$10$$$ It works because $$$h_3-h_2 = 9-3 \\geq 6$$$, $$$h_5-h_1 = 12-1\\geq 6$$$, and $$$h_6-h_4 = 16-10\\geq 6$$$. In the second test case, it can be shown there is no way to order people in a way that satisfies the condition.In the third test case, the only way to arrange people to satisfy the condition is to have the first person on the back row and the second person on the front row."}, "positive_code": [{"source_code": "import scala.io.StdIn._\r\nimport scala.util.control.Breaks.break\r\nobject Main extends App{\r\n var x=readInt()\r\n while(x!=0){\r\n val y=readLine().split(\" \").map(_.toInt)\r\n val h=y(1)\r\n val z=readLine().split(\" \").map(_.toInt).sorted\r\n val pad= y(0)\r\n var flag=1\r\n for(i <- 0 until pad){\r\n if((z(i+pad)-z(i)) 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"} {"nl": {"description": "Imagine that there is a group of three friends: A, B and \u0421. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100;\u00a00\u2009\u2264\u2009m\u2009\u2264\u2009104). The next m lines contain the debts. The i-th line contains three integers ai,\u2009bi,\u2009ci (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi;\u00a01\u2009\u2264\u2009ci\u2009\u2264\u2009100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x,\u2009y) and pair of people (y,\u2009x).", "output_spec": "Print a single integer \u2014 the minimum sum of debts in the optimal rearrangement.", "sample_inputs": ["5 3\n1 2 10\n2 3 1\n2 4 1", "3 0", "4 3\n1 2 1\n2 3 1\n3 1 1"], "sample_outputs": ["10", "0", "0"], "notes": "NoteIn the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.In the second sample, there are no debts.In the third sample, you can annul all the debts."}, "positive_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.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"}, {"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"} {"nl": {"description": "You're given an array $$$a$$$ of $$$n$$$ integers, such that $$$a_1 + a_2 + \\cdots + a_n = 0$$$.In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$), decrement $$$a_i$$$ by one and increment $$$a_j$$$ by one. If $$$i < j$$$ this operation is free, otherwise it costs one coin.How many coins do you have to spend in order to make all elements equal to $$$0$$$?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 5000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u00a0\u2014 the number of elements. The next line contains $$$n$$$ integers $$$a_1, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$). It is given that $$$\\sum_{i=1}^n a_i = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the minimum number of coins we have to spend in order to make all elements equal to $$$0$$$.", "sample_inputs": ["7\n4\n-3 5 -3 1\n2\n1 -1\n4\n-3 2 -3 4\n4\n-1 1 1 -1\n7\n-5 7 -6 -4 17 -13 4\n6\n-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000\n1\n0"], "sample_outputs": ["3\n0\n4\n1\n8\n3000000000\n0"], "notes": "NotePossible strategy for the first test case: Do $$$(i=2, j=3)$$$ three times (free), $$$a = [-3, 2, 0, 1]$$$. Do $$$(i=2, j=1)$$$ two times (pay two coins), $$$a = [-1, 0, 0, 1]$$$. Do $$$(i=4, j=1)$$$ one time (pay one coin), $$$a = [0, 0, 0, 0]$$$. "}, "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": "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"}, {"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"} {"nl": {"description": "You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace \"01\" with \"10\" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace \"12\" with \"21\" or vice versa).For example, for string \"010210\" we can perform the following moves: \"010210\" $$$\\rightarrow$$$ \"100210\"; \"010210\" $$$\\rightarrow$$$ \"001210\"; \"010210\" $$$\\rightarrow$$$ \"010120\"; \"010210\" $$$\\rightarrow$$$ \"010201\". Note than you cannot swap \"02\" $$$\\rightarrow$$$ \"20\" and vice versa. You cannot perform any other operations with the given string excluding described above.You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).String $$$a$$$ is lexicographically less than string $$$b$$$ (if strings $$$a$$$ and $$$b$$$ have the same length) if there exists some position $$$i$$$ ($$$1 \\le i \\le |a|$$$, where $$$|s|$$$ is the length of the string $$$s$$$) such that for every $$$j < i$$$ holds $$$a_j = b_j$$$, and $$$a_i < b_i$$$.", "input_spec": "The first line of the input contains the string $$$s$$$ consisting only of characters '0', '1' and '2', its length is between $$$1$$$ and $$$10^5$$$ (inclusive).", "output_spec": "Print a single string \u2014 the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).", "sample_inputs": ["100210", "11222121", "20"], "sample_outputs": ["001120", "11112222", "20"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "You are given n numbers a1,\u2009a2,\u2009...,\u2009an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make as large as possible, where denotes the bitwise OR. Find the maximum possible value of after performing at most k operations optimally.", "input_spec": "The first line contains three integers n, k and x (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u200910, 2\u2009\u2264\u2009x\u2009\u2264\u20098). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Output the maximum value of a bitwise OR of sequence elements after performing operations.", "sample_inputs": ["3 1 2\n1 1 1", "4 2 3\n1 2 4 8"], "sample_outputs": ["3", "79"], "notes": "NoteFor the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is . For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result."}, "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, x) = readInts(3)\n val as = readLongs(n)\n val prefix = as.scanLeft(0L)(_ | _)\n val suffix = as.scanRight(0L)(_ | _)\n \n var mult = 1L\n for (_ <- 0 until k) mult *= x\n\n var res = 0L\n \n for (i <- 0 until n) {\n val or = prefix(i) | suffix(i + 1) | as(i) * mult\n if (or > res) res = or\n }\n\n println(res)\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, k, x) = readInts(3)\n val as = readLongs(n)\n var res = as.max\n val maxPos = as.indexOf(res)\n \n for (_ <- 0 until k) res *= x\n\n for (i <- 0 until n) if (i != maxPos) res |= as(i) \n\n println(res)\n}\n"}], "src_uid": "b544f02d12846026f6c76876bc6bd079"} {"nl": {"description": "The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $$$n \\times m$$$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as \"X\" while the remaining ones were marked as \".\". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $$$0$$$) some trees were set on fire. At the beginning of minute $$$0$$$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $$$8$$$ neighboring trees. At the beginning of minute $$$T$$$, the fire was extinguished.The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $$$T$$$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $$$T$$$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.Note that you'd like to maximize value $$$T$$$ but the set of trees can be arbitrary.", "input_spec": "The first line contains two integer $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^6$$$, $$$1 \\le n \\cdot m \\le 10^6$$$) \u2014 the sizes of the map. Next $$$n$$$ lines contain the map. The $$$i$$$-th line corresponds to the $$$i$$$-th row of the map and contains $$$m$$$-character string. The $$$j$$$-th character of the $$$i$$$-th string is \"X\" if the corresponding tree is burnt and \".\" otherwise. It's guaranteed that the map contains at least one \"X\".", "output_spec": "In the first line print the single integer $$$T$$$ \u2014 the maximum time the Forest was on fire. In the next $$$n$$$ lines print the certificate: the map ($$$n \\times m$$$ rectangle) where the trees that were set on fire are marked as \"X\" and all other trees are marked as \".\".", "sample_inputs": ["3 6\nXXXXXX\nXXXXXX\nXXXXXX", "10 10\n.XXXXXX...\n.XXXXXX...\n.XXXXXX...\n.XXXXXX...\n.XXXXXXXX.\n...XXXXXX.\n...XXXXXX.\n...XXXXXX.\n...XXXXXX.\n..........", "4 5\nX....\n..XXX\n..XXX\n..XXX"], "sample_outputs": ["1\n......\n.X.XX.\n......", "2\n..........\n..........\n...XX.....\n..........\n..........\n..........\n.....XX...\n..........\n..........\n..........", "0\nX....\n..XXX\n..XXX\n..XXX"], "notes": null}, "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 /**\n * \u5358\u8abf\u6e1b\u5c11\n * [l, h) \u65b9\u5f0f\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\n def add(a: Array[Array[Int]], x1: Int, y1: Int, x2: Int, y2: Int, v: Int): Unit = {\n a(y1)(x1) += 1\n a(y1)(x2 + 1) -= 1\n a(y2 + 1)(x1) -= 1\n a(y2 + 1)(x2 + 1) += 1\n }\n\n def imos(a: Array[Array[Int]]) = {\n val n = a.length - 1\n val m = a(0).length - 1\n REP(n + 1) { i =>\n REP(m) { j =>\n a(i)(j + 1) += a(i)(j)\n }\n }\n REP(m + 1) { j =>\n REP(n) { i =>\n a(i + 1)(j) += a(i)(j)\n }\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val g = Array.fill[Char](N + 2, M + 2)('.')\n REP(N) { i =>\n val s = ns(M)\n REP(M) { j =>\n g(i + 1)(j + 1) = s(j)\n }\n }\n val MAX = (min(N, M) - 1) / 2\n val flg = Array.ofDim[Int](MAX * 2 + N + 3, MAX * 2 + M + 3)\n val campus = Array.ofDim[Int](N + 1, M + 1)\n\n debug(g.map(_.mkString).mkString(\"\\n\"))\n debug(s\"MAX:$MAX\")\n\n def mkFlg(x: Int): Unit = {\n REP(flg.length) { i =>\n import java.util\n util.Arrays.fill(flg(i), 0)\n }\n REP(N + 2) { i =>\n REP(M + 2) { j =>\n if (g(i)(j) == '.') {\n add(flg, MAX + j - x, MAX + i - x, MAX + j + x, MAX + i + x, 1)\n }\n }\n }\n imos(flg)\n }\n\n def paint(x: Int): Unit = {\n REP(campus.length) { i =>\n import java.util\n util.Arrays.fill(campus(i), 0)\n }\n REP(N) { i =>\n REP(M) { j =>\n if (flg(MAX + i + 1)(MAX + j + 1) == 0) {\n add(campus, j - x, i - x, j + x, i + x, 1)\n }\n }\n }\n imos(campus)\n }\n\n def testCampus: Boolean = {\n REP(N) { i =>\n REP(M) { j =>\n val actual = campus(i)(j) == 0\n val expected = g(i + 1)(j + 1) == '.'\n// debug(s\"$i:$j $actual $expected\")\n if (actual != expected) {\n debug(s\"RETURN $i:$j $actual $expected\")\n return false\n }\n }\n }\n true\n }\n\n def test(x: Int): Boolean = {\n debug(s\"test($x)\")\n mkFlg(x)\n debug(\"show flag\")\n debugDim(flg)\n paint(x)\n debug(\"show campus\")\n debugDim(campus)\n val res = testCampus\n debug(s\"test($x)=$res\")\n res\n }\n\n val k = findMax(test, 0, MAX)\n mkFlg(k)\n val ans = Array.ofDim[Char](N, M)\n REP(N) { i =>\n REP(M) { j =>\n ans(i)(j) = if (flg(MAX + i + 1)(MAX + j + 1) == 0) 'X' else '.'\n }\n }\n\n out.println(k)\n REP(N) { i =>\n out.println(ans(i).mkString)\n }\n }\n}"}], "negative_code": [], "src_uid": "9602fa7b9d05560959ee5fdeeb1f6507"} {"nl": {"description": "Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers the condition |ci\u2009-\u2009cj|\u2009\u2264\u20091 must hold. if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1,\u20091,\u20092,\u20092] satisfies this condition while the subsequence [1,\u20092,\u20092,\u20091] doesn't. Note that [1,\u20091,\u20092,\u20092] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8\u00a0\u2014 the description of Vladik's sequence.", "output_spec": "Print single integer\u00a0\u2014 the length of the longest subsequence of Vladik's sequence that satisfies both conditions.", "sample_inputs": ["3\n1 1 1", "8\n8 7 6 5 4 3 2 1", "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8"], "sample_outputs": ["1", "8", "17"], "notes": "NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer: Integer a (1\u2009\u2264\u2009a\u2009\u2264\u2009105) means that Inna gives Dima a command to add number a into one of containers. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers. ", "output_spec": "Each command of the input must correspond to one line of the output \u2014 Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice: pushStack \u2014 add to the end of the stack; pushQueue \u2014 add to the end of the queue; pushFront \u2014 add to the beginning of the deck; pushBack \u2014 add to the end of the deck. For a command of the second type first print an integer k (0\u2009\u2264\u2009k\u2009\u2264\u20093), that shows the number of extract operations, then print k words separated by space. The words can be: popStack \u2014 extract from the end of the stack; popQueue \u2014 extract from the beginning of the line; popFront \u2014 extract from the beginning from the deck; popBack \u2014 extract from the end of the deck. The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.", "sample_inputs": ["10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0", "4\n1\n2\n3\n0"], "sample_outputs": ["0\npushStack\n1 popStack\npushStack\npushQueue\n2 popStack popQueue\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront", "pushStack\npushQueue\npushFront\n3 popStack popQueue popFront"], "notes": null}, "positive_code": [{"source_code": "import scala.collection._\n\nobject C extends App {\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val n = readInt\n val as = Array.fill(n)(readInt)\n\n var end = 0\n \n while (end < as.size) {\n val start = end\n val end0 = as.indexWhere(_ == 0, start)\n end = if (end0 < 0) as.size else end0\n val bs = as.slice(start, end)\n val k = math.min(bs.size, 3)\n val sorted = bs.sorted.reverse\n var toQueue = if (k > 0) sorted(0) else -1\n var toStack = if (k > 1) sorted(1) else -1\n var toDeck = if (k > 2) sorted(2) else -1\n \n for (b <- bs) {\n if (b == toQueue) {\n println(\"pushQueue\")\n toQueue = -1\n } else if (b == toStack) {\n println(\"pushStack\")\n toStack = -1\n } else if (b == toDeck) {\n println(\"pushFront\")\n toDeck = -1\n } else {\n println(\"pushBack\")\n }\n }\n \n if (end0 >= 0) {\n print(k)\n if (k > 0) print(\" popQueue\")\n if (k > 1) print(\" popStack\")\n if (k > 2) print(\" popFront\")\n println\n end += 1\n }\n\n }\n\n Console.flush\n}"}], "negative_code": [], "src_uid": "07ae50199dd94f72313ee7675fefadb7"} {"nl": {"description": "Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out $$$n$$$ skewers parallel to each other, and enumerated them with consecutive integers from $$$1$$$ to $$$n$$$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $$$i$$$, it leads to turning $$$k$$$ closest skewers from each side of the skewer $$$i$$$, that is, skewers number $$$i - k$$$, $$$i - k + 1$$$, ..., $$$i - 1$$$, $$$i + 1$$$, ..., $$$i + k - 1$$$, $$$i + k$$$ (if they exist). For example, let $$$n = 6$$$ and $$$k = 1$$$. When Miroslav turns skewer number $$$3$$$, then skewers with numbers $$$2$$$, $$$3$$$, and $$$4$$$ will come up turned over. If after that he turns skewer number $$$1$$$, then skewers number $$$1$$$, $$$3$$$, and $$$4$$$ will be turned over, while skewer number $$$2$$$ will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $$$n$$$ skewers with the minimal possible number of actions. For example, for the above example $$$n = 6$$$ and $$$k = 1$$$, two turnings are sufficient: he can turn over skewers number $$$2$$$ and $$$5$$$.Help Miroslav turn over all $$$n$$$ skewers.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 1000$$$, $$$0 \\leq k \\leq 1000$$$)\u00a0\u2014 the number of skewers and the number of skewers from each side that are turned in one step.", "output_spec": "The first line should contain integer $$$l$$$\u00a0\u2014 the minimum number of actions needed by Miroslav to turn over all $$$n$$$ skewers. After than print $$$l$$$ integers from $$$1$$$ to $$$n$$$ denoting the number of the skewer that is to be turned over at the corresponding step.", "sample_inputs": ["7 2", "5 1"], "sample_outputs": ["2\n1 6", "2\n1 4"], "notes": "NoteIn the first example the first operation turns over skewers $$$1$$$, $$$2$$$ and $$$3$$$, the second operation turns over skewers $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$.In the second example it is also correct to turn over skewers $$$2$$$ and $$$5$$$, but turning skewers $$$2$$$ and $$$4$$$, or $$$1$$$ and $$$5$$$ are incorrect solutions because the skewer $$$3$$$ is in the initial state after these operations."}, "positive_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 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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces\u2019 superhero. Byteforces is a country that consists of n cities, connected by n\u2009-\u20091 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u2009123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n\u2009-\u20091 lines, describing the road system. Each line contains two city numbers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.", "output_spec": "First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique.", "sample_inputs": ["7 2\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n2 7", "6 4\n1 2\n2 3\n2 4\n4 5\n4 6\n2 4 5 6"], "sample_outputs": ["2\n3", "2\n4"], "notes": "NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number."}, "positive_code": [{"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).sorted\n val attackedSet = attacked.toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3, d4 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int, depth: Int): Unit = {\n d3(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)\n }\n\n def dfs4(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))\n d4(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attackedSet(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var u2 = attacked.min\n for (u <- attacked) {\n if ((d1(u) max d2(u)) > (d1(u2) max d2(u2))) {\n u2 = u\n }\n }\n dfs3(u2, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if ((d1(u) max d2(u) max d3(u)) > (d1(start) max d2(start) max d3(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs4(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}], "negative_code": [{"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))\n d3(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n dfs2(attacked.max, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs3(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3, d4 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int, depth: Int): Unit = {\n d3(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)\n }\n\n def dfs4(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))\n d4(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var u2 = attacked.min\n for (u <- attacked) {\n if ((d1(u) max d2(u)) > (d1(u2) max d2(u2))) {\n u2 = u\n }\n }\n dfs3(u2, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if ((d1(u) max d2(u) max d3(u)) > (d1(start) max d2(start) max d3(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs4(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).sorted\n val attackedSet = attacked.toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))\n d3(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attackedSet(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n dfs2(attacked.max, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs3(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))\n d3(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n dfs2(attacked.max, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs3(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"source_code": "import 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\n val Array(n, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).sorted\n val attackedSet = attacked.toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))\n d3(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attackedSet(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs3(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3, d4 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int, depth: Int): Unit = {\n d3(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)\n }\n\n def dfs4(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))\n d4(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var u2 = attacked.min\n for (u <- attacked) {\n if (d2(u) > d2(u2)) {\n u2 = u\n }\n }\n dfs3(u2, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if ((d2(u) max d3(u)) > (d2(start) max d3(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs4(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3, d4 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int, depth: Int): Unit = {\n d3(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)\n }\n\n def dfs4(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))\n d4(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var u2 = attacked.min\n for (u <- attacked) {\n if (d2(u) > d2(u2)) {\n u2 = u\n }\n }\n dfs3(u2, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if ((d1(u) max d2(u) max d3(u)) > (d1(start) max d2(start) max d3(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs4(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))\n d3(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs3(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3, d4 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int, depth: Int): Unit = {\n d3(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)\n }\n\n def dfs4(u: Int, prev: Int): Int = {\n var max = 0\n for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))\n d4(u) = max + 1\n max + 1\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min + 1)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n var u1 = attacked.min\n for (u <- attacked) {\n if (d1(u) > d1(u1)) {\n u1 = u\n }\n }\n dfs2(u1, -1, 0)\n var u2 = attacked.min\n for (u <- attacked) {\n if (d2(u) > d2(u2)) {\n u2 = u\n }\n }\n dfs3(u2, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if ((d3(u)) > (d3(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs4(start, -1)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}, {"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, m) = readInts(2)\n val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }\n\n for (_ <- 1 until n) {\n val Array(u, v) = readInts(2).map(_ - 1)\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n\n val attacked = readInts(m).map(_ - 1).toSet\n\n val adjs = adjBuilders.map(_.result)\n\n val d1, d2, d3 = Array.ofDim[Int](n)\n\n def dfs1(u: Int, prev: Int, depth: Int): Unit = {\n d1(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)\n }\n\n def dfs2(u: Int, prev: Int, depth: Int): Unit = {\n d2(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)\n }\n\n def dfs3(u: Int, prev: Int, depth: Int): Unit = {\n d3(u) = depth\n for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)\n }\n\n val sizes = Array.ofDim[Int](n)\n \n def size(u: Int, prev: Int): Int = {\n var s = if (attacked(u)) 1 else 0\n for (v <- adjs(u)) if (v != prev) s += size(v, u)\n sizes(u) = s\n s\n }\n\n def steps(u: Int, prev: Int, goBack: Boolean): Int = {\n val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)\n var s = if (goBack) 2 else 1\n for (i <- 0 until as.length - 1) s += steps(as(i), u, true)\n if (as.length > 0) s += steps(as.last, u, goBack)\n s\n }\n\n if (m == 1) {\n println(attacked.min)\n println(0)\n } else {\n dfs1(attacked.min, -1, 0)\n dfs2(attacked.max, -1, 0)\n var start = attacked.min\n for (u <- attacked) {\n if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {\n start = u\n }\n }\n size(start, -1)\n dfs3(start, -1, 0)\n println(start + 1)\n println(steps(start, -1, false) - 1)\n }\n}\n"}], "src_uid": "bda7d223eabfcc519a60801012c58616"} {"nl": {"description": "Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i\u2009+\u20091,\u2009i\u2009+\u20092,\u2009...,\u2009i\u2009+\u2009k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105,\u20091\u2009\u2264\u2009k\u2009\u2264\u20093\u00b7105). The next line contains n characters \u2014 the description of the road: the i-th character equals \".\", if the i-th sector contains no rocks. Otherwise, it equals \"#\". It is guaranteed that the first and the last characters equal \".\".", "output_spec": "Print \"YES\" (without the quotes) if Ksusha can reach the end of the road, otherwise print \"NO\" (without the quotes).", "sample_inputs": ["2 1\n..", "5 2\n.#.#.", "7 3\n.#.###."], "sample_outputs": ["YES", "YES", "NO"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * @author chengyi\n */\nobject KsushaSquirrel {\n \n def canPass(line:String, k:Int):String={\n //find the biggest consecutive #\n var num:Int = 0\n var maxNum:Int = 0\n for (a<-0 to line.length-1){\n val cur = line(a)\n if (cur=='#'){\n num = num + 1\n maxNum = Math.max(num, maxNum)\n }else if (cur=='.'){\n num = 0\n }\n }\n if (maxNumx.toInt}\n val n = nk(0)\n val k = nk(1)\n val line = StdIn.readLine()\n println(canPass(line, k))\n }\n \n}"}], "negative_code": [], "src_uid": "d504d894b2f6a830c4d3b4edc54395be"} {"nl": {"description": "Keshi is throwing a party and he wants everybody in the party to be happy.He has $$$n$$$ friends. His $$$i$$$-th friend has $$$i$$$ dollars. If you invite the $$$i$$$-th friend to the party, he will be happy only if at most $$$a_i$$$ people in the party are strictly richer than him and at most $$$b_i$$$ people are strictly poorer than him.Keshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1\\le t\\le 10^4)$$$ \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\\le n\\le 2 \\cdot 10^5)$$$ \u2014 the number of Keshi's friends. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ $$$(0 \\le a_i, b_i < n)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print the maximum number of people Keshi can invite.", "sample_inputs": ["3\n3\n1 2\n2 1\n1 1\n2\n0 0\n0 1\n2\n1 0\n0 1"], "sample_outputs": ["2\n1\n2"], "notes": "NoteIn the first test case, he invites the first and the second person. If he invites all of them, the third person won't be happy because there will be more than $$$1$$$ person poorer than him."}, "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 Main2 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, c: Double)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (b == that.b)\n return -1 * c.compareTo(that.c)\n else\n return -1 * b.compareTo(that.b)\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 for (tt <- 1 to t) {\n val n = readInt()\n val a = new Array[Int](n+1)\n val b = new Array[Int](n+1)\n for (i <- 1 to n) {\n a(i) = readInt()\n b(i) = readInt()\n }\n def check(kk: Int): Boolean = {\n var sz = 0\n for (i <- 1 to n) {\n if (a(i) >= kk-sz-1 && b(i) >= sz)\n sz += 1\n }\n if (sz >= kk)\n return true\n else\n return false\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 writer.println(bs(1, n))\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "93e9eb2c95fc9d86f526a03754ffd576"} {"nl": {"description": "In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways: If server is free and query queue is empty, then server immediately starts to process this query. If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue. If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.", "input_spec": "The first line of the input contains two integers n and b (1\u2009\u2264\u2009n,\u2009b\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of queries and the maximum possible size of the query queue. Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1\u2009\u2264\u2009ti,\u2009di\u2009\u2264\u2009109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti\u2009-\u20091\u2009<\u2009ti for all i\u2009>\u20091.", "output_spec": "Print the sequence of n integers e1,\u2009e2,\u2009...,\u2009en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or \u2009-\u20091 if the corresponding query will be rejected.", "sample_inputs": ["5 1\n2 9\n4 8\n10 9\n15 2\n19 1", "4 1\n2 8\n4 8\n10 9\n15 2"], "sample_outputs": ["11 19 -1 21 22", "10 18 27 -1"], "notes": "NoteConsider the first sample. The server will start to process first query at the moment 2 and will finish to process it at the moment 11. At the moment 4 second query appears and proceeds to the queue. At the moment 10 third query appears. However, the server is still busy with query 1, b\u2009=\u20091 and there is already query 2 pending in the queue, so third query is just rejected. At the moment 11 server will finish to process first query and will take the second query from the queue. At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue. At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there. Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue. Server finishes to process query number 5 at the moment 22. "}, "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, 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"}, {"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"} {"nl": {"description": "In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.", "input_spec": "The first line contains integer n \u2014 the number of Olympiads in 2013 (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the following n lines contains four integers mi, di, pi and ti \u2014 the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1\u2009\u2264\u2009mi\u2009\u2264\u200912, di\u2009\u2265\u20091, 1\u2009\u2264\u2009pi,\u2009ti\u2009\u2264\u2009100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year.", "output_spec": "Print a single number \u2014 the minimum jury size.", "sample_inputs": ["2\n5 23 1 2\n3 13 2 3", "3\n12 9 2 1\n12 8 1 3\n12 8 2 2", "1\n1 10 1 13"], "sample_outputs": ["2", "3", "1"], "notes": null}, "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\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"}, {"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"} {"nl": {"description": "You're given an array of $$$n$$$ integers between $$$0$$$ and $$$n$$$ inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is $$$[0, 2, 2, 1, 4]$$$, you can choose the second element and replace it by the MEX of the present elements \u00a0\u2014 $$$3$$$. Array will become $$$[0, 3, 2, 1, 4]$$$.You must make the array non-decreasing, using at most $$$2n$$$ operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them.\u00a0\u2013An array $$$b[1 \\ldots n]$$$ is non-decreasing if and only if $$$b_1 \\le b_2 \\le \\ldots \\le b_n$$$.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of $$$[2, 2, 1]$$$ is $$$0$$$, because $$$0$$$ does not belong to the array. The MEX of $$$[3, 1, 0, 1]$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the array, but $$$2$$$ does not. The MEX of $$$[0, 3, 1, 2]$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the array, but $$$4$$$ does not. It's worth mentioning that the MEX of an array of length $$$n$$$ is always between $$$0$$$ and $$$n$$$ inclusive.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 1000$$$)\u00a0\u2014 length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, \\ldots, a_n$$$ ($$$0 \\le a_i \\le n$$$)\u00a0\u2014 elements of the array. Note that they don't have to be distinct. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$.", "output_spec": "For each test case, you must output two lines: The first line must contain a single integer $$$k$$$ ($$$0 \\le k \\le 2n$$$) \u00a0\u2014 the number of operations you perform. The second line must contain $$$k$$$ integers $$$x_1, \\ldots, x_k$$$ ($$$1 \\le x_i \\le n$$$), where $$$x_i$$$ is the index chosen for the $$$i$$$-th operation. If there are many solutions, you can find any of them. Please remember that it is not required to minimize $$$k$$$.", "sample_inputs": ["5\n3\n2 2 3\n3\n2 1 0\n7\n0 7 3 1 3 7 7\n9\n2 0 1 1 2 4 4 2 0\n9\n8 4 7 6 1 2 3 0 5"], "sample_outputs": ["0\n\n2\n3 1\n4\n2 5 5 4\n11\n3 8 9 7 8 5 9 6 4 1 2\n10\n1 8 1 9 5 2 4 6 3 7"], "notes": "NoteIn the first test case, the array is already non-decreasing ($$$2 \\le 2 \\le 3$$$).Explanation of the second test case (the element modified by each operation is colored in red): $$$a = [2, 1, 0]$$$ ; the initial MEX is $$$3$$$. $$$a = [2, 1, \\color{red}{3}]$$$ ; the new MEX is $$$0$$$. $$$a = [\\color{red}{0}, 1, 3]$$$ ; the new MEX is $$$2$$$. The final array is non-decreasing: $$$0 \\le 1 \\le 3$$$. Explanation of the third test case: $$$a = [0, 7, 3, 1, 3, 7, 7]$$$ ; the initial MEX is $$$2$$$. $$$a = [0, \\color{red}{2}, 3, 1, 3, 7, 7]$$$ ; the new MEX is $$$4$$$. $$$a = [0, 2, 3, 1, \\color{red}{4}, 7, 7]$$$ ; the new MEX is $$$5$$$. $$$a = [0, 2, 3, 1, \\color{red}{5}, 7, 7]$$$ ; the new MEX is $$$4$$$. $$$a = [0, 2, 3, \\color{red}{4}, 5, 7, 7]$$$ ; the new MEX is $$$1$$$. The final array is non-decreasing: $$$0 \\le 2 \\le 3 \\le 4 \\le 5 \\le 7 \\le 7$$$. "}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n def isSorted(as: Array[Int]): Boolean = {\n var i = 1\n while (i < as.length) {\n if (as(i) < as(i - 1)) return false\n i += 1\n }\n true\n }\n\n def mex(counts: Array[Int]): Int = {\n var i = 0\n while (i < counts.length) {\n if (counts(i) == 0) return i\n i += 1\n }\n i\n }\n\n for (_ <- 1 to nextInt) {\n val n = nextInt\n val as = nextInts(n)\n val counts = Array.fill(n + 2)(0)\n for (a <- as) counts(a) += 1\n\n val res = mutable.ArrayBuffer.empty[Int]\n\n while (!isSorted(as)) {\n val m = mex(counts)\n val pos = if (m > n - 1) {\n var i = n - 1\n while (i > 0 && as(i) == i) {\n i -= 1\n }\n i\n } else m\n counts(as(pos)) -= 1\n counts(m) += 1\n as(pos) = m\n res += (pos + 1)\n //println(as.mkString(\" \"))\n }\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": [], "src_uid": "ebd4411d03bbce51e2b53064146644d4"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\\operatorname{AB}(s) = \\operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \\le i \\le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \\dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \\le |s| \\le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.", "output_spec": "For each test case, print the resulting string $$$s$$$ with $$$\\operatorname{AB}(s) = \\operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.", "sample_inputs": ["4\nb\naabbbabaa\nabbb\nabbaab"], "sample_outputs": ["b\naabbbabaa\nbbbb\nabbaaa"], "notes": "NoteIn the first test case, both $$$\\operatorname{AB}(s) = 0$$$ and $$$\\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\\operatorname{AB}(s) = 2$$$ and $$$\\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\\operatorname{AB}(s) = 1$$$ and $$$\\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\\operatorname{AB}(s) = 2$$$ and $$$\\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,\u2009b,\u2009c the following conditions held: a\u2009<\u2009b\u2009<\u2009c; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u200999999) \u2014 the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.", "output_spec": "If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.", "sample_inputs": ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"], "sample_outputs": ["-1", "1 2 4\n1 2 6"], "notes": null}, "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 = 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 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"}, {"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 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"}, {"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}"}], "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"} {"nl": {"description": "Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c \u2014 one through b and the other one through d, he calls the group a \"damn rhombus\". Note that pairs (a,\u2009b), (b,\u2009c), (a,\u2009d), (d,\u2009c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a \"damn rhombus\" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of \"damn rhombi\" in the city.When rhombi are compared, the order of intersections b and d doesn't matter.", "input_spec": "The first line of the input contains a pair of integers n, m (1\u2009\u2264\u2009n\u2009\u2264\u20093000,\u20090\u2009\u2264\u2009m\u2009\u2264\u200930000) \u2014 the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;ai\u2009\u2260\u2009bi) \u2014 the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one.", "output_spec": "Print the required number of \"damn rhombi\".", "sample_inputs": ["5 4\n1 2\n2 3\n1 4\n4 3", "4 12\n1 2\n1 3\n1 4\n2 1\n2 3\n2 4\n3 1\n3 2\n3 4\n4 1\n4 2\n4 3"], "sample_outputs": ["1", "12"], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "6e85f83d544eeb16f57523eb532abf04"} {"nl": {"description": "Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi,\u2009yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.", "input_spec": "The first line of the input contains a single integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). Each of the next n lines contains two integers xi and yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.", "output_spec": "Print three distinct integers on a single line\u00a0\u2014 the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.", "sample_inputs": ["3\n0 1\n1 0\n1 1", "5\n0 0\n0 2\n2 0\n2 2\n1 1"], "sample_outputs": ["1 2 3", "1 3 5"], "notes": "NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture. Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border)."}, "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 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"}, {"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: 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"}], "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"} {"nl": {"description": "The polar bears are going fishing. They plan to sail from (sx,\u2009sy) to (ex,\u2009ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x,\u2009y). If the wind blows to the east, the boat will move to (x\u2009+\u20091,\u2009y). If the wind blows to the south, the boat will move to (x,\u2009y\u2009-\u20091). If the wind blows to the west, the boat will move to (x\u2009-\u20091,\u2009y). If the wind blows to the north, the boat will move to (x,\u2009y\u2009+\u20091). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x,\u2009y). Given the wind direction for t seconds, what is the earliest time they sail to (ex,\u2009ey)?", "input_spec": "The first line contains five integers t,\u2009sx,\u2009sy,\u2009ex,\u2009ey (1\u2009\u2264\u2009t\u2009\u2264\u2009105,\u2009\u2009-\u2009109\u2009\u2264\u2009sx,\u2009sy,\u2009ex,\u2009ey\u2009\u2264\u2009109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: \"E\" (east), \"S\" (south), \"W\" (west) and \"N\" (north).", "output_spec": "If they can reach (ex,\u2009ey) within t seconds, print the earliest time they can achieve it. Otherwise, print \"-1\" (without quotes).", "sample_inputs": ["5 0 0 1 1\nSESNW", "10 5 3 3 6\nNENSWESNEE"], "sample_outputs": ["4", "-1"], "notes": "NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination."}, "positive_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(_.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\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\u2009+\u20091,\u2009y).\n // If the wind blows to the south, the boat will move to (x,\u2009y\u2009-\u20091).\n // If the wind blows to the west, the boat will move to (x\u2009-\u20091,\u2009y).\n // If the wind blows to the north, the boat will move to (x,\u2009y\u2009+\u20091). \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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions \"make a rectangle\" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.", "input_spec": "The first line of input will contain two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500), the dimensions of the puzzle piece. The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space. It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.", "output_spec": "Output \"YES\" if it is possible for Hongcow to make a rectangle. Output \"NO\" otherwise.", "sample_inputs": ["2 3\nXXX\nXXX", "2 2\n.X\nXX", "5 5\n.....\n..X..\n.....\n.....\n....."], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................"}, "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"}, {"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"}], "negative_code": [], "src_uid": "b395be2597f4cc0478bc45f774fa1c01"} {"nl": {"description": "Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of elements in the array. The second line contains n distinct space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the elements of array. The third line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of queries. The last line contains m space-separated integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the search queries. Note that the queries can repeat.", "output_spec": "Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specifier.", "sample_inputs": ["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"], "sample_outputs": ["1 2", "2 1", "6 6"], "notes": "NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element)."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.So imagine Monocarp got recommended $$$n$$$ songs, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th song had its predicted rating equal to $$$p_i$$$, where $$$1 \\le p_i \\le n$$$ and every integer from $$$1$$$ to $$$n$$$ appears exactly once. In other words, $$$p$$$ is a permutation.After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string $$$s$$$, such that $$$s_i=0$$$ means that he disliked the $$$i$$$-th song, and $$$s_i=1$$$ means that he liked it.Now the service has to re-evaluate the song ratings in such a way that: the new ratings $$$q_1, q_2, \\dots, q_n$$$ still form a permutation ($$$1 \\le q_i \\le n$$$; each integer from $$$1$$$ to $$$n$$$ appears exactly once); every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all $$$i, j$$$ such that $$$s_i=1$$$ and $$$s_j=0$$$, $$$q_i>q_j$$$ should hold). Among all valid permutations $$$q$$$ find the one that has the smallest value of $$$\\sum\\limits_{i=1}^n |p_i-q_i|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$.Print the permutation $$$q_1, q_2, \\dots, q_n$$$. If there are multiple answers, you can print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of songs. The second line of each testcase contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$)\u00a0\u2014 the permutation of the predicted ratings. The third line contains a single string $$$s$$$, consisting of $$$n$$$ characters. Each character is either a $$$0$$$ or a $$$1$$$. $$$0$$$ means that Monocarp disliked the song, and $$$1$$$ means that he liked it. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a permutation $$$q$$$\u00a0\u2014 the re-evaluated ratings of the songs. If there are multiple answers such that $$$\\sum\\limits_{i=1}^n |p_i-q_i|$$$ is minimum possible, you can print any of them.", "sample_inputs": ["3\n2\n1 2\n10\n3\n3 1 2\n111\n8\n2 3 1 8 5 4 7 6\n01110001"], "sample_outputs": ["2 1\n3 1 2\n1 6 5 8 3 2 4 7"], "notes": "NoteIn the first testcase, there exists only one permutation $$$q$$$ such that each liked song is rating higher than each disliked song: song $$$1$$$ gets rating $$$2$$$ and song $$$2$$$ gets rating $$$1$$$. $$$\\sum\\limits_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2$$$.In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to $$$p$$$. Its cost is $$$0$$$."}, "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 = nextInt\n val ps = nextInts(n)\n val s = nextLine\n\n val res0 = (0 until n).sortBy {\n i => (s(i), ps(i))\n }\n\n val res = Array.ofDim[Int](n)\n for (i <- 0 until n) {\n res(res0(i)) = 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"}], "negative_code": [], "src_uid": "0903a40d72c19a9d1cc1147d01ea94a7"} {"nl": {"description": "John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\\leq a_i, b_i, c_i, d_i\\leq 100$$$)\u00a0\u2014 the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$.", "output_spec": "Print the rank of Thomas Smith. Thomas's id is $$$1$$$.", "sample_inputs": ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$."}, "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 n = nextInt\n val arr = Array.ofDim[(Int, Int)](n)\n for(i <- arr.indices) {\n var sum = 0\n for(_ <- 1 to 4) {\n sum += nextInt\n }\n arr(i) = sum -> i\n }\n val res = arr.sorted(Ordering.Tuple2(Ordering.Int.reverse, Ordering.Int))\n .zipWithIndex.find(_._1._2 == 0).get._2\n println(res + 1)\n }\n\n }\n\n}\n\n\n"}], "negative_code": [], "src_uid": "3c984366bba580993d1694d27982a773"} {"nl": {"description": "You have decided to watch the best moments of some movie. There are two buttons on your player: Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t\u2009+\u2009x). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li,\u2009li\u2009+\u20091,\u2009...,\u2009ri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?", "input_spec": "The first line contains two space-separated integers n, x (1\u2009\u2264\u2009n\u2009\u2264\u200950, 1\u2009\u2264\u2009x\u2009\u2264\u2009105) \u2014 the number of the best moments of the movie and the value of x for the second button. The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009105). It is guaranteed that for all integers i from 2 to n the following condition holds: ri\u2009-\u20091\u2009<\u2009li.", "output_spec": "Output a single number \u2014 the answer to the problem.", "sample_inputs": ["2 3\n5 6\n10 12", "1 1\n1 100000"], "sample_outputs": ["6", "100000"], "notes": "NoteIn the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie."}, "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 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}"}, {"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"} {"nl": {"description": "There are $$$n$$$ traps numbered from $$$1$$$ to $$$n$$$. You will go through them one by one in order. The $$$i$$$-th trap deals $$$a_i$$$ base damage to you.Instead of going through a trap, you can jump it over. You can jump over no more than $$$k$$$ traps. If you jump over a trap, it does not deal any damage to you. But there is an additional rule: if you jump over a trap, all next traps damages increase by $$$1$$$ (this is a bonus damage).Note that if you jump over a trap, you don't get any damage (neither base damage nor bonus damage). Also, the bonus damage stacks so, for example, if you go through a trap $$$i$$$ with base damage $$$a_i$$$, and you have already jumped over $$$3$$$ traps, you get $$$(a_i + 3)$$$ damage.You have to find the minimal damage that it is possible to get if you are allowed to jump over no more than $$$k$$$ traps.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le n$$$)\u00a0\u2014 the number of traps and the number of jump overs that you are allowed to make. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 base damage values of all traps. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output a single integer \u2014 the minimal total damage that it is possible to get if you are allowed to jump over no more than $$$k$$$ traps.", "sample_inputs": ["5\n\n4 4\n\n8 7 1 4\n\n4 1\n\n5 10 11 5\n\n7 5\n\n8 2 5 15 11 2 8\n\n6 3\n\n1 2 3 4 5 6\n\n1 1\n\n7"], "sample_outputs": ["0\n21\n9\n6\n0"], "notes": "NoteIn the first test case it is allowed to jump over all traps and take $$$0$$$ damage.In the second test case there are $$$5$$$ ways to jump over some traps: Do not jump over any trap.Total damage: $$$5 + 10 + 11 + 5 = 31$$$. Jump over the $$$1$$$-st trap.Total damage: $$$\\underline{0} + (10 + 1) + (11 + 1) + (5 + 1) = 29$$$. Jump over the $$$2$$$-nd trap.Total damage: $$$5 + \\underline{0} + (11 + 1) + (5 + 1) = 23$$$. Jump over the $$$3$$$-rd trap.Total damage: $$$5 + 10 + \\underline{0} + (5 + 1) = 21$$$. Jump over the $$$4$$$-th trap.Total damage: $$$5 + 10 + 11 + \\underline{0} = 26$$$.To get minimal damage it is needed to jump over the $$$3$$$-rd trap, so the answer is $$$21$$$.In the third test case it is optimal to jump over the traps $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$7$$$:Total damage: $$$0 + (2 + 1) + 0 + 0 + 0 + (2 + 4) + 0 = 9$$$."}, "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util\n\nobject Main {\n\n def findNotSortedRow(a: Array[Array[Int]]): Option[Int] = {\n a.indices.find { i =>\n (1 until a(i).length).exists { j =>\n a(i)(j - 1) > a(i)(j)\n }\n }\n }\n\n def swapColumns(a: Array[Array[Int]], i: Int, j: Int) = {\n a.foreach { row =>\n val temp = row(i)\n row(i) = row(j)\n row(j) = temp\n }\n }\n\n case class Trap(dmg: Long, id: Int) {\n val evadeProfit = -(dmg + id)\n }\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.nextInt()\n val k = reader.nextInt()\n val a = new Array[Trap](n)\n a.indices.foreach { i =>\n a(i) = Trap(reader.nextLong(), i)\n }\n\n val temp = a.sortBy(_.evadeProfit)\n val evaded = new util.HashSet[Trap]()\n (0 until k).foreach { i =>\n evaded.add(temp(i))\n }\n\n var sumDamage: Long = 0\n var evadedNum = 0\n a.foreach { i =>\n if (evaded.contains(i)) {\n evadedNum += 1\n } else {\n sumDamage += i.dmg + evadedNum\n }\n }\n\n System.out.println(sumDamage)\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(): Long = {\n nextString().toLong\n }\n\n }\n\n}\n"}], "negative_code": [], "src_uid": "66daa3864875e48d32a7acd23bd7a829"} {"nl": {"description": "Shubham has an array $$$a$$$ of size $$$n$$$, and wants to select exactly $$$x$$$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.Tell him whether he can do so.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1\\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \\le x \\le n \\le 1000)$$$\u00a0\u2014 the length of the array and the number of elements you need to choose. The next line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 1000)$$$\u00a0\u2014 elements of the array.", "output_spec": "For each test case, print \"Yes\" or \"No\" depending on whether it is possible to choose $$$x$$$ elements such that their sum is odd. You may print every letter in any case you want.", "sample_inputs": ["5\n1 1\n999\n1 1\n1000\n2 1\n51 50\n2 2\n51 50\n3 3\n101 102 103"], "sample_outputs": ["Yes\nNo\nYes\nYes\nNo"], "notes": "NoteFor $$$1$$$st case: We must select element $$$999$$$, and the sum is odd.For $$$2$$$nd case: We must select element $$$1000$$$, so overall sum is not odd.For $$$3$$$rd case: We can select element $$$51$$$.For $$$4$$$th case: We must select both elements $$$50$$$ and $$$51$$$ \u00a0\u2014 so overall sum is odd.For $$$5$$$th case: We must select all elements \u00a0\u2014 but overall sum is not odd."}, "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"}, {"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}"}], "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"} {"nl": {"description": "You've got a string $$$a_1, a_2, \\dots, a_n$$$, consisting of zeros and ones.Let's call a sequence of consecutive elements $$$a_i, a_{i\u2009+\u20091}, \\ldots,\u2009a_j$$$ ($$$1\\leq\u2009i\\leq\u2009j\\leq\u2009n$$$) a substring of string $$$a$$$. You can apply the following operations any number of times: Choose some substring of string $$$a$$$ (for example, you can choose entire string) and reverse it, paying $$$x$$$ coins for it (for example, \u00ab0101101\u00bb $$$\\to$$$ \u00ab0111001\u00bb); Choose some substring of string $$$a$$$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones\u00a0\u2014 by zeros), paying $$$y$$$ coins for it (for example, \u00ab0101101\u00bb $$$\\to$$$ \u00ab0110001\u00bb). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.What is the minimum number of coins you need to spend to get a string consisting only of ones?", "input_spec": "The first line of input contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1\u2009\\leq\u2009n\u2009\\leq\u2009300\\,000, 0 \\leq x, y \\leq 10^9$$$)\u00a0\u2014 length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring). The second line contains the string $$$a$$$ of length $$$n$$$, consisting of zeros and ones.", "output_spec": "Print a single integer\u00a0\u2014 the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $$$0$$$, if you do not need to perform any operations.", "sample_inputs": ["5 1 10\n01000", "5 10 1\n01000", "7 2 3\n1111111"], "sample_outputs": ["11", "2", "0"], "notes": "NoteIn the first sample, at first you need to reverse substring $$$[1 \\dots 2]$$$, and then you need to invert substring $$$[2 \\dots 5]$$$. Then the string was changed as follows:\u00ab01000\u00bb $$$\\to$$$ \u00ab10000\u00bb $$$\\to$$$ \u00ab11111\u00bb.The total cost of operations is $$$1 + 10 = 11$$$.In the second sample, at first you need to invert substring $$$[1 \\dots 1]$$$, and then you need to invert substring $$$[3 \\dots 5]$$$. Then the string was changed as follows:\u00ab01000\u00bb $$$\\to$$$ \u00ab11000\u00bb $$$\\to$$$ \u00ab11111\u00bb.The overall cost is $$$1 + 1 = 2$$$.In the third example, string already consists only of ones, so the answer is $$$0$$$."}, "positive_code": [{"source_code": "import scala.annotation.tailrec\n\nobject Multiple extends App{\n\n @tailrec\n def countZeroRanges(row: List[Char], prevZero: Boolean = false, count: Int = 0): Int = row match {\n case head :: tail => countZeroRanges(row.tail, row.head == '0',\n if (row.head == '0' && !prevZero) count + 1 else count)\n case Nil => count\n }\n \n val n :: x :: y :: Nil = Console.in.readLine().split(' ').map(_.toLong).toList\n val row = Console.in.readLine().toList\n\n val zeroRanges = countZeroRanges(row)\n if (zeroRanges == 0) {\n println(0)\n }\n else if (x > y) {\n println(zeroRanges * y)\n }\n else {\n println((zeroRanges - 1) * x + y)\n }\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\n\nobject Multiple extends App{\n\n @tailrec\n def countZeroRanges(row: List[Char], prevZero: Boolean = false, count: Int = 0): Int = row match {\n case head :: tail => countZeroRanges(row.tail, row.head == '0',\n if (row.head == '0' && !prevZero) count + 1 else count)\n case Nil => count\n }\n\n val n :: x :: y :: Nil = Console.in.readLine().split(' ').map(_.toLong).toList\n val row = Console.in.readLine().toList\n\n val zeroRanges = countZeroRanges(row)\n if (x > y) {\n println(zeroRanges * y)\n }\n else {\n println((zeroRanges - 1) * x + y)\n }\n\n}\n\n"}], "src_uid": "b267f69cc4af3e319fc59e3ccd8b1c9d"} {"nl": {"description": "You are given an integer array of length $$$n$$$.You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $$$[x, x + 1, \\dots, x + k - 1]$$$ for some value $$$x$$$ and length $$$k$$$.Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array $$$[5, 3, 1, 2, 4]$$$ the following arrays are subsequences: $$$[3]$$$, $$$[5, 3, 1, 2, 4]$$$, $$$[5, 1, 4]$$$, but the array $$$[1, 3]$$$ is not.", "input_spec": "The first line of the input containing integer number $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of the array. The second line of the input containing $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the array itself.", "output_spec": "On the first line print $$$k$$$ \u2014 the maximum length of the subsequence of the given array that forms an increasing sequence of consecutive integers. On the second line print the sequence of the indices of the any maximum length subsequence of the given array that forms an increasing sequence of consecutive integers.", "sample_inputs": ["7\n3 3 4 7 5 6 8", "6\n1 3 5 2 4 6", "4\n10 9 8 7", "9\n6 7 8 3 4 5 9 10 11"], "sample_outputs": ["4\n2 3 5 6", "2\n1 4", "1\n1", "6\n1 2 3 7 8 9"], "notes": "NoteAll valid answers for the first example (as sequences of indices): $$$[1, 3, 5, 6]$$$ $$$[2, 3, 5, 6]$$$ All valid answers for the second example: $$$[1, 4]$$$ $$$[2, 5]$$$ $$$[3, 6]$$$ All valid answers for the third example: $$$[1]$$$ $$$[2]$$$ $$$[3]$$$ $$$[4]$$$ All valid answers for the fourth example: $$$[1, 2, 3, 7, 8, 9]$$$ "}, "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 = ni()\n val A = na(N)\n val cnt = mutable.Map[Int, Int]() withDefaultValue 0\n A foreach { a =>\n cnt(a) = cnt(a - 1) + 1\n }\n val (xmx, k) = cnt.maxBy(_._2)\n\n val ix = ArrayBuffer[Int]()\n val x = xmx - k + 1\n var j = 0\n rep(N){ i =>\n if (j < k && A(i) == x + j) {\n ix += i\n j += 1\n }\n }\n\n out.println(k)\n out.println(ix.map(_ + 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 val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": [], "src_uid": "70986d3b1ff66ac612e8841a6049866d"} {"nl": {"description": "Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types: replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4); swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.", "input_spec": "The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.", "output_spec": "Print on the single line the single number \u2014 the minimum number of operations needed to convert string a into string b.", "sample_inputs": ["47\n74", "774\n744", "777\n444"], "sample_outputs": ["1", "1", "3"], "notes": "NoteIn the first sample it is enough simply to swap the first and the second digit.In the second sample we should replace the second digit with its opposite.In the third number we should replace all three digits with their opposites."}, "positive_code": [{"source_code": "object Solution extends App {\n\n val in = scala.io.Source.stdin.getLines()\n val r = in.next().zip(in.next()).foldLeft((0, 0)) {\n case ((c47, c74), ('4', '7')) => (c47 + 1, c74)\n case ((c47, c74), ('7', '4')) => (c47, c74 + 1)\n case (acc, el) => acc\n }\n\n println(Math.min(r._1, r._2) + Math.abs(r._1 - r._2))\n}\n"}], "negative_code": [], "src_uid": "2d1609b434262d30f6bd030d41a71bd5"} {"nl": {"description": "Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed .You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009400\u2009000)\u00a0\u2014 the number of vertices in the tree. Each of the next n\u2009-\u20091 lines contains a pair of vertex indices ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n)\u00a0\u2014 endpoints of the corresponding edge.", "output_spec": "Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.", "sample_inputs": ["3\n1 2\n2 3", "5\n1 2\n1 3\n1 4\n1 5"], "sample_outputs": ["1 1 1", "1 0 0 0 0"], "notes": "NoteIn the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2,\u20093) with the edge (1,\u20093)."}, "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 @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"}, {"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"} {"nl": {"description": "A team of three programmers is going to play a contest. The contest consists of $$$n$$$ problems, numbered from $$$1$$$ to $$$n$$$. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong \u2014 the statements were printed in the wrong order, so the contestants have received the problems in some random order.The first contestant has received problems $$$a_{1, 1}, a_{1, 2}, \\dots, a_{1, k_1}$$$. The second one has received problems $$$a_{2, 1}, a_{2, 2}, \\dots, a_{2, k_2}$$$. The third one has received all remaining problems ($$$a_{3, 1}, a_{3, 2}, \\dots, a_{3, k_3}$$$).The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems.During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems?It is possible that after redistribution some participant (or even two of them) will not have any problems.", "input_spec": "The first line contains three integers $$$k_1, k_2$$$ and $$$k_3$$$ ($$$1 \\le k_1, k_2, k_3 \\le 2 \\cdot 10^5, k_1 + k_2 + k_3 \\le 2 \\cdot 10^5$$$) \u2014 the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains $$$k_1$$$ integers $$$a_{1, 1}, a_{1, 2}, \\dots, a_{1, k_1}$$$ \u2014 the problems initially taken by the first participant. The third line contains $$$k_2$$$ integers $$$a_{2, 1}, a_{2, 2}, \\dots, a_{2, k_2}$$$ \u2014 the problems initially taken by the second participant. The fourth line contains $$$k_3$$$ integers $$$a_{3, 1}, a_{3, 2}, \\dots, a_{3, k_3}$$$ \u2014 the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer $$$a_{i, j}$$$ meets the condition $$$1 \\le a_{i, j} \\le n$$$, where $$$n = k_1 + k_2 + k_3$$$.", "output_spec": "Print one integer \u2014 the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems.", "sample_inputs": ["2 1 2\n3 1\n4\n2 5", "3 2 1\n3 2 1\n5 4\n6", "2 1 3\n5 6\n4\n1 2 3", "1 5 1\n6\n5 1 2 4 7\n3"], "sample_outputs": ["1", "0", "3", "2"], "notes": "NoteIn the first example the third contestant should give the problem $$$2$$$ to the first contestant, so the first contestant has $$$3$$$ first problems, the third contestant has $$$1$$$ last problem, and the second contestant has $$$1$$$ remaining problem.In the second example the distribution of problems is already valid: the first contestant has $$$3$$$ first problems, the third contestant has $$$1$$$ last problem, and the second contestant has $$$2$$$ remaining problems.The best course of action in the third example is to give all problems to the third contestant.The best course of action in the fourth example is to give all problems to the second contestant."}, "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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val k1, k2, k3 = ni()\n val n = k1 + k2 + k3\n val A1 = na(k1)\n val A2 = na(k2)\n val A3 = na(k3)\n sort(A1)\n sort(A2)\n sort(A3)\n\n // \u5168\u90e8\uff11\u3064\u306e\u5834\u6240\u306b\u79fb\u52d5\u3059\u308b\u30b1\u30fc\u30b9\n val calc1 = n - max(k1, max(k2, k3))\n\n val inf = 1e9.toInt\n\n // 3\u3064\u3068\u3082\u306b\u6570\u5024\u304c\u3042\u308b\u30b1\u30fc\u30b9\u3068\u3001\uff12\u3064\u306b\u3060\u3051\u6570\u5024\u304c\u3042\u308b\u30b1\u30fc\u30b9\n def calc23: Int = {\n var p1, p2, p3 = 0\n var res = 1e9.toInt\n var best, next = Array.fill[Int](3)(inf)\n TO(1, n) { k =>\n if(p1 < k1 && A1(p1) == k) {\n p1 += 1\n next(0) = if (best(0) == inf) 0 else best(0)\n next(1) = if (best(1) == inf) 1 else best(1) + 1\n next(2) = min(inf, min(best(2) + 1, best(0) + 1))\n }\n if(p2 < k2 && A2(p2) == k) {\n p2 += 1\n next(0) = if (best(0) == inf) 1 else best(0) + 1\n next(1) = if (best(1) == inf) 0 else best(1)\n next(2) = min(inf, min(best(2), best(0)))\n }\n if(p3 < k3 && A3(p3) == k) {\n p3 += 1\n Array.copy(best, 0, next, 0, 3)\n }\n debug(next)\n\n var v = next.min\n if (v == inf) v = 0 // \u307e\u3060\u6570\u5024\u304c\uff11\u3053\u3082\u3067\u3066\u304d\u3066\u3044\u306a\u3044\n\n res = min(res, p3 + v + (k1 - p1) + (k2 - p2))\n val t = best\n best = next\n next = t\n }\n res\n }\n val ans = min(calc1, calc23)\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[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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val k1, k2, k3 = ni()\n val n = k1 + k2 + k3\n val A1 = na(k1)\n val A2 = na(k2)\n val A3 = na(k3)\n sort(A1)\n sort(A2)\n sort(A3)\n\n // \u5168\u90e8\uff11\u3064\u306e\u5834\u6240\u306b\u79fb\u52d5\u3059\u308b\u30b1\u30fc\u30b9\n val calc1 = n - max(k1, max(k2, k3))\n\n val inf = 1e9.toInt\n\n // 3\u3064\u3068\u3082\u306b\u6570\u5024\u304c\u3042\u308b\u30b1\u30fc\u30b9\u3068\u3001\uff12\u3064\u306b\u3060\u3051\u6570\u5024\u304c\u3042\u308b\u30b1\u30fc\u30b9\n def calc23: Int = {\n var p1, p2, p3 = 0\n var res = 1e9.toInt\n var best, next = Array.fill[Int](3)(inf)\n TO(1, n) { k =>\n Array.copy(best, 0, next, 0, 3)\n if(p1 < k1 && A1(p1) == k) {\n p1 += 1\n if (best(0) == inf) next(0) = 0\n next(1) = if (best(1) == inf) 1 else best(1) + 1\n next(2) = min(inf, min(best(2) + 1, best(0) + 1))\n }\n if(p2 < k2 && A2(p2) == k) {\n p2 += 1\n next(0) = if (best(0) == inf) 1 else best(0) + 1\n if (best(1) == inf) next(1) = 0\n next(2) = min(inf, min(best(2), best(0)))\n }\n debug(next)\n if(p3 < k3 && A3(p3) == k) p3 += 1\n\n var v = best.min\n if (v == inf) v = 0 // \u307e\u3060\u6570\u5024\u304c\uff11\u3053\u3082\u3067\u3066\u304d\u3066\u3044\u306a\u3044\n\n res = min(res, p3 + v + (k1 - p1) + (k2 - p2))\n val t = best\n best = next\n next = t\n }\n res\n }\n val ans = min(calc1, calc23)\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[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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val k1, k2, k3 = ni()\n val n = k1 + k2 + k3\n val A1 = na(k1)\n val A2 = na(k2)\n val A3 = na(k3)\n sort(A1)\n sort(A2)\n sort(A3)\n\n // \u5168\u90e8\uff11\u3064\u306e\u5834\u6240\u306b\u79fb\u52d5\u3059\u308b\u30b1\u30fc\u30b9\n val calc1 = n - max(k1, max(k2, k3))\n\n val inf = 1e9.toInt\n\n // 3\u3064\u3068\u3082\u306b\u6570\u5024\u304c\u3042\u308b\u30b1\u30fc\u30b9\u3068\u3001\uff12\u3064\u306b\u3060\u3051\u6570\u5024\u304c\u3042\u308b\u30b1\u30fc\u30b9\n def calc23: Int = {\n var p1, p2, p3 = 0\n var res = 1e9.toInt\n var best, next = Array.fill[Int](3)(inf)\n TO(1, n) { k =>\n if(p1 < k1 && A1(p1) == k) {\n p1 += 1\n if (best(0) == inf) next(0) = 0\n next(1) = if (best(1) == inf) 1 else best(1) + 1\n next(2) = min(inf, min(best(2) + 1, best(0) + 1))\n }\n if(p2 < k2 && A2(p2) == k) {\n p2 += 1\n next(0) = if (best(0) == inf) 1 else best(0) + 1\n if (best(1) == inf) next(1) = 0\n next(2) = min(inf, min(best(2), best(0)))\n }\n if(p3 < k3 && A3(p3) == k) {\n p3 += 1\n Array.copy(best, 0, next, 0, 3)\n }\n debug(next)\n\n var v = next.min\n if (v == inf) v = 0 // \u307e\u3060\u6570\u5024\u304c\uff11\u3053\u3082\u3067\u3066\u304d\u3066\u3044\u306a\u3044\n\n res = min(res, p3 + v + (k1 - p1) + (k2 - p2))\n val t = best\n best = next\n next = t\n }\n res\n }\n val ans = min(calc1, calc23)\n out.println(ans)\n }\n}"}], "src_uid": "8351259ef4a4c8fbfd19d31da50aa0f1"} {"nl": {"description": "Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of \u200b\u200bthe region that will be cleared from snow. Help him.", "input_spec": "The first line of the input contains three integers\u00a0\u2014 the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integers\u00a0\u2014 coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1\u2009000\u2009000 in their absolute value.", "output_spec": "Print a single real value number\u00a0\u2014 the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"], "sample_outputs": ["12.566370614359172464", "21.991148575128551812"], "notes": "NoteIn the first sample snow will be removed from that area: "}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a binary matrix $$$a$$$ of size $$$n \\times m$$$. A binary matrix is a matrix where each element is either $$$0$$$ or $$$1$$$.You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in this row to the opposite ($$$0$$$ to $$$1$$$, $$$1$$$ to $$$0$$$). Inverting a column is changing all values in this column to the opposite.Your task is to sort the initial matrix by some sequence of such operations. The matrix is considered sorted if the array $$$[a_{1, 1}, a_{1, 2}, \\dots, a_{1, m}, a_{2, 1}, a_{2, 2}, \\dots, a_{2, m}, \\dots, a_{n, m - 1}, a_{n, m}]$$$ is sorted in non-descending order.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 200$$$) \u2014 the number of rows and the number of columns in the matrix. The next $$$n$$$ lines contain $$$m$$$ integers each. The $$$j$$$-th element in the $$$i$$$-th line is $$$a_{i, j}$$$ ($$$0 \\le a_{i, j} \\le 1$$$) \u2014 the element of $$$a$$$ at position $$$(i, j)$$$.", "output_spec": "If it is impossible to obtain a sorted matrix, print \"NO\" in the first line. Otherwise print \"YES\" in the first line. In the second line print a string $$$r$$$ of length $$$n$$$. The $$$i$$$-th character $$$r_i$$$ of this string should be '1' if the $$$i$$$-th row of the matrix is inverted and '0' otherwise. In the third line print a string $$$c$$$ of length $$$m$$$. The $$$j$$$-th character $$$c_j$$$ of this string should be '1' if the $$$j$$$-th column of the matrix is inverted and '0' otherwise. If there are multiple answers, you can print any.", "sample_inputs": ["2 2\n1 1\n0 1", "3 4\n0 0 0 1\n0 0 0 0\n1 1 1 1", "3 3\n0 0 0\n1 0 1\n1 1 0"], "sample_outputs": ["YES\n00\n10", "YES\n010\n0000", "NO"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.generic\nimport scala.io.BufferedSource\nimport scala.collection.immutable.List\nimport scala.collection.generic.SeqFactory\n\nobject InverseOfRowsAndColumns extends App {\n val listOfLines = new BufferedSource(System.in)\n .getLines()\n .toList\n val List(n,m) : List[Int] = listOfLines.head.split(\" \").toList.map(_.toInt)\n val rowContainingOnes = List.fill (m) (1)\n val rowContainingZeros = List.fill(m) (0)\n val grid: List[List[Int]] = listOfLines\n .drop(1)\n .map(_.split(\" \").toList.map(_.toInt))\n def listToString(l : List[Int]) = {\n l.map(e => e.toString).reduce( (e1,e2) => e1+e2 )\n }\n def inverse(e : Int): Int = {\n if (e == 0) 1 else 0\n }\n def inverseUsingPattern(list: List[Int], pattern: List[Int]): List[Int] = {\n list.zip(pattern).map{case (e,p) => if (p == 1) inverse(e) else e}\n }\n def isSorted(list: List[Int]) = {\n list.dropRight(1).zip(list.tail).forall{case (e1,e2) => e1 <= e2 }\n }\n val inverseList: List[Int] => List[Int] = { list : List[Int] => list.map(inverse)}\n\n def tryPattern(pattern : List[Int]): (Boolean, String) = {\n val (s,_,b) = grid.foldLeft (\"\", 0, true) {\n case ( (s, state, b), l) =>\n val inversed = inverseUsingPattern(l, pattern)\n state match {\n case 0 => {\n if (inversed == rowContainingZeros)\n (s + '0',0,b)\n else\n if (inverseList(inversed) == rowContainingZeros)\n (s + '1',0,b)\n else\n if (isSorted(inversed) )\n (s + '0',1,b)\n else\n if (isSorted(inverseList(inversed)) )\n (s+'1',1,b)\n else\n (\"\",1,false)\n }\n case 1 => {\n if (inversed == rowContainingOnes)\n (s+'0',1,b)\n else\n if (inverseList(inversed) == rowContainingOnes)\n (s+'1',1,b)\n else\n (\"\",1,false)\n }\n }\n }\n (b,s)\n }\n val patterns = List(grid.head, grid.last, inverseList(grid.head), inverseList(grid.last))\n var it = patterns.iterator\n var b = false\n var (rowsResult,colsResult,s) = (\"\",\"\",\"\")\n var pattern = List[Int]()\n do {\n pattern = it.next()\n val (b2,s2) = tryPattern(pattern)\n b = b2\n s = s2\n } while(!b && it.hasNext)\n if (b) {\n rowsResult = s\n colsResult = listToString(pattern)\n print(\n s\"\"\"\n |YES\n |${rowsResult}\n |${colsResult}\n \"\"\".stripMargin)\n } else {\n println(\"NO\")\n }\n\n\n\n}\n"}], "negative_code": [], "src_uid": "b1c5de6d5f1ee1eec5200b1918603931"} {"nl": {"description": "The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1,\u2009a2,\u2009...,\u2009ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k\u2009<\u2009n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) such that ai\u2009>\u20090 and an integer t (t\u2009\u2265\u20090) such that i\u2009+\u20092t\u2009\u2264\u2009n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai\u2009+\u20092t is increased by 1. For example, let n\u2009=\u20094 and a\u2009=\u2009(1,\u20090,\u20091,\u20092), then it is possible to make move i\u2009=\u20093, t\u2009=\u20090 and get a\u2009=\u2009(1,\u20090,\u20090,\u20093) or to make move i\u2009=\u20091, t\u2009=\u20091 and get a\u2009=\u2009(0,\u20090,\u20092,\u20092) (the only possible other move is i\u2009=\u20091, t\u2009=\u20090).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1\u2009\u2264\u2009k\u2009<\u2009n).", "input_spec": "The first input line contains a single integer n. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009104), separated by single spaces. The input limitations for getting 20 points are: 1\u2009\u2264\u2009n\u2009\u2264\u2009300 The input limitations for getting 50 points are: 1\u2009\u2264\u2009n\u2009\u2264\u20092000 The input limitations for getting 100 points are: 1\u2009\u2264\u2009n\u2009\u2264\u2009105 ", "output_spec": "Print exactly n\u2009-\u20091 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams, or the %I64d specifier.", "sample_inputs": ["4\n1 0 1 2", "8\n1 2 3 4 5 6 7 8"], "sample_outputs": ["1\n1\n3", "1\n3\n6\n10\n16\n24\n40"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?", "input_spec": "The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \\le n \\le 10^{5}$$$, $$$1 \\le L \\le 10^{9}$$$, $$$1 \\le a \\le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \\le t_{i} \\le L - 1$$$, $$$1 \\le l_{i} \\le L$$$). It is guaranteed that $$$t_{i} + l_{i} \\le t_{i + 1}$$$ and $$$t_{n} + l_{n} \\le L$$$.", "output_spec": "Output one integer \u00a0\u2014 the maximum number of breaks.", "sample_inputs": ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"], "sample_outputs": ["3", "2", "0"], "notes": "NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks."}, "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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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"} {"nl": {"description": "Shohag has an integer sequence $$$a_1, a_2, \\ldots, a_n$$$. He can perform the following operation any number of times (possibly, zero): Select any positive integer $$$k$$$ (it can be different in different operations). Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $$$k$$$ into the sequence at this position. This way, the sequence $$$a$$$ changes, and the next operation is performed on this changed sequence. For example, if $$$a=[3,3,4]$$$ and he selects $$$k = 2$$$, then after the operation he can obtain one of the sequences $$$[\\underline{2},3,3,4]$$$, $$$[3,\\underline{2},3,4]$$$, $$$[3,3,\\underline{2},4]$$$, or $$$[3,3,4,\\underline{2}]$$$.Shohag wants this sequence to satisfy the following condition: for each $$$1 \\le i \\le |a|$$$, $$$a_i \\le i$$$. Here, $$$|a|$$$ denotes the size of $$$a$$$.Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the initial length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the elements of the sequence.", "output_spec": "For each test case, print a single integer \u00a0\u2014 the minimum number of operations needed to perform to achieve the goal mentioned in the statement.", "sample_inputs": ["4\n3\n1 3 4\n5\n1 2 5 7 4\n1\n1\n3\n69 6969 696969"], "sample_outputs": ["1\n3\n0\n696966"], "notes": "NoteIn the first test case, we have to perform at least one operation, as $$$a_2=3>2$$$. We can perform the operation $$$[1, 3, 4] \\rightarrow [1, \\underline{2}, 3, 4]$$$ (the newly inserted element is underlined), now the condition is satisfied.In the second test case, Shohag can perform the following operations:$$$[1, 2, 5, 7, 4] \\rightarrow [1, 2, \\underline{3}, 5, 7, 4] \\rightarrow [1, 2, 3, \\underline{4}, 5, 7, 4] \\rightarrow [1, 2, 3, 4, 5, \\underline{3}, 7, 4]$$$.In the third test case, the sequence already satisfies the condition."}, "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"}, {"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"}], "negative_code": [], "src_uid": "e79c6a337e9347522bf19f3d5c162541"} {"nl": {"description": "We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \\ne j$$$, $$$i \\in [1, n]$$$ and $$$j \\in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 5 \\cdot 10^5$$$) \u2014 the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$, $$$x_i \\ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree.", "output_spec": "Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i < r_i \\le 2n$$$) \u2014 the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists.", "sample_inputs": ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"], "sample_outputs": ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "This is an easier version of the next problem. In this version, $$$q = 0$$$.A sequence of integers is called nice if its elements are arranged in blocks like in $$$[3, 3, 3, 4, 1, 1]$$$. Formally, if two elements are equal, everything in between must also be equal.Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $$$x$$$ to value $$$y$$$, you must also change all other elements of value $$$x$$$ into $$$y$$$ as well. For example, for $$$[3, 3, 1, 3, 2, 1, 2]$$$ it isn't allowed to change first $$$1$$$ to $$$3$$$ and second $$$1$$$ to $$$2$$$. You need to leave $$$1$$$'s untouched or change them to the same value.You are given a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ and $$$q$$$ updates.Each update is of form \"$$$i$$$ $$$x$$$\"\u00a0\u2014 change $$$a_i$$$ to $$$x$$$. Updates are not independent (the change stays for the future).Print the difficulty of the initial sequence and of the sequence after every update.", "input_spec": "The first line contains integers $$$n$$$ and $$$q$$$ ($$$1 \\le n \\le 200\\,000$$$, $$$q = 0$$$), the length of the sequence and the number of the updates. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 200\\,000$$$), the initial sequence. Each of the following $$$q$$$ lines contains integers $$$i_t$$$ and $$$x_t$$$ ($$$1 \\le i_t \\le n$$$, $$$1 \\le x_t \\le 200\\,000$$$), the position and the new value for this position.", "output_spec": "Print $$$q+1$$$ integers, the answer for the initial sequence and the answer after every update.", "sample_inputs": ["5 0\n3 7 3 7 3", "10 0\n1 2 1 2 3 1 1 1 50 1", "6 0\n6 6 3 3 4 4", "7 0\n3 3 1 3 2 1 2"], "sample_outputs": ["2", "4", "0", "4"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, Q = ni()\n val A = na(N)\n val MAX = if(oj) 2e5.toInt else 50\n val first, last = Array.fill[Int](MAX + 1)(-1)\n val cnt = Array.ofDim[Int](MAX + 1)\n REP(N) { i =>\n if (first(A(i)) == -1) first(A(i)) = i\n last(A(i)) = i\n cnt(A(i)) += 1\n }\n\n debug(cnt)\n\n var ans = 0\n val unbalances = mutable.Set[Int]()\n val cum = ArrayBuffer[Int]()\n REP(N) { i =>\n if (first(A(i)) == i) {\n unbalances += A(i)\n }\n if (last(A(i)) == i) {\n unbalances -= A(i)\n cum += A(i)\n var mx = 0\n var s = 0\n if (unbalances.isEmpty) {\n REP(cum.length) { j =>\n mx = max(mx, cnt(cum(j)))\n s += cnt(cum(j))\n }\n debug(s\"s:$s mx:$mx\")\n ans += s - mx\n cum.clear()\n }\n }\n }\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "2f171f2a3774c5eb3a6d830ac66233d1"} {"nl": {"description": "AquaMoon had $$$n$$$ strings of length $$$m$$$ each. $$$n$$$ is an odd number.When AquaMoon was gone, Cirno tried to pair these $$$n$$$ strings together. After making $$$\\frac{n-1}{2}$$$ pairs, she found out that there was exactly one string without the pair!In her rage, she disrupted each pair of strings. For each pair, she selected some positions (at least $$$1$$$ and at most $$$m$$$) and swapped the letters in the two strings of this pair at the selected positions.For example, if $$$m = 6$$$ and two strings \"abcdef\" and \"xyzklm\" are in one pair and Cirno selected positions $$$2$$$, $$$3$$$ and $$$6$$$ she will swap 'b' with 'y', 'c' with 'z' and 'f' with 'm'. The resulting strings will be \"ayzdem\" and \"xbcklf\".Cirno then stole away the string without pair and shuffled all remaining strings in arbitrary order.AquaMoon found the remaining $$$n-1$$$ strings in complete disarray. Also, she remembers the initial $$$n$$$ strings. She wants to know which string was stolen, but she is not good at programming. Can you help her?", "input_spec": "This problem is made as interactive. It means, that your solution will read the input, given by the interactor. But the interactor will give you the full input at the beginning and after that, you should print the answer. So you should solve the problem, like as you solve the usual, non-interactive problem because you won't have any interaction process. The only thing you should not forget is to flush the output buffer, after printing the answer. Otherwise, you can get an \"Idleness limit exceeded\" verdict. Refer to the interactive problems guide for the detailed information about flushing the output buffer. The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$1 \\leq m \\leq 10^5$$$) \u2014 the number of strings and the length of each string, respectively. The next $$$n$$$ lines each contain a string with length $$$m$$$, describing the original $$$n$$$ strings. All string consists of lowercase Latin letters. The next $$$n-1$$$ lines each contain a string with length $$$m$$$, describing the strings after Cirno exchanged and reordered them. It is guaranteed that $$$n$$$ is odd and that the sum of $$$n \\cdot m$$$ over all test cases does not exceed $$$10^5$$$. Hack format: The first line should contain a single integer $$$t$$$. After that $$$t$$$ test cases should follow in the following format: The first line should contain two integers $$$n$$$ and $$$m$$$. The following $$$n$$$ lines should contain $$$n$$$ strings of length $$$m$$$, describing the original strings. The following $$$\\frac{n-1}{2}$$$ lines should describe the pairs. They should contain, in the following order: the index of the first string $$$i$$$ ($$$1 \\leq i \\leq n$$$), the index of the second string $$$j$$$ ($$$1 \\leq j \\leq n$$$, $$$i \\neq j$$$), the number of exchanged positions $$$k$$$ ($$$1 \\leq k \\leq m$$$), and the list of $$$k$$$ positions that are exchanged ($$$k$$$ distinct indices from $$$1$$$ to $$$m$$$ in any order). The final line should contain a permutation of integers from $$$1$$$ to $$$n$$$, describing the way the strings should be reordered. The strings will be placed in the order indices placed in this permutation, the stolen string index will be ignored.", "output_spec": "For each test case print a single line with the stolen string.", "sample_inputs": ["3\n3 5\naaaaa\nbbbbb\nccccc\naaaaa\nbbbbb\n3 4\naaaa\nbbbb\ncccc\naabb\nbbaa\n5 6\nabcdef\nuuuuuu\nkekeke\nekekek\nxyzklm\nxbcklf\neueueu\nayzdem\nukukuk"], "sample_outputs": ["ccccc\ncccc\nkekeke"], "notes": "NoteIn the first test case, \"aaaaa\" and \"bbbbb\" exchanged all positions, and \"ccccc\" is the stolen string.In the second test case, \"aaaa\" and \"bbbb\" exchanged two first positions, and \"cccc\" is the stolen string.This is the first test in the hack format: 33 5aaaaabbbbbccccc1 2 5 1 2 3 4 52 1 33 4aaaabbbbcccc1 2 2 1 22 1 35 6abcdefuuuuuukekekeekekekxyzklm1 5 3 2 3 62 4 3 2 4 65 4 1 2 3"}, "positive_code": [{"source_code": "object B extends App {\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = nextInts(2)\r\n val originals = Array.fill(n)(nextLine())\r\n val fakes = Array.fill(n - 1)(nextLine())\r\n\r\n val ans = (0 until m)\r\n .foldLeft(List.empty[Char]) { case (ls, i) =>\r\n val c = originals.foldLeft(0) { case (sum, s) => sum + s(i) } -\r\n fakes.foldLeft(0) { case (sum, s) => sum + s(i) }\r\n c.toChar :: ls\r\n }\r\n .reverse\r\n .mkString(\"\")\r\n\r\n out.println(ans)\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n import java.util.Scanner\r\n\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 import scala.io.StdIn._\r\n\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n val t = readInt()\r\n\r\n val ans = (0 until t).map { _ =>\r\n val Array(n, _) = readLine().split(\" \").map(_.toInt)\r\n val os = Array.fill(n)(readLine())\r\n val fs = Array.fill(n - 1)(readLine())\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.mkString(\"\")\r\n }.mkString(\"\\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 val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\r\n val os = Array.fill(n)(readLine())\r\n val fs = Array.fill(n - 1)(readLine())\r\n\r\n val ans = {\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.mkString(\"\")\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}, {"source_code": "object B extends App {\r\n import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = nextInts(2)\r\n val os = Array.fill(n)(nextLine())\r\n val fs = Array.fill(n - 1)(nextLine())\r\n\r\n val ans = {\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.mkString(\"\")\r\n }\r\n\r\n out.println(ans)\r\n }\r\n\r\n out.flush()\r\n\r\n final object InOut {\r\n import java.util.Scanner\r\n\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 import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = nextInts(2)\r\n val os = Array.fill(n)(nextLine())\r\n val fs = Array.fill(n - 1)(nextLine())\r\n\r\n val ans = {\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.mkString(\"\")\r\n }\r\n\r\n out.print(ans)\r\n out.flush()\r\n }\r\n \r\n\r\n final object InOut {\r\n import java.util.Scanner\r\n\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 import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = nextInts(2)\r\n val os = Array.fill(n)(nextLine())\r\n val fs = Array.fill(n - 1)(nextLine())\r\n\r\n val ans = {\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.toString\r\n }\r\n\r\n out.println(ans)\r\n out.flush()\r\n }\r\n \r\n\r\n final object InOut {\r\n import java.util.Scanner\r\n\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 import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = nextInts(2)\r\n val os = Array.fill(n)(nextLine())\r\n val fs = Array.fill(n - 1)(nextLine())\r\n\r\n val ans = {\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.mkString(\"\")\r\n }\r\n\r\n out.println(ans)\r\n }\r\n out.flush()\r\n\r\n final object InOut {\r\n import java.util.Scanner\r\n\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 import InOut._\r\n\r\n val t = nextInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, m) = nextInts(2)\r\n val os = Array.fill(n)(nextLine())\r\n val fs = Array.fill(n - 1)(nextLine())\r\n\r\n val ans = {\r\n def f: Array[String] => Array[Int] = _.map(_.toArray).transpose.map(_.foldLeft(0)(_ + _))\r\n\r\n (f(os) zip f(fs)).map { case (o, f) => (o - f).toChar }.mkString(\"\")\r\n }\r\n\r\n out.println(ans)\r\n out.flush()\r\n }\r\n\r\n final object InOut {\r\n import java.util.Scanner\r\n\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": "b8ffd93a80c840ea645c6797f8ee269c"} {"nl": {"description": "There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior.There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself.Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.", "input_spec": "The first line contains two positive integers n and s (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009s\u2009\u2264\u2009n)\u00a0\u2014 the number of workers and the id of the chief. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u20091), where ai is the number of superiors (not only immediate) the worker with id i reported about.", "output_spec": "Print the minimum number of workers that could make a mistake.", "sample_inputs": ["3 2\n2 0 2", "5 3\n1 0 0 4 1"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example it is possible that only the first worker made a mistake. Then: the immediate superior of the first worker is the second worker, the immediate superior of the third worker is the first worker, the second worker is the chief. "}, "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, s) = readInts(2)\n val as = readInts(n)\n var res = 0\n\n if (as(s - 1) != 0) {\n res += 1\n as(s - 1) = 0\n }\n\n val wrong0Count = as.count(_ == 0) - 1\n\n res += wrong0Count\n\n val bs = as.filter(_ > 0).sorted ++ Array.fill(wrong0Count){ 0 }\n\n var left = 0\n var right = bs.length\n var maxParent = 0\n//println(bs.mkString(\" \"))\n while (left < right && bs(left) > 0) {\n if (bs(left) == maxParent + 1) {\n maxParent += 1\n left += 1\n } else if (bs(left) > maxParent + 1) {\n if (right > left) {\n right -= 1\n if (bs(right) > 0) res += 1\n } else res += 1\n maxParent += 1\n //left += 1\n } else left += 1\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "3def8503f4e7841d33be5b4890065526"} {"nl": {"description": "Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai\u2009+\u20091 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?", "input_spec": "The first line contains two space-separated integers n and v (1\u2009\u2264\u2009n,\u2009v\u2009\u2264\u20093000) \u2014 the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20093000) \u2014 the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.", "output_spec": "Print a single integer \u2014 the maximum number of fruit that Valera can collect. ", "sample_inputs": ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"], "sample_outputs": ["8", "60"], "notes": "NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither."}, "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//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}"}, {"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 * 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/**\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//\u7b2c\u4e00\u5929\u53ea\u80fd\u91c7\u7b2c\u4e00\u5929\u7684\u6c34\u679c,yetCollect\u4fdd\u5b58\u7684\u4e3a\u524d\u4e00\u5929\u6240\u6458\u7684\u6570\u91cf\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) 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"}, {"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(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}"}], "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"} {"nl": {"description": "The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called \"Testing Pants for Sadness\".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), the number of answer variants to question i.", "output_spec": "Print a single number \u2014 the minimal number of clicks needed to pass the test it the worst-case scenario. Please do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specificator.", "sample_inputs": ["2\n1 1", "2\n2 2", "1\n10"], "sample_outputs": ["2", "5", "10"], "notes": "NoteNote to the second sample. In the worst-case scenario you will need five clicks: the first click selects the first variant to the first question, this answer turns out to be wrong. the second click selects the second variant to the first question, it proves correct and we move on to the second question; the third click selects the first variant to the second question, it is wrong and we go back to question 1; the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; the fifth click selects the second variant to the second question, it proves correct, the test is finished. "}, "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).zipWithIndex.foldLeft(0l) {\n case (result, (i, index)) => result + index * (i - 1) + i}\n println(data)\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).zipWithIndex.foldLeft(0l) {\n case (result, (i, index)) => result + index * (i - 1) + i}\n println(data)\n}"}], "src_uid": "c8531b2ab93993b2c3467595ad0679c5"} {"nl": {"description": "$$$n$$$ students attended the first meeting of the Berland SU programming course ($$$n$$$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains one integer $$$n$$$ ($$$2 \\le n \\le 1\\,000$$$)\u00a0\u2014 the number of students. The $$$i$$$-th of the next $$$n$$$ lines contains $$$5$$$ integers, each of them is $$$0$$$ or $$$1$$$. If the $$$j$$$-th integer is $$$1$$$, then the $$$i$$$-th student can attend the lessons on the $$$j$$$-th day of the week. If the $$$j$$$-th integer is $$$0$$$, then the $$$i$$$-th student cannot attend the lessons on the $$$j$$$-th day of the week. Additional constraints on the input: for each student, at least one of the days of the week is convenient, the total number of students over all testcases doesn't exceed $$$10^5$$$.", "output_spec": "For each testcase print an answer. If it's possible to divide the students into two groups of equal sizes and choose different days for the groups so each student can attend the lesson in the chosen day of their group, print \"YES\" (without quotes). Otherwise, print \"NO\" (without quotes). ", "sample_inputs": ["2\n4\n1 0 0 1 0\n0 1 0 0 1\n0 0 0 1 0\n0 1 0 1 0\n2\n0 0 0 1 0\n0 0 0 1 0"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first testcase, there is a way to meet all the constraints. For example, the first group can consist of the first and the third students, they will attend the lessons on Thursday (the fourth day); the second group can consist of the second and the fourth students, and they will attend the lessons on Tuesday (the second day).In the second testcase, it is impossible to divide the students into groups so they attend the lessons on different days."}, "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 val rem = 1000000007\n var days = new Array[ArrayBuffer[Int]](5)\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n for (i <- 0 to 4)\n days(i) = new ArrayBuffer[Int]()\n for (i <- 1 to n) {\n for (j <- 0 to 4) {\n if (readInt() == 1)\n days(j).append(i)\n }\n }\n var found = false\n for (i <- 0 to 4){\n for (j <- i+1 to 4) {\n if (!found && days(i).length >= n/2 && days(j).length >= n/2) {\n val mark = new Array[Boolean](n + 1)\n var cnt = 0\n for (k <- days(i)) {\n mark(k) = true\n }\n for (k <- days(j)) {\n if (mark(k))\n cnt += 1\n }\n val sz1 = days(i).length - cnt\n val sz2 = days(j).length - cnt\n cnt -= max(0, n/2-sz1)\n cnt -= max(0, n/2-sz2)\n if (cnt >= 0)\n found = true\n }\n }\n }\n if (found)\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n\n }\n writer.flush()\n}\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 val rem = 1000000007\n var days = new Array[ArrayBuffer[Int]](5)\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n for (i <- 0 to 4)\n days(i) = new ArrayBuffer[Int]()\n for (i <- 1 to n) {\n for (j <- 0 to 4) {\n if (readInt() == 1)\n days(j).append(i)\n }\n }\n var found = false\n for (i <- 0 to 4){\n for (j <- i+1 to 4) {\n if (!found && days(i).length >= n/2 && days(j).length >= n/2) {\n var mark = new Array[Boolean](n + 1)\n var cnt = 0\n for (k <- days(i))\n mark(k) = true\n for (k <- days(j)) {\n if (mark(k))\n cnt += 1\n }\n val sz1 = days(i).length - cnt\n val sz2 = days(j).length - cnt\n cnt -= min(0, n/2-sz1)\n cnt -= min(0, n/2-sz2)\n if (cnt >= 0)\n found = true\n }\n }\n }\n if (found)\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n\n }\n writer.flush()\n}\n"}], "src_uid": "068cbfb901aadcd15f794dbbf3dfd453"} {"nl": {"description": "You are given a number $$$k$$$ and a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: The first character '*' in the original string should be replaced with 'x'; The last character '*' in the original string should be replaced with 'x'; The distance between two neighboring replaced characters 'x' must not exceed $$$k$$$ (more formally, if you replaced characters at positions $$$i$$$ and $$$j$$$ ($$$i < j$$$) and at positions $$$[i+1, j-1]$$$ there is no \"x\" symbol, then $$$j-i$$$ must be no more than $$$k$$$). For example, if $$$n=7$$$, $$$s=$$$.**.*** and $$$k=3$$$, then the following strings will satisfy the conditions above: .xx.*xx; .x*.x*x; .xx.xxx. But, for example, the following strings will not meet the conditions: .**.*xx (the first character '*' should be replaced with 'x'); .x*.xx* (the last character '*' should be replaced with 'x'); .x*.*xx (the distance between characters at positions $$$2$$$ and $$$6$$$ is greater than $$$k=3$$$). Given $$$n$$$, $$$k$$$, and $$$s$$$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 50$$$). The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. It is guaranteed that there is at least one '*' in the string $$$s$$$. It is guaranteed that the distance between any two neighboring '*' characters does not exceed $$$k$$$.", "output_spec": "For each test case output the minimum number of '*' characters that must be replaced with 'x' characters in order to satisfy the conditions above.", "sample_inputs": ["5\n7 3\n.**.***\n5 1\n..*..\n5 2\n*.*.*\n3 2\n*.*\n1 1\n*"], "sample_outputs": ["3\n1\n3\n2\n1"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject B {\r\n\r\n def solution(args: Seq[String]): Seq[Int] = {\r\n def solve(n: Int, k: Int, str: List[Char]): Int = {\r\n\r\n def loop(ik: Int, prevK: Int, str0: List[Char], in: Boolean, result: Int): Int = {\r\n str0 match {\r\n case h :: hs =>\r\n\r\n if (!in) {\r\n h match {\r\n case '*' =>\r\n loop(1, 1, hs, !in, 1)\r\n case '.' =>\r\n loop(0, 0, hs, in, 0)\r\n }\r\n } else {\r\n h match {\r\n case '*' =>\r\n if (ik == k) loop(1, 1, hs, in, result + 1)\r\n else loop(ik + 1, 1, hs, in, result)\r\n\r\n case '.' =>\r\n if (ik < k) loop(ik + 1, prevK + 1, hs, in, result)\r\n else if (ik == k && prevK == k) result\r\n else if (ik == k) loop(prevK + 1, prevK + 1, hs, in, result + 1)\r\n else result - 1\r\n }\r\n }\r\n\r\n case Nil =>\r\n if(ik != prevK) result + 1\r\n else result\r\n }\r\n }\r\n\r\n loop(0, 0, str, false, 0)\r\n }\r\n\r\n for(i <- 0 until args.length by 2) yield {\r\n val nk = args(i).split(\" \").map(_.toInt)\r\n val (n, k) = (nk(0), nk(1))\r\n solve(n, k, args(i + 1).toCharArray.toList)\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n def readInput(result: List[String]): List[String] = {\r\n if (result.length < t * 2) readInput(result ::: List(StdIn.readLine))\r\n else result\r\n }\r\n\r\n val input = readInput(List.empty)\r\n solution(input).foreach(println)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject B {\r\n\r\n def solution(args: Seq[String]): Seq[Int] = {\r\n def solve(n: Int, k: Int, str: List[Char]): Int = {\r\n\r\n def loop(ik: Int, prevK: Int, str0: List[Char], in: Boolean, result: Int): Int = {\r\n str0 match {\r\n case h :: hs =>\r\n\r\n if (!in) {\r\n h match {\r\n case '*' =>\r\n loop(1, 1, hs, !in, 1)\r\n case '.' =>\r\n loop(0, 0, hs, in, 0)\r\n }\r\n } else {\r\n h match {\r\n case '*' =>\r\n if (ik == k) loop(1, 1, hs, in, result + 1)\r\n else loop(ik + 1, 1, hs, in, result)\r\n\r\n case '.' =>\r\n if (ik < k) loop(ik + 1, prevK + 1, hs, in, result)\r\n else if (ik == k) loop(prevK + 1, prevK + 1, hs, in, result + 1)\r\n else result - 1\r\n }\r\n }\r\n\r\n case Nil =>\r\n if(ik != prevK) result + 1\r\n else result\r\n }\r\n }\r\n\r\n loop(0, 0, str, false, 0)\r\n }\r\n\r\n for(i <- 0 until args.length by 2) yield {\r\n val nk = args(i).split(\" \").map(_.toInt)\r\n val (n, k) = (nk(0), nk(1))\r\n solve(n, k, args(i + 1).toCharArray.toList)\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n def readInput(result: List[String]): List[String] = {\r\n if (result.length < t * 2) readInput(result ::: List(StdIn.readLine))\r\n else result\r\n }\r\n\r\n val input = readInput(List.empty)\r\n solution(input).foreach(println)\r\n }\r\n}\r\n"}, {"source_code": "import scala.io.StdIn\r\n\r\nobject B {\r\n\r\n def solution(args: Seq[String]): Seq[Int] = {\r\n def solve(n: Int, k: Int, str: List[Char]): Int = {\r\n\r\n def loop(ik: Int, prevK: Int, str0: List[Char], in: Boolean, result: Int): Int = {\r\n str0 match {\r\n case h :: hs =>\r\n\r\n if (!in) {\r\n h match {\r\n case '*' =>\r\n loop(1, 1, hs, !in, 1)\r\n case '.' =>\r\n loop(0, 0, hs, in, 0)\r\n }\r\n } else {\r\n h match {\r\n case '*' =>\r\n if (ik == k) loop(1, 1, hs, in, result + 1)\r\n else loop(ik + 1, 1, hs, in, result)\r\n\r\n case '.' =>\r\n if (ik < k) loop(ik + 1, prevK + 1, hs, in, result)\r\n else if (ik == k) loop(prevK + 1, prevK + 1, hs, in, result + 1)\r\n else result - 1\r\n }\r\n }\r\n\r\n case Nil =>\r\n if(ik != prevK && ik == k) result + 1\r\n else result\r\n }\r\n }\r\n\r\n loop(0, 0, str, false, 0)\r\n }\r\n\r\n for(i <- 0 until args.length by 2) yield {\r\n val nk = args(i).split(\" \").map(_.toInt)\r\n val (n, k) = (nk(0), nk(1))\r\n solve(n, k, args(i + 1).toCharArray.toList)\r\n }\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val t = StdIn.readInt()\r\n def readInput(result: List[String]): List[String] = {\r\n if (result.length < t * 2) readInput(result ::: List(StdIn.readLine))\r\n else result\r\n }\r\n\r\n val input = readInput(List.empty)\r\n solution(input).foreach(println)\r\n }\r\n}\r\n"}], "src_uid": "874e22d4fd8e35f7e0eade2b469ee5dc"} {"nl": {"description": "This problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 1000$$$)\u00a0\u2014 the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \\le x_i, y_i \\le 10^4$$$)\u00a0\u2014 the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.", "output_spec": "Print a single integer\u00a0\u2014 the number of pairs of wires that are intersecting.", "sample_inputs": ["4\n0 0\n1 1\n0 3\n1 2", "4\n0 0\n0 2\n0 4\n2 0", "3\n-1 -1\n1 0\n3 1"], "sample_outputs": ["14", "6", "0"], "notes": "NoteIn the first example: In the second example: Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example: "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n case class Coord(x: Int, y: Int)\n case class Line(a: Int, b: Int, c: Int) {\n def slope: Slope = Slope(a, b)\n }\n case class Slope(a: Int, b: Int)\n\n def toLine(c1: Coord, c2: Coord): Line = {\n var a = c2.y - c1.y\n var b = c1.x - c2.x\n\n if (a < 0) {\n a *= -1\n b *= -1\n }\n\n if (a != 0 && b != 0) {\n val g = gcd(a, b)\n a /= g\n b /= g\n }\n\n if (a == 0) b = 1\n else if (b == 0) a = 1\n\n val c = -(c1.x * a + c1.y * b)\n Line(a, b, c)\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(): Unit = {\n val N = ni()\n val P = Array.ofDim[Coord](N)\n REP(N) { i =>\n val x, y = ni()\n P(i) = Coord(x, y)\n }\n\n val lines = mutable.Set[Line]()\n\n REP(N - 1) { i =>\n TO(i + 1, N - 1) { j =>\n lines += toLine(P(i), P(j))\n }\n }\n\n val slope = mutable.Map[Slope, Int]().withDefaultValue(0)\n lines.foreach { l =>\n val s = l.slope\n slope(s) = slope(s) + 1\n }\n\n val lineNum = lines.size\n var ans = 0L\n slope.foreach { case (_, num) =>\n ans += num.toLong * (lineNum - num)\n }\n out.println(ans / 2)\n }\n}"}], "negative_code": [], "src_uid": "d7d8d91be04f5d9065a0c22e66d11de3"} {"nl": {"description": "Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009m\u2009\u2264\u2009109)\u00a0\u2014 the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the numbers on Eugeny's cards.", "output_spec": "If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integers\u00a0\u2014 Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.", "sample_inputs": ["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"], "sample_outputs": ["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"], "notes": null}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.util.Try\n\nimport scala.collection.JavaConverters._\n\nobject E 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 if (n % 2 != 0) println(-1) else Try {\n\n read()\n val arr = Array.fill(n)(int())\n val set = arr.toSet\n var emobase = set.count(_ % 2 == 0) * 2 - set.size\n val mset = new java.util.HashSet[Int]\n var changed = 0\n\n val forced = Math.max(0, emobase.abs - (n - set.size)) / 2\n val unchanged = if (forced == 0) Array.empty[Int] else\n if (emobase > 0) set.filter(_%2==0).toArray\n else set.filter(_%2!=0).toArray\n java.util.Arrays.sort(unchanged)\n val forcedSet = new java.util.HashSet[Int]\n unchanged.take(forced).foreach(forcedSet.add)\n\n val (even, odd) = Iterator\n .from(1, 1)\n .take(m)\n .filterNot(set.contains)\n .partition(_ % 2 == 0)\n\n var v = 0\n (0 until n).foreach { i =>\n v = arr(i)\n if (mset.contains(v) || forcedSet.contains(v)) {\n if (emobase > 0) {\n arr(i) = odd.next\n emobase -= 1\n changed += 1\n } else {\n arr(i) = even.next\n emobase += 1\n changed += 1\n }\n } else {\n mset.add(v)\n }\n }\n println(changed)\n println(arr.mkString(\" \"))\n }.getOrElse(println(-1))\n}\n\n/*\nif (forced == 0) {\n} else {\n if (emobase > 0 && (v%2==0)) {\n arr(i) = odd.next()\n emobase -= 1\n forced -= 1\n changed += 1\n } else if (emobase < 0 && (v%2!=0)) {\n arr(i) = even.next()\n emobase += 1\n forced -= 1\n changed += 1\n }\n}*/"}], "negative_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.util.Try\n\nobject E 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 if (n % 2 != 0) println(-1) else Try {\n\n read()\n val arr = Array.fill(n)(int())\n val set = arr.toSet\n var emobase = set.count(_ % 2 == 0) * 2 - set.size\n var forced = Math.max(0, emobase.abs - (n - set.size)) / 2\n val mset = new java.util.HashSet[Int]\n var changed = 0\n\n val (even, odd) = Iterator\n .from(1, 1)\n .take(m)\n .filterNot(set.contains)\n .partition(_ % 2 == 0)\n\n var v = 0\n (0 until n).foreach { i =>\n v = arr(i)\n if (mset.contains(v)) {\n if (emobase > 0) {\n arr(i) = odd.next\n emobase -= 1\n changed += 1\n } else {\n arr(i) = even.next\n emobase += 1\n changed += 1\n }\n } else {\n if (forced == 0) {\n mset.add(v)\n } else {\n if (emobase > 0 && (v%2==0)) {\n arr(i) = odd.next()\n emobase -= 1\n forced -= 1\n changed += 1\n } else if (emobase < 0 && (v%2!=0)) {\n arr(i) = even.next()\n emobase += 1\n forced -= 1\n changed += 1\n }\n }\n }\n }\n println(changed)\n println(arr.mkString(\" \"))\n }.getOrElse(println(-1))\n}\n"}, {"source_code": "import java.util.StringTokenizer\n\nimport scala.util.Try\n\nobject E 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 if (n % 2 != 0) println(-1) else Try {\n\n read()\n val arr = Array.fill(n)(int())\n val set = arr.toSet\n var emobase = set.map { i => if (i % 2 == 0) 1 else -1 }.sum\n var forced = Math.max(0, emobase.abs - (n - set.size)) / 2\n val mset = new java.util.HashSet[Int]\n var changed = 0\n\n val (even, odd) = Iterator\n .from(1, 1)\n .take(m)\n .filterNot(set.contains)\n .partition(_ % 2 == 0)\n\n var v = 0\n (0 until n).foreach { i =>\n v = arr(i)\n if (mset.contains(v)) {\n if (emobase > 0) {\n arr(i) = odd.next\n emobase -= 1\n changed += 1\n } else {\n arr(i) = even.next\n emobase += 1\n changed += 1\n }\n } else {\n if (forced == 0) {\n mset.add(v)\n } else {\n if (emobase > 0 && (v%2==0)) {\n arr(i) = odd.next()\n emobase -= 1\n forced -= 1\n changed += 1\n } else if (emobase < 0 && (v%2!=0)) {\n arr(i) = even.next()\n emobase += 1\n forced -= 1\n changed += 1\n }\n }\n }\n }\n println(changed)\n println(arr.mkString(\" \"))\n }.getOrElse(println(-1))\n}\n"}], "src_uid": "86bf9688b92ced5238009eefd051387d"} {"nl": {"description": "You are given a huge integer $$$a$$$ consisting of $$$n$$$ digits ($$$n$$$ is between $$$1$$$ and $$$3 \\cdot 10^5$$$, inclusive). It may contain leading zeros.You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $$$2$$$). For example, if $$$a = 032867235$$$ you can get the following integers in a single operation: $$$302867235$$$ if you swap the first and the second digits; $$$023867235$$$ if you swap the second and the third digits; $$$032876235$$$ if you swap the fifth and the sixth digits; $$$032862735$$$ if you swap the sixth and the seventh digits; $$$032867325$$$ if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions $$$2$$$ and $$$4$$$ because the positions are not adjacent. Also, you can't swap digits on positions $$$3$$$ and $$$4$$$ because the digits have the same parity.You can perform any number (possibly, zero) of such operations.Find the minimum integer you can obtain.Note that the resulting integer also may contain leading zeros.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. The only line of each test case contains the integer $$$a$$$, its length $$$n$$$ is between $$$1$$$ and $$$3 \\cdot 10^5$$$, inclusive. It is guaranteed that the sum of all values $$$n$$$ does not exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case print line \u2014 the minimum integer you can obtain.", "sample_inputs": ["3\n0709\n1337\n246432"], "sample_outputs": ["0079\n1337\n234642"], "notes": "NoteIn the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): $$$0 \\underline{\\textbf{70}} 9 \\rightarrow 0079$$$.In the second test case, the initial integer is optimal. In the third test case you can perform the following sequence of operations: $$$246 \\underline{\\textbf{43}} 2 \\rightarrow 24 \\underline{\\textbf{63}}42 \\rightarrow 2 \\underline{\\textbf{43}} 642 \\rightarrow 234642$$$."}, "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 class Queue(n: Int) {\n private val as = Array.ofDim[Int](n)\n var p = 0\n var cur = 0\n\n def +=(a: Int): Unit = {\n as(p) = a\n p += 1\n }\n\n def dequeue(): Int = {\n val a = as(cur)\n cur += 1\n a\n }\n\n def head: Int = as(cur)\n\n def apply(i: Int): Int = as(cur + i)\n\n def length: Int = p - cur\n def isEmpty: Boolean = length == 0\n def nonEmpty: Boolean = !isEmpty\n\n def mkString(delimiter: String = \"\"): String = as.slice(cur, cur + length).mkString(delimiter)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val s = ns()\n val odds, evens = new Queue(s.length)\n REP(s.length) { i =>\n val a = s(i)-'0'\n if (a % 2 == 0) evens += a\n else odds += a\n }\n\n while(odds.nonEmpty || evens.nonEmpty) {\n val v = if (odds.isEmpty) evens.dequeue()\n else if (evens.isEmpty) odds.dequeue()\n else {\n if (odds.head < evens.head) odds.dequeue()\n else evens.dequeue()\n }\n out.print(v)\n }\n out.println()\n }\n }\n}"}], "negative_code": [], "src_uid": "55956c5389c34e4012069de92b3185dc"} {"nl": {"description": "By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form \"activate/deactivate the i-th collider\". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of \"+ i\" (that is, to activate the i-th collider), the program should print exactly one of the following responses: \"Success\" if the activation was successful. \"Already on\", if the i-th collider was already activated before the request. \"Conflict with j\", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of \"- i\" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: \"Success\", if the deactivation was successful. \"Already off\", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either \"+ i\" (without the quotes) \u2014 activate the i-th collider, or \"-\u00a0i\" (without the quotes) \u2014 deactivate the i-th collider (1\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "Print m lines \u2014 the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.", "sample_inputs": ["10 10\n+ 6\n+ 10\n+ 5\n- 10\n- 5\n- 6\n+ 10\n+ 3\n+ 6\n+ 3"], "sample_outputs": ["Success\nConflict with 6\nSuccess\nAlready off\nSuccess\nSuccess\nSuccess\nSuccess\nConflict with 10\nAlready on"], "notes": "NoteNote that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response \"Conflict with 3\"."}, "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 = 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"}, {"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"} {"nl": {"description": "There are $$$n$$$ programmers that you want to split into several non-empty teams. The skill of the $$$i$$$-th programmer is $$$a_i$$$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $$$x$$$.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.", "input_spec": "The first line contains the integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5; 1 \\le x \\le 10^9$$$)\u00a0\u2014 the number of programmers and the restriction of team skill respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th programmer. The sum of $$$n$$$ over all inputs does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer \u2014 the maximum number of teams that you can assemble. ", "sample_inputs": ["3\n5 10\n7 11 2 9 5\n4 8\n2 4 2 3\n4 11\n1 3 3 7"], "sample_outputs": ["2\n1\n0"], "notes": null}, "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, 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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "8a6953a226abef41a44963c9b4998a25"} {"nl": {"description": "Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $$$k$$$ is vowelly if there are positive integers $$$n$$$ and $$$m$$$ such that $$$n\\cdot m = k$$$ and when the word is written by using $$$n$$$ rows and $$$m$$$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.You are given an integer $$$k$$$ and you must either print a vowelly word of length $$$k$$$ or print $$$-1$$$ if no such word exists.In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.", "input_spec": "Input consists of a single line containing the integer $$$k$$$ ($$$1\\leq k \\leq 10^4$$$)\u00a0\u2014 the required length.", "output_spec": "The output must consist of a single line, consisting of a vowelly word of length $$$k$$$ consisting of lowercase English letters if it exists or $$$-1$$$ if it does not. If there are multiple possible words, you may output any of them.", "sample_inputs": ["7", "36"], "sample_outputs": ["-1", "agoeuioaeiruuimaeoieauoweouoiaouimae"], "notes": "NoteIn the second example, the word \"agoeuioaeiruuimaeoieauoweouoiaouimae\" can be arranged into the following $$$6 \\times 6$$$ grid: It is easy to verify that every row and every column contain all the vowels."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai\u2009-\u2009aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of soldiers. Then follow the heights of the soldiers in their order in the circle \u2014 n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000). The soldier heights are given in clockwise or counterclockwise direction.", "output_spec": "Output two integers \u2014 indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.", "sample_inputs": ["5\n10 12 13 15 10", "4\n10 20 30 40"], "sample_outputs": ["5 1", "1 2"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$.You are also given a set of distinct positions $$$p_1, p_2, \\dots, p_m$$$, where $$$1 \\le p_i < n$$$. The position $$$p_i$$$ means that you can swap elements $$$a[p_i]$$$ and $$$a[p_i + 1]$$$. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order ($$$a_1 \\le a_2 \\le \\dots \\le a_n$$$) using only allowed swaps.For example, if $$$a = [3, 2, 1]$$$ and $$$p = [1, 2]$$$, then we can first swap elements $$$a[2]$$$ and $$$a[3]$$$ (because position $$$2$$$ is contained in the given set $$$p$$$). We get the array $$$a = [3, 1, 2]$$$. Then we swap $$$a[1]$$$ and $$$a[2]$$$ (position $$$1$$$ is also contained in $$$p$$$). We get the array $$$a = [1, 3, 2]$$$. Finally, we swap $$$a[2]$$$ and $$$a[3]$$$ again and get the array $$$a = [1, 2, 3]$$$, sorted in non-decreasing order.You can see that if $$$a = [4, 1, 2, 3]$$$ and $$$p = [3, 2]$$$ then you cannot sort the array.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le m < n \\le 100$$$) \u2014 the number of elements in $$$a$$$ and the number of elements in $$$p$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$). The third line of the test case contains $$$m$$$ integers $$$p_1, p_2, \\dots, p_m$$$ ($$$1 \\le p_i < n$$$, all $$$p_i$$$ are distinct) \u2014 the set of positions described in the problem statement.", "output_spec": "For each test case, print the answer \u2014 \"YES\" (without quotes) if you can sort the initial array in non-decreasing order ($$$a_1 \\le a_2 \\le \\dots \\le a_n$$$) using only allowed swaps. Otherwise, print \"NO\".", "sample_inputs": ["6\n3 2\n3 2 1\n1 2\n4 2\n4 1 2 3\n3 2\n5 1\n1 2 3 4 5\n1\n4 2\n2 1 4 3\n1 3\n4 2\n4 3 2 1\n1 3\n5 2\n2 1 2 3 3\n1 4"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO\nYES"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "There are n integers b1,\u2009b2,\u2009...,\u2009bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: The crow sets ai initially 0. The crow then adds bi to ai, subtracts bi\u2009+\u20091, adds the bi\u2009+\u20092 number, and so on until the n'th number. Thus, ai\u2009=\u2009bi\u2009-\u2009bi\u2009+\u20091\u2009+\u2009bi\u2009+\u20092\u2009-\u2009bi\u2009+\u20093.... Memory gives you the values a1,\u2009a2,\u2009...,\u2009an, and he now wants you to find the initial numbers b1,\u2009b2,\u2009...,\u2009bn written in the row? Can you do it?", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of integers written in the row. The next line contains n, the i'th of which is ai (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the value of the i'th number.", "output_spec": "Print n integers corresponding to the sequence b1,\u2009b2,\u2009...,\u2009bn. It's guaranteed that the answer is unique and fits in 32-bit integer type.", "sample_inputs": ["5\n6 -4 8 -2 3", "5\n3 -2 -1 5 6"], "sample_outputs": ["2 4 6 1 3", "1 -3 4 11 6"], "notes": "NoteIn the first sample test, the crows report the numbers 6,\u2009-\u20094, 8,\u2009-\u20092, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6\u2009=\u20092\u2009-\u20094\u2009+\u20096\u2009-\u20091\u2009+\u20093, and \u2009-\u20094\u2009=\u20094\u2009-\u20096\u2009+\u20091\u2009-\u20093.In the second sample test, the sequence 1, \u2009-\u20093, 4, 11, 6 satisfies the reports. For example, 5\u2009=\u200911\u2009-\u20096 and 6\u2009=\u20096."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.", "input_spec": "The first input line contains 3 space-separated integer numbers n, m, v (3\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009v\u2009\u2264\u2009n), n \u2014 amount of servers, m \u2014 amount of direct connections, v \u2014 index of the server that fails and leads to the failure of the whole system.", "output_spec": "If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each \u2014 description of all the direct connections in the system. Each direct connection is described by two numbers \u2014 indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.", "sample_inputs": ["5 6 3", "6 100 1"], "sample_outputs": ["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "959709bfe7b26a4b9f2e7430350650a9"} {"nl": {"description": "You are given a decimal representation of an integer $$$x$$$ without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in $$$x$$$ and replace them with their sum without leading zeros (if the sum is $$$0$$$, it's represented as a single $$$0$$$).For example, if $$$x = 10057$$$, the possible reductions are: choose the first and the second digits $$$1$$$ and $$$0$$$, replace them with $$$1+0=1$$$; the result is $$$1057$$$; choose the second and the third digits $$$0$$$ and $$$0$$$, replace them with $$$0+0=0$$$; the result is also $$$1057$$$; choose the third and the fourth digits $$$0$$$ and $$$5$$$, replace them with $$$0+5=5$$$; the result is still $$$1057$$$; choose the fourth and the fifth digits $$$5$$$ and $$$7$$$, replace them with $$$5+7=12$$$; the result is $$$10012$$$. What's the largest number that can be obtained?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. Each testcase consists of a single integer $$$x$$$ ($$$10 \\le x < 10^{200000}$$$). $$$x$$$ doesn't contain leading zeros. The total length of the decimal representations of $$$x$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the largest number that can be obtained after the reduction is applied exactly once. The number should not contain leading zeros.", "sample_inputs": ["2\n10057\n90"], "sample_outputs": ["10012\n9"], "notes": "NoteThe first testcase of the example is already explained in the statement.In the second testcase, there is only one possible reduction: the first and the second digits."}, "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, 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 z = '0'.toInt\n val s = readString()\n var c = 0\n var v = 0\n for (i <- 0 to s.length-2) {\n if (s(i).toInt - z + s(i+1).toInt - z >= 10) {\n c = i\n }\n }\n for (i <- 0 until s.length) {\n if (i != c && i != c+1) {\n writer.print(s(i))\n }\n if (i == c) {\n v = s(c).toInt - z + s(c+1).toInt - z\n if (v >= 10) {\n writer.print('1')\n }\n v %= 10\n writer.print((v + z).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}"}], "negative_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, 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 z = '0'.toInt\n val s = readString()\n var c = s.length - 2\n var v = 0\n for (i <- s.indices) {\n if (i != s.length - 1) {\n if (s(i).toInt - z + s(i+1).toInt - z >= 10) {\n c = i\n }\n }\n }\n for (i <- s.indices) {\n if (i != c && i != c+1) {\n writer.print(s(i))\n }\n if (i == c) {\n v = s(i).toInt - z + s(i+1).toInt - z\n if (v >= 10) {\n writer.print((v/10 + z).toChar)\n }\n writer.print((v%10 + z).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}"}], "src_uid": "6db42771fdd582578194c7b69a4ef575"} {"nl": {"description": "The King of Berland Polycarp LXXXIV has $$$n$$$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $$$n$$$ other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from $$$1$$$ to $$$n$$$ and the kingdoms from $$$1$$$ to $$$n$$$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $$$n$$$-th daughter.For example, let there be $$$4$$$ daughters and kingdoms, the lists daughters have are $$$[2, 3]$$$, $$$[1, 2]$$$, $$$[3, 4]$$$, $$$[3]$$$, respectively. In that case daughter $$$1$$$ marries the prince of kingdom $$$2$$$, daughter $$$2$$$ marries the prince of kingdom $$$1$$$, daughter $$$3$$$ marries the prince of kingdom $$$3$$$, leaving daughter $$$4$$$ nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer $$$t$$$ independent test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of daughters and the number of kingdoms. Each of the next $$$n$$$ lines contains the description of each daughter's list. The first integer $$$k$$$ ($$$0 \\le k \\le n$$$) is the number of entries in the $$$i$$$-th daughter's list. After that $$$k$$$ distinct integers follow $$$g_i[1], g_i[2], \\dots, g_i[k]$$$ ($$$1 \\le g_i[j] \\le n$$$) \u2014 the indices of the kingdoms in the list in the increasing order ($$$g_i[1] < g_i[2] < \\dots < g_i[k]$$$). It's guaranteed that the total number of daughters over all test cases does not exceed $$$10^5$$$. It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the answer to it. Print \"IMPROVE\" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers \u2014 the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list. If there are multiple ways to add an entry so that the total number of married couples increases then print any of them. Otherwise the only line should contain one word \"OPTIMAL\".", "sample_inputs": ["5\n4\n2 2 3\n2 1 2\n2 3 4\n1 3\n2\n0\n0\n3\n3 1 2 3\n3 1 2 3\n3 1 2 3\n1\n1 1\n4\n1 1\n1 2\n1 3\n1 4"], "sample_outputs": ["IMPROVE\n4 4\nIMPROVE\n1 1\nOPTIMAL\nOPTIMAL\nOPTIMAL"], "notes": "NoteThe first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.In the second test case any new entry will increase the number of marriages from $$$0$$$ to $$$1$$$.In the third and the fourth test cases there is no way to add an entry.In the fifth test case there is no way to change the marriages by adding any entry."}, "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\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"} {"nl": {"description": "You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between $$$0$$$ and $$$100$$$ points, inclusive, for each stage, independently of other contestants.Points received by contestants in different stages are used for forming overall contest results. Suppose that $$$k$$$ stages of the contest are completed. For each contestant, $$$k - \\lfloor \\frac{k}{4} \\rfloor$$$ stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here $$$\\lfloor t \\rfloor$$$ denotes rounding $$$t$$$ down.)For example, suppose $$$9$$$ stages are completed, and your scores are $$$50, 30, 50, 50, 100, 10, 30, 100, 50$$$. First, $$$7$$$ stages with the highest scores are chosen\u00a0\u2014 for example, all stages except for the $$$2$$$-nd and the $$$6$$$-th can be chosen. Then your overall result is equal to $$$50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$$$.As of now, $$$n$$$ stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of completed stages. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 100$$$)\u00a0\u2014 your points for the completed stages. The third line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$0 \\le b_i \\le 100$$$)\u00a0\u2014 Ilya's points for the completed stages. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the smallest number of additional stages required for your result to be able to become greater than or equal to Ilya's result. If your result is already not less than Ilya's result, print $$$0$$$.", "sample_inputs": ["5\n1\n100\n0\n1\n0\n100\n4\n20 30 40 50\n100 100 100 100\n4\n10 20 30 40\n100 100 100 100\n7\n7 59 62 52 27 31 55\n33 35 50 98 83 80 64"], "sample_outputs": ["0\n1\n3\n4\n2"], "notes": "NoteIn the first test case, you have scored $$$100$$$ points for the first stage, while Ilya has scored $$$0$$$. Thus, your overall result ($$$100$$$) is already not less than Ilya's result ($$$0$$$).In the second test case, you have scored $$$0$$$ points for the first stage, while Ilya has scored $$$100$$$. A single stage with an opposite result is enough for both your and Ilya's overall scores to become equal to $$$100$$$.In the third test case, your overall result is $$$30 + 40 + 50 = 120$$$, while Ilya's result is $$$100 + 100 + 100 = 300$$$. After three additional stages your result might become equal to $$$420$$$, while Ilya's result might become equal to $$$400$$$.In the fourth test case, your overall result after four additional stages might become equal to $$$470$$$, while Ilya's result might become equal to $$$400$$$. Three stages are not enough."}, "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, n << 1, 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, 200000, 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, 500000, 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"} {"nl": {"description": "\"The zombies are lurking outside. Waiting. Moaning. And when they come...\"\"When they come?\"\"I hope the Wall is high enough.\"Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.", "input_spec": "The first line of the input consists of two space-separated integers R and C, 1\u2009\u2264\u2009R,\u2009C\u2009\u2264\u2009100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R\u2009-\u2009r\u2009+\u20091, and . otherwise. B", "output_spec": "The number of wall segments in the input configuration.", "sample_inputs": ["3 7\n.......\n.......\n.BB.B..", "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "1 1\nB", "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB"], "sample_outputs": ["2", "2", "1", "1", "3", "2"], "notes": "NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second."}, "positive_code": [{"source_code": "/**\n * Created by John Compitello on 7/25/16.\n */\nobject Easy {\n def main(args: Array[String]) = {\n val lines: Array[String] = (for (ln <- io.Source.stdin.getLines) yield (ln)).toArray\n val wallSegments = lines(lines.length - 1).split(\"\\\\.\").filter(_ != \"\")\n println(wallSegments.length)\n }\n}\n"}], "negative_code": [], "src_uid": "c339795767a174a59225a79023b5d14f"} {"nl": {"description": "You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1\u2009<\u2009i\u2009\u2264\u2009n) holds ci\u2009\u2264\u2009ci\u2009-\u20091. Let's denote s as the total number of cells of table a, that is, . We know that each cell of the table contains a single integer from 1 to s, at that all written integers are distinct. Let's assume that the cells of the i-th row of table a are numbered from 1 to ci, then let's denote the number written in the j-th cell of the i-th row as ai,\u2009j. Your task is to perform several swap operations to rearrange the numbers in the table so as to fulfill the following conditions: for all i,\u2009j (1\u2009<\u2009i\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009j\u2009\u2264\u2009ci) holds ai,\u2009j\u2009>\u2009ai\u2009-\u20091,\u2009j; for all i,\u2009j (1\u2009\u2264\u2009i\u2009\u2264\u2009n;\u00a01\u2009<\u2009j\u2009\u2264\u2009ci) holds ai,\u2009j\u2009>\u2009ai,\u2009j\u2009-\u20091. In one swap operation you are allowed to choose two different cells of the table and swap the recorded there numbers, that is the number that was recorded in the first of the selected cells before the swap, is written in the second cell after it. Similarly, the number that was recorded in the second of the selected cells, is written in the first cell after the swap.Rearrange the numbers in the required manner. Note that you are allowed to perform any number of operations, but not more than s. You do not have to minimize the number of operations.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) that shows the number of rows in the table. The second line contains n space-separated integers ci (1\u2009\u2264\u2009ci\u2009\u2264\u200950;\u00a0ci\u2009\u2264\u2009ci\u2009-\u20091) \u2014 the numbers of cells on the corresponding rows. Next n lines contain table \u0430. The i-th of them contains ci space-separated integers: the j-th integer in this line represents ai,\u2009j. It is guaranteed that all the given numbers ai,\u2009j are positive and do not exceed s. It is guaranteed that all ai,\u2009j are distinct.", "output_spec": "In the first line print a single integer m (0\u2009\u2264\u2009m\u2009\u2264\u2009s), representing the number of performed swaps. In the next m lines print the description of these swap operations. In the i-th line print four space-separated integers xi,\u2009yi,\u2009pi,\u2009qi (1\u2009\u2264\u2009xi,\u2009pi\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009yi\u2009\u2264\u2009cxi;\u00a01\u2009\u2264\u2009qi\u2009\u2264\u2009cpi). The printed numbers denote swapping the contents of cells axi,\u2009yi and api,\u2009qi. Note that a swap operation can change the contents of distinct table cells. Print the swaps in the order, in which they should be executed.", "sample_inputs": ["3\n3 2 1\n4 3 5\n6 1\n2", "1\n4\n4 3 2 1"], "sample_outputs": ["2\n1 1 2 2\n2 1 3 1", "2\n1 1 1 4\n1 2 1 3"], "notes": null}, "positive_code": [{"source_code": "\n\nobject JungTables extends App {\n // reading data\n var moves:List[(Int, Int, Int, Int)] = List()\n val n = Console.readLine() toInt\n var aa = Array.fill(n, 1)(0)\n val cc = Console.readLine() split(\" \") map (_.toInt)\n for (i <- 0 until n) {\n aa(i) = Console.readLine() split(\" \") map (_.toInt)\n }\n \n def findMin(ia: Int, ja:Int) : (Int, Int, Int) = {\n var mn=aa(ia)(ja)\n var ii=ia\n var jj=ja\n for {\n i <- Range(ia, n)\n j <- Range(ja, cc(i))\n } if (aa(i)(j) < mn) {\n mn = aa(i)(j); ii = i; jj=j\n }\n (mn, ii, jj)\n }\n \n def fixPoint(ia:Int, ja:Int) = {\n val (mn, ii, jj) = findMin(ia, ja) \n if (ii != ia || jj != ja) {\n val temp = aa(ia)(ja)\n aa(ia)(ja) = aa(ii)(jj)\n aa(ii)(jj) = temp\n moves = (ia+1, ja+1, ii+1, jj+1) :: moves \n }\n }\n \n for {\n i <- 0 until n\n j <- 0 until cc(i)\n } fixPoint(i,j)\n moves = moves reverse;\n println(moves length)\n for ((a,b,c,d) <- moves) \n println(a + \" \" + b + \" \" + c + \" \" + d)\n}"}], "negative_code": [], "src_uid": "62df8b1821558bea910f422591618e29"} {"nl": {"description": "You are given an array $$$a$$$ with $$$n$$$ non-negative integers. You can apply the following operation on it. Choose two indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$). If $$$a_l + a_r$$$ is odd, do $$$a_r := a_l$$$. If $$$a_l + a_r$$$ is even, do $$$a_l := a_r$$$. Find any sequence of at most $$$n$$$ operations that makes $$$a$$$ non-decreasing. It can be proven that it is always possible. Note that you do not have to minimize the number of operations.An array $$$a_1, a_2, \\ldots, a_n$$$ is non-decreasing if and only if $$$a_1 \\le a_2 \\le \\ldots \\le a_n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$) \u00a0\u2014 the array itself. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print one integer $$$m$$$ ($$$0 \\le m \\le n$$$), the number of operations, in the first line. Then print $$$m$$$ lines. Each line must contain two integers $$$l_i, r_i$$$, which are the indices you chose in the $$$i$$$-th operation ($$$1 \\le l_i < r_i \\le n$$$). If there are multiple solutions, print any of them.", "sample_inputs": ["3\n\n2\n\n7 8\n\n5\n\n1 1000000000 3 0 5\n\n1\n\n0"], "sample_outputs": ["0\n2\n3 4\n1 2\n0"], "notes": "NoteIn the second test case, $$$a$$$ changes like this: Select indices $$$3$$$ and $$$4$$$. $$$a_3 + a_4 = 3$$$ is odd, so do $$$a_4 := a_3$$$. $$$a = [1, 1000000000, 3, 3, 5]$$$ now. Select indices $$$1$$$ and $$$2$$$. $$$a_1 + a_2 = 1000000001$$$ is odd, so do $$$a_2 := a_1$$$. $$$a = [1, 1, 3, 3, 5]$$$ now, and it is non-decreasing. In the first and third test cases, $$$a$$$ is already non-decreasing."}, "positive_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 n = readInt()\r\n val a: Array[Int] = readLine().split(\" \").map(_.toInt)\r\n println(n - 1)\r\n if(n != 1) println(s\"1 $n\")\r\n val pivot = if((a(0) + a(n-1)) % 2 == 0) a(n-1) else a(0)\r\n for(i <- 2 to (n - 1)){\r\n if((a(i - 1) + pivot) % 2 == 0) \r\n println(s\"$i $n\")\r\n else\r\n println(s\"1 $i\")\r\n }\r\n\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"}], "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 n = readInt()\r\n val a: Array[Int] = readLine().split(\" \").map(_.toInt)\r\n println(n - 1)\r\n println(s\"1 $n\")\r\n val pivot = if((a(0) + a(n-1)) % 2 == 0) a(n-1) else a(0)\r\n for(i <- 2 to (n - 1)){\r\n if((a(i - 1) + pivot) % 2 == 0) \r\n println(s\"$i $n\")\r\n else\r\n println(s\"1 $i\")\r\n }\r\n \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": "10f3f4ae348fd4d28c371d8bf570d4c2"} {"nl": {"description": "Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\\leq n\\leq 100$$$, $$$1\\leq d\\leq 10^9$$$)\u00a0\u2014 the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \\ldots, x_n$$$ ($$$-10^9\\leq x_i\\leq 10^9$$$)\u00a0\u2014 coordinates of Sonya's hotels.", "output_spec": "Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.", "sample_inputs": ["4 3\n-3 2 9 16", "5 2\n4 8 11 18 19"], "sample_outputs": ["6", "5"], "notes": "NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "5babbb7c5f6b494992ffa921c8e19294"} {"nl": {"description": "Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.", "input_spec": "The first line contains $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$) \u2014 all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \\dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.", "output_spec": "In the first line, output $$$t$$$ \u2014 the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers \u2014 the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.", "sample_inputs": ["7\n1 2 3 1 2 3 4", "4\n1 1 1 1", "5\n1 2 3 4 5", "5\n1 2 1 2 1"], "sample_outputs": ["2\n3 4", "4\n1 1 1 1", "1\n5", "3\n2 2 1"], "notes": null}, "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 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}"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "0ee86e75ff7a47a711c9eb41b34ad1a5"} {"nl": {"description": "There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\leq i, j \\leq n$$$; $$$i \\neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\\max(a)-\\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^7$$$)\u00a0\u2014 the heights of the buildings.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimum possible ugliness of the buildings.", "sample_inputs": ["3\n3\n10 10 10\n4\n3 2 1 2\n5\n1 2 3 1 5"], "sample_outputs": ["0\n0\n1"], "notes": "NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations: with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$, with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$, with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$. The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test."}, "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615A(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nclass CF1615A (fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n\r\n import Main._\r\n import fScanner._\r\n\r\n def solve(): Unit = {\r\n val T = ni()\r\n (1 to T).foreach { i =>\r\n val n = ni()\r\n val sum =\r\n (1 to n).map(_ => ni()).sum\r\n out.println{\r\n if (sum % n == 0) 0\r\n else 1\r\n }\r\n }\r\n }\r\n\r\n}"}], "negative_code": [], "src_uid": "644ef17fe304b090e0cf33a84ddc546a"} {"nl": {"description": "You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \\le l_i \\le r_i \\le 10^9$$$) \u2014 the description of the $$$i$$$-th segment.", "output_spec": "Print a single integer \u2014 the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.", "sample_inputs": ["4\n1 3\n2 6\n0 4\n3 3", "5\n2 6\n1 3\n0 4\n1 20\n0 4", "3\n4 5\n1 2\n9 20", "2\n3 10\n1 5"], "sample_outputs": ["1", "2", "0", "7"], "notes": "NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$."}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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}"}, {"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}"}], "negative_code": [], "src_uid": "b50df0e6d91d538cd7db8dfdc7cd5266"} {"nl": {"description": "Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.", "input_spec": "The first line contains three integers: a,\u2009b,\u2009n (1\u2009\u2264\u2009a,\u2009b,\u2009n\u2009\u2264\u2009105).", "output_spec": "In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.", "sample_inputs": ["5 4 5", "12 11 1", "260 150 10"], "sample_outputs": ["524848", "121", "-1"], "notes": null}, "positive_code": [{"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": "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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string \"aabaabaabaab\" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.", "input_spec": "The first input line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1\u2009\u2264\u2009|s|\u2009\u2264\u20091000, where |s| is the length of string s.", "output_spec": "Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print \"-1\" (without quotes).", "sample_inputs": ["2\naazz", "3\nabcabcabz"], "sample_outputs": ["azaz", "-1"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?", "input_spec": "First line of input data contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 length of the array. Next line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Output answer in single line. \"First\", if first player wins, and \"Second\" otherwise (without quotes).", "sample_inputs": ["4\n1 3 2 3", "2\n2 2"], "sample_outputs": ["First", "Second"], "notes": "NoteIn first sample first player remove whole array in one move and win.In second sample first player can't make a move and lose."}, "positive_code": [{"source_code": "/**\n * Created by mettu.r on 20/08/17.\n */\nobject Demo extends App {\n override def main(args: Array[String]): Unit = {\n var n = readInt();\n var a = readLine().split(\" \").map( x => x.toInt)\n var sum = 0;\n a.foreach(x =>{\n sum += x;\n sum %= 2;\n });\n var ans = false;\n if( sum % 2 == 1 )\n ans = true;\n a.foreach(x => if( x % 2 == 1 ) ans = true);\n if( ans )\n println(\"First\\n\");\n else\n println(\"Second\\n\");\n }\n}"}], "negative_code": [], "src_uid": "808611f86c70659a1d5b8fc67875de31"} {"nl": {"description": "Let's call an array $$$t$$$ dominated by value $$$v$$$ in the next situation.At first, array $$$t$$$ should have at least $$$2$$$ elements. Now, let's calculate number of occurrences of each number $$$num$$$ in $$$t$$$ and define it as $$$occ(num)$$$. Then $$$t$$$ is dominated (by $$$v$$$) if (and only if) $$$occ(v) > occ(v')$$$ for any other number $$$v'$$$. For example, arrays $$$[1, 2, 3, 4, 5, 2]$$$, $$$[11, 11]$$$ and $$$[3, 2, 3, 2, 3]$$$ are dominated (by $$$2$$$, $$$11$$$ and $$$3$$$ respectevitely) but arrays $$$[3]$$$, $$$[1, 2]$$$ and $$$[3, 3, 2, 2, 1]$$$ are not.Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.You are given array $$$a_1, a_2, \\dots, a_n$$$. Calculate its shortest dominated subarray or say that there are no such subarrays.The subarray of $$$a$$$ is a contiguous part of the array $$$a$$$, i.\u2009e. the array $$$a_i, a_{i + 1}, \\dots, a_j$$$ for some $$$1 \\le i \\le j \\le n$$$.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$) \u2014 the corresponding values of the array $$$a$$$. It's guaranteed that the total length of all arrays in one test doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 one per test case. For each test case print the only integer \u2014 the length of the shortest dominated subarray, or $$$-1$$$ if there are no such subarrays.", "sample_inputs": ["4\n1\n1\n6\n1 2 3 4 5 1\n9\n4 1 2 4 5 4 3 2 1\n4\n3 3 3 3"], "sample_outputs": ["-1\n6\n3\n2"], "notes": "NoteIn the first test case, there are no subarrays of length at least $$$2$$$, so the answer is $$$-1$$$.In the second test case, the whole array is dominated (by $$$1$$$) and it's the only dominated subarray.In the third test case, the subarray $$$a_4, a_5, a_6$$$ is the shortest dominated subarray.In the fourth test case, all subarrays of length more than one are dominated."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner\u00a0\u2014 Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D'\u00a0\u2014 the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.", "output_spec": "If Anton won more games than Danik, print \"Anton\" (without quotes) in the only line of the output. If Danik won more games than Anton, print \"Danik\" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print \"Friendship\" (without quotes).", "sample_inputs": ["6\nADAAAA", "7\nDDDAADA", "6\nDADADA"], "sample_outputs": ["Anton", "Danik", "Friendship"], "notes": "NoteIn the first sample, Anton won 6 games, while Danik\u00a0\u2014 only 1. Hence, the answer is \"Anton\".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is \"Danik\".In the third sample, both Anton and Danik won 3 games and the answer is \"Friendship\"."}, "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": "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}"}, {"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"} {"nl": {"description": "This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pok\u00e9mon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pok\u00e9mon! Pok\u00e9mon trainer Andrew decided to help Pikachu to build a pok\u00e9mon army to resist.First, Andrew counted all the pok\u00e9mon\u00a0\u2014 there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pok\u00e9mon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \\le b_1 < b_2 < \\dots < b_k \\le n$$$, and his army will consist of pok\u00e9mons with forces $$$a_{b_1}, a_{b_2}, \\dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \\dots$$$.Andrew is experimenting with pok\u00e9mon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pok\u00e9mon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pok\u00e9mon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pok\u00e9mon, or team R will realize their tricky plan!", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n \\le 3 \\cdot 10^5, q = 0$$$) denoting the number of pok\u00e9mon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$) denoting the strengths of the pok\u00e9mon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) denoting the indices of pok\u00e9mon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$. ", "output_spec": "For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.", "sample_inputs": ["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"], "sample_outputs": ["3\n2\n9"], "notes": "NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5\u22123+7=9$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Moamen has an array of $$$n$$$ distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once: Split the array into exactly $$$k$$$ non-empty subarrays such that each element belongs to exactly one subarray. Reorder these subarrays arbitrary. Merge the subarrays in their new order. A sequence $$$a$$$ is a subarray of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le |a_i| \\le 10^9$$$). It is guaranteed that all numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\\cdot10^5$$$.", "output_spec": "For each test case, you should output a single string. If Moamen can sort the array in non-decreasing order, output \"YES\" (without quotes). Otherwise, output \"NO\" (without quotes). You can print each letter of \"YES\" and \"NO\" in any case (upper or lower).", "sample_inputs": ["3\n5 4\n6 3 4 2 1\n4 2\n1 -4 0 -2\n5 1\n1 2 3 4 5"], "sample_outputs": ["Yes\nNo\nYes"], "notes": "NoteIn the first test case, $$$a = [6, 3, 4, 2, 1]$$$, and $$$k = 4$$$, so we can do the operations as follows: Split $$$a$$$ into $$$\\{ [6], [3, 4], [2], [1] \\}$$$. Reorder them: $$$\\{ [1], [2], [3,4], [6] \\}$$$. Merge them: $$$[1, 2, 3, 4, 6]$$$, so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only $$$2$$$ subarrays.As an example, if we split it into $$$\\{ [1, -4], [0, -2] \\}$$$, we can reorder them into $$$\\{ [1, -4], [0, -2] \\}$$$ or $$$\\{ [0, -2], [1, -4] \\}$$$. However, after merging the subarrays, it is impossible to get a sorted array."}, "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"}, {"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"}], "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"} {"nl": {"description": "Bash likes playing with arrays. He has an array a1,\u2009a2,\u2009... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.Suppose he guesses that the gcd of the elements in the range [l,\u2009r] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array \u2014 he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process q queries of one of the following forms: 1\u2009l\u2009r\u2009x \u2014 Bash guesses that the gcd of the range [l,\u2009r] is x. Report if this guess is almost correct. 2\u2009i\u2009y \u2014 Bash sets ai to y. Note: The array is 1-indexed.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u00a0\u2014 the size of the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u00a0\u2014 the elements of the array. The third line contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u20094\u00b7105) \u00a0\u2014 the number of queries. The next q lines describe the queries and may have one of the following forms: 1\u2009l\u2009r\u2009x (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009x\u2009\u2264\u2009109). 2\u2009i\u2009y (1\u2009\u2264\u2009i\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009109). Guaranteed, that there is at least one query of first type.", "output_spec": "For each query of first type, output \"YES\" (without quotes) if Bash's guess is almost correct and \"NO\" (without quotes) otherwise.", "sample_inputs": ["3\n2 6 3\n4\n1 1 2 2\n1 1 3 3\n2 1 9\n1 1 3 2", "5\n1 2 3 4 5\n6\n1 1 4 2\n2 3 6\n1 1 4 2\n1 1 5 2\n2 5 10\n1 1 5 2"], "sample_outputs": ["YES\nYES\nNO", "NO\nYES\nNO\nYES"], "notes": "NoteIn the first sample, the array initially is {2,\u20096,\u20093}. For query 1, the first two numbers already have their gcd as 2.For query 2, we can achieve a gcd of 3 by changing the first element of the array to 3. Note that the changes made during queries of type 1 are temporary and do not get reflected in the array. After query 3, the array is now {9,\u20096,\u20093}. For query 4, no matter which element you change, you cannot get the gcd of the range to be 2. "}, "positive_code": [{"source_code": "import java.util\n\nimport 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 as = readInts(n)\n val Array(q) = readInts(1)\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n\n case class SegTree(as: Array[Int]) {\n\n //val NEUTRAL = Array.empty[Int]\n\n private 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) = gcd(t(v2), t(v2 + 1))\n }\n }\n\n private def merge(left: Array[Int], right: Array[Int]): Array[Int] = {\n val resBuilder = new mutable.ArrayBuilder.ofInt\n var l = 0\n var r = 0\n while (l < left.length && r < right.length) {\n if (left(l) == right(r)) {\n resBuilder += left(l)\n l += 1\n r += 1\n } else if (left(l) < right(r)) l += 1\n else r += 1\n }\n val res = resBuilder.result()\n println(\"Merge \" + left.mkString(\" \") + \"; \" + right.mkString(\" \") + \"; \" + res.mkString(\" \") + \"; \")\n res\n }\n\n def query(l: Int, r: Int, goal: Int, canChange: Boolean, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Boolean = {\n if (l > r) true\n else if (l == tl && r == tr && l == r) {\n canChange || t(v) % goal == 0\n } else if (l == tl && r == tr && t(v) % goal == 0) {\n true\n } else if (l == tl && r == tr && !canChange) {\n t(v) % goal == 0\n } else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n val q1 = query(l, Math.min(r, tm), goal, false, v2, tl, tm)\n val q2 = query(Math.max(l, tm + 1), r, goal, false, v2 + 1, tm + 1, tr)\n if (q1 && q2) true\n else if ((q1 || q2) && canChange) {\n (q1 && query(Math.max(l, tm + 1), r, goal, true, v2 + 1, tm + 1, tr)) ||\n (q2 && query(l, Math.min(r, tm), goal, true, v2, tl, tm))\n } else false\n }\n }\n\n def update(pos: Int, value: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {\n if (tl == tr) t(v) = value\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n if (pos <= tm) update(pos, value, v2, tl, tm)\n else update(pos, value, v2 + 1, tm + 1, tr)\n t(v) = gcd(t(v2), t(v2 + 1))\n }\n }\n\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val segTree = SegTree(as)\n\n for (_ <- 1 to q) {\n val s = readLine\n if (s.head == '1') {\n val Array(_, _l, _r, x) = s.split(\" \").map(_.toInt)\n val l = _l - 1\n val r = _r - 1\n val ok = segTree.query(l, r, x, true)\n println(if (ok) \"YES\" else \"NO\")\n } else {\n val Array(_, i, y) = s.split(\" \").map(_.toInt)\n as(i - 1) = y\n segTree.update(i - 1, y)\n }\n }\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "39e7083c9d16a8cb92fc93bd8185fad2"} {"nl": {"description": "Little penguin Polo adores integer segments, that is, pairs of integers [l;\u00a0r] (l\u2009\u2264\u2009r). He has a set that consists of n integer segments: [l1;\u00a0r1],\u2009[l2;\u00a0r2],\u2009...,\u2009[ln;\u00a0rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l;\u00a0r] to either segment [l\u2009-\u20091;\u00a0r], or to segment [l;\u00a0r\u2009+\u20091].The value of a set of segments that consists of n segments [l1;\u00a0r1],\u2009[l2;\u00a0r2],\u2009...,\u2009[ln;\u00a0rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj\u2009\u2264\u2009x\u2009\u2264\u2009rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009105). Each of the following n lines contain a segment as a pair of integers li and ri (\u2009-\u2009105\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i,\u2009j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) the following inequality holds, min(ri,\u2009rj)\u2009<\u2009max(li,\u2009lj).", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"], "sample_outputs": ["2", "0"], "notes": null}, "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": "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 }"}, {"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"} {"nl": {"description": "n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8,\u200910,\u200913,\u200914,\u200916] currently in the circle, the leader is child 13 and ai\u2009=\u200912, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.", "input_spec": "The first line contains two integer numbers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009-\u20091). The next line contains k integer numbers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.", "sample_inputs": ["7 5\n10 4 11 4 1", "3 2\n2 5"], "sample_outputs": ["4 2 5 6 1", "3 2"], "notes": "NoteLet's consider first example: In the first step child 4 is eliminated, child 5 becomes the leader. In the second step child 2 is eliminated, child 3 becomes the leader. In the third step child 5 is eliminated, child 6 becomes the leader. In the fourth step child 6 is eliminated, child 7 becomes the leader. In the final step child 1 is eliminated, child 3 becomes the leader. "}, "positive_code": [{"source_code": "import io.StdIn.readLine\nobject B extends App{\n val Array(n, k) = readLine().split(' ').map(_.toInt)\n\n val game = readLine().split(' ').map(_.toInt).scanLeft((Vector.range[Int](1, n + 1), -1)) {\n case ((children, _), num) \u21d2\n val i = num % children.size\n (children.drop(i + 1) ++ children.take(i), children(i))\n }.map(_._2).tail\n\n println(game.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "5512fbe2963dab982a58a14daf805291"} {"nl": {"description": "Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.Given two strings s1 and s2 consist of lowercase Latin letters, find the smallest (by length) common substring p of both s1 and s2, where p is a unique substring in s1 and also in s2. See notes for formal definition of substring and uniqueness.", "input_spec": "The first line of input contains s1 and the second line contains s2 (1\u2009\u2264\u2009|s1|,\u2009|s2|\u2009\u2264\u20095000). Both strings consist of lowercase Latin letters.", "output_spec": "Print the length of the smallest common unique substring of s1 and s2. If there are no common unique substrings of s1 and s2 print -1.", "sample_inputs": ["apple\npepperoni", "lover\ndriver", "bidhan\nroy", "testsetses\nteeptes"], "sample_outputs": ["2", "1", "-1", "3"], "notes": "NoteImagine we have string a\u2009=\u2009a1a2a3...a|a|, where |a| is the length of string a, and ai is the ith letter of the string. We will call string alal\u2009+\u20091al\u2009+\u20092...ar (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009|a|) the substring [l,\u2009r] of the string a. The substring [l,\u2009r] is unique in a if and only if there is no pair l1,\u2009r1 such that l1\u2009\u2260\u2009l and the substring [l1,\u2009r1] is equal to the substring [l,\u2009r] in a."}, "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 * \u3053\u308c\u4ee5\u4e0a\u306e\u9577\u3055\u306e\u90e8\u5206\u6587\u5b57\u5217\u3058\u3083\u306a\u3044\u3068\u91cd\u8907\u304c\u5b58\u5728\u3059\u308b\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\u304cS1\u306b, p2\u304cS2\u306b\u542b\u307e\u308c\u308b\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\u3068\u3082\u306b\u91cd\u8907\u5236\u9650\u306b\u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u6700\u77ed\u306e\u6587\u5b57\u5217\n val len = mxLim + 1\n\n // lcp\u304clen\u3092\u4f5c\u308c\u308b\u7a0b\u306b\u5341\u5206\u9577\u3044\n if (len <= lcp(i)) {\n // p1+leln\u304cS1\u3092\u8d85\u3048\u306a\u3044\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\u306b\u306f\u4e00\u500b\u624b\u524d\u306e\u6587\u5b57\u3068\u306e\u5171\u901a\u306e\u6587\u5b57\u6570\u304c\u5165\u3063\u3066\u3044\u308b\n * @return (LCP, \u6587\u5b57\u5217\u306e\u4f4d\u7f6e => \u8f9e\u66f8\u9806\u306e\u4f4d)\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\u4e0a\u3067\uff11\u500b\u524d\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 * \u5927\u6587\u5b57\u5c0f\u6587\u5b57\u304c\u6df7\u3056\u3063\u3066\u308b\u5834\u5408\u306f\u3046\u307e\u304f\u3044\u304b\u306a\u3044\u306e\u3067\u6ce8\u610f\n * @return \u8f9e\u66f8\u9806 => \u6587\u5b57\u5217\u306e\u4f4d\u7f6e\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 // \u9577\u3055\u304c\u8db3\u308a\u306a\u3044\u3063\u3066\u3053\u3068\u306f\u6587\u5b57\u304c\u306a\u3044\u3066\u3053\u3068\u306a\u306e\u3067\u3001\u8f9e\u66f8\u9806\u3067\u5148\u306b\u306a\u308b\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 // \u4eca\u306e\u30e9\u30f3\u30af\u3068\u30c0\u30d6\u30ea\u30f3\u30b0\u3092\u3064\u304b\u3063\u3066len*2\u307e\u3067\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u308b\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // \u6b21\u306elen*2\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u305fsa\u304b\u3089rank\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\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) // \u524d\u306e\u9806\u4f4d\u306e\u3082\u306e\u3088\u308a\u5927\u304d\u3044\u5834\u5408\u306f+1\u3059\u308b\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": "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"}], "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 * \u3053\u308c\u4ee5\u4e0a\u306e\u9577\u3055\u306e\u90e8\u5206\u6587\u5b57\u5217\u3058\u3083\u306a\u3044\u3068\u91cd\u8907\u304c\u5b58\u5728\u3059\u308b\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\u304cS1\u306b, p2\u304cS2\u306b\u542b\u307e\u308c\u308b\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\u3068\u3082\u306b\u91cd\u8907\u5236\u9650\u306b\u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u7a0b\u306e\u9577\u3044\u6587\u5b57\u5217\n if (len <= lcp(i)) {\n // p1+l\u304cS1\u3092\u8d85\u3048\u306a\u3044\n if (p1 + len <= S1.length) {\n // debug\n// System.err.println(s\"$i ${S.substring(p1, p1 + len)}\")\n ans = min(ans, len) // \u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u6700\u77ed\u306e\u6587\u5b57\u5217\n }\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCP\u306b\u306f\u4e00\u500b\u624b\u524d\u306e\u6587\u5b57\u3068\u306e\u5171\u901a\u306e\u6587\u5b57\u6570\u304c\u5165\u3063\u3066\u3044\u308b\n * @return (LCP, \u6587\u5b57\u5217\u306e\u4f4d\u7f6e => \u8f9e\u66f8\u9806\u306e\u4f4d)\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\u4e0a\u3067\uff11\u500b\u524d\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 * \u5927\u6587\u5b57\u5c0f\u6587\u5b57\u304c\u6df7\u3056\u3063\u3066\u308b\u5834\u5408\u306f\u3046\u307e\u304f\u3044\u304b\u306a\u3044\u306e\u3067\u6ce8\u610f\n * @return \u8f9e\u66f8\u9806 => \u6587\u5b57\u5217\u306e\u4f4d\u7f6e\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 // \u9577\u3055\u304c\u8db3\u308a\u306a\u3044\u3063\u3066\u3053\u3068\u306f\u6587\u5b57\u304c\u306a\u3044\u3066\u3053\u3068\u306a\u306e\u3067\u3001\u8f9e\u66f8\u9806\u3067\u5148\u306b\u306a\u308b\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 // \u4eca\u306e\u30e9\u30f3\u30af\u3068\u30c0\u30d6\u30ea\u30f3\u30b0\u3092\u3064\u304b\u3063\u3066len*2\u307e\u3067\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u308b\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // \u6b21\u306elen*2\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u305fsa\u304b\u3089rank\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\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) // \u524d\u306e\u9806\u4f4d\u306e\u3082\u306e\u3088\u308a\u5927\u304d\u3044\u5834\u5408\u306f+1\u3059\u308b\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 * \u3053\u308c\u4ee5\u4e0a\u306e\u9577\u3055\u306e\u90e8\u5206\u6587\u5b57\u5217\u3058\u3083\u306a\u3044\u3068\u91cd\u8907\u304c\u5b58\u5728\u3059\u308b\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\u304cS1\u306b, p2\u304cS2\u306b\u542b\u307e\u308c\u308b\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\u3068\u3082\u306b\u91cd\u8907\u5236\u9650\u306b\u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u7a0b\u306e\u9577\u3044\u6587\u5b57\u5217\n if (mxLim < lcp(i)) {\n val len = mxLim + 1\n // p1+l\u304cS1\u3092\u8d85\u3048\u306a\u3044\n// if (len <= S.length) {\n ans = min(ans, len) // \u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u6700\u77ed\u306e\u6587\u5b57\u5217\n// }\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCP\u306b\u306f\u4e00\u500b\u624b\u524d\u306e\u6587\u5b57\u3068\u306e\u5171\u901a\u306e\u6587\u5b57\u6570\u304c\u5165\u3063\u3066\u3044\u308b\n * @return (LCP, \u6587\u5b57\u5217\u306e\u4f4d\u7f6e => \u8f9e\u66f8\u9806\u306e\u4f4d)\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\u4e0a\u3067\uff11\u500b\u524d\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 * \u5927\u6587\u5b57\u5c0f\u6587\u5b57\u304c\u6df7\u3056\u3063\u3066\u308b\u5834\u5408\u306f\u3046\u307e\u304f\u3044\u304b\u306a\u3044\u306e\u3067\u6ce8\u610f\n * @return \u8f9e\u66f8\u9806 => \u6587\u5b57\u5217\u306e\u4f4d\u7f6e\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 // \u9577\u3055\u304c\u8db3\u308a\u306a\u3044\u3063\u3066\u3053\u3068\u306f\u6587\u5b57\u304c\u306a\u3044\u3066\u3053\u3068\u306a\u306e\u3067\u3001\u8f9e\u66f8\u9806\u3067\u5148\u306b\u306a\u308b\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 // \u4eca\u306e\u30e9\u30f3\u30af\u3068\u30c0\u30d6\u30ea\u30f3\u30b0\u3092\u3064\u304b\u3063\u3066len*2\u307e\u3067\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u308b\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // \u6b21\u306elen*2\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u305fsa\u304b\u3089rank\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\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) // \u524d\u306e\u9806\u4f4d\u306e\u3082\u306e\u3088\u308a\u5927\u304d\u3044\u5834\u5408\u306f+1\u3059\u308b\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 * \u3053\u308c\u4ee5\u4e0a\u306e\u9577\u3055\u306e\u90e8\u5206\u6587\u5b57\u5217\u3058\u3083\u306a\u3044\u3068\u91cd\u8907\u304c\u5b58\u5728\u3059\u308b\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\u304cS1\u306b, p2\u304cS2\u306b\u542b\u307e\u308c\u308b\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\u3068\u3082\u306b\u91cd\u8907\u5236\u9650\u306b\u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u6700\u77ed\u306e\u6587\u5b57\u5217\n val len = mxLim + 1\n\n // lcp\u304clen\u3092\u4f5c\u308c\u308b\u7a0b\u306b\u5341\u5206\u9577\u3044\n if (len <= lcp(i)) {\n // p1+leln\u304cS1\u3092\u8d85\u3048\u306a\u3044\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\u306b\u306f\u4e00\u500b\u624b\u524d\u306e\u6587\u5b57\u3068\u306e\u5171\u901a\u306e\u6587\u5b57\u6570\u304c\u5165\u3063\u3066\u3044\u308b\n * @return (LCP, \u6587\u5b57\u5217\u306e\u4f4d\u7f6e => \u8f9e\u66f8\u9806\u306e\u4f4d)\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\u4e0a\u3067\uff11\u500b\u524d\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 * \u5927\u6587\u5b57\u5c0f\u6587\u5b57\u304c\u6df7\u3056\u3063\u3066\u308b\u5834\u5408\u306f\u3046\u307e\u304f\u3044\u304b\u306a\u3044\u306e\u3067\u6ce8\u610f\n * @return \u8f9e\u66f8\u9806 => \u6587\u5b57\u5217\u306e\u4f4d\u7f6e\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 // \u9577\u3055\u304c\u8db3\u308a\u306a\u3044\u3063\u3066\u3053\u3068\u306f\u6587\u5b57\u304c\u306a\u3044\u3066\u3053\u3068\u306a\u306e\u3067\u3001\u8f9e\u66f8\u9806\u3067\u5148\u306b\u306a\u308b\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 // \u4eca\u306e\u30e9\u30f3\u30af\u3068\u30c0\u30d6\u30ea\u30f3\u30b0\u3092\u3064\u304b\u3063\u3066len*2\u307e\u3067\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u308b\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // \u6b21\u306elen*2\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u305fsa\u304b\u3089rank\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\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) // \u524d\u306e\u9806\u4f4d\u306e\u3082\u306e\u3088\u308a\u5927\u304d\u3044\u5834\u5408\u306f+1\u3059\u308b\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 * \u3053\u308c\u4ee5\u4e0a\u306e\u9577\u3055\u306e\u90e8\u5206\u6587\u5b57\u5217\u3058\u3083\u306a\u3044\u3068\u91cd\u8907\u304c\u5b58\u5728\u3059\u308b\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]\u304cS1\u306b, [p2, p2+len]\u304cS2\u306b\u542b\u307e\u308c\u308b\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\u3068\u3082\u306b\u91cd\u8907\u5236\u9650\u306b\u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u7a0b\u306e\u9577\u3044\u6587\u5b57\u5217\n if (mxLim < len) {\n ans = min(ans, mxLim + 1) // \u5f15\u3063\u304b\u304b\u3089\u306a\u3044\u6700\u77ed\u306e\u6587\u5b57\u5217\n }\n }\n }\n }\n\n if (ans == INF) ans = -1\n out.println(ans)\n }\n\n /**\n * LCP\u306b\u306f\u4e00\u500b\u624b\u524d\u306e\u6587\u5b57\u3068\u306e\u5171\u901a\u306e\u6587\u5b57\u6570\u304c\u5165\u3063\u3066\u3044\u308b\n * @return (LCP, \u6587\u5b57\u5217\u306e\u4f4d\u7f6e => \u8f9e\u66f8\u9806\u306e\u4f4d)\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\u4e0a\u3067\uff11\u500b\u524d\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 * \u5927\u6587\u5b57\u5c0f\u6587\u5b57\u304c\u6df7\u3056\u3063\u3066\u308b\u5834\u5408\u306f\u3046\u307e\u304f\u3044\u304b\u306a\u3044\u306e\u3067\u6ce8\u610f\n * @return \u8f9e\u66f8\u9806 => \u6587\u5b57\u5217\u306e\u4f4d\u7f6e\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 // \u9577\u3055\u304c\u8db3\u308a\u306a\u3044\u3063\u3066\u3053\u3068\u306f\u6587\u5b57\u304c\u306a\u3044\u3066\u3053\u3068\u306a\u306e\u3067\u3001\u8f9e\u66f8\u9806\u3067\u5148\u306b\u306a\u308b\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 // \u4eca\u306e\u30e9\u30f3\u30af\u3068\u30c0\u30d6\u30ea\u30f3\u30b0\u3092\u3064\u304b\u3063\u3066len*2\u307e\u3067\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u308b\n Sorting.quickSort[Int](sa)(Ordering.fromLessThan(lt(len)))\n\n // \u6b21\u306elen*2\u306e\u9577\u3055\u3067\u4e26\u3073\u66ff\u3048\u305fsa\u304b\u3089rank\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\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) // \u524d\u306e\u9806\u4f4d\u306e\u3082\u306e\u3088\u308a\u5927\u304d\u3044\u5834\u5408\u306f+1\u3059\u308b\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"} {"nl": {"description": "One day, Ahmed_Hossam went to Hemose and said \"Let's solve a gym contest!\". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?There is an Agent in Valorant, and he has $$$n$$$ weapons. The $$$i$$$-th weapon has a damage value $$$a_i$$$, and the Agent will face an enemy whose health value is $$$H$$$.The Agent will perform one or more moves until the enemy dies.In one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to $$$0$$$. However, not everything is so easy: the Agent can't choose the same weapon for $$$2$$$ times in a row.What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \\leq t \\leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$H$$$ $$$(2 \\leq n \\leq 10^3, 1 \\leq H \\leq 10^9)$$$ \u2014 the number of available weapons and the initial health value of the enemy. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(1 \\leq a_i \\leq 10^9)$$$ \u2014 the damage values of the weapons. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer \u2014 the minimum number of times that the Agent will have to use the weapons to kill the enemy.", "sample_inputs": ["3\n2 4\n3 7\n2 6\n4 2\n3 11\n2 1 7"], "sample_outputs": ["1\n2\n3"], "notes": "NoteIn the first test case, the Agent can use the second weapon, making health value of the enemy equal to $$$4-7=-3$$$. $$$-3 \\le 0$$$, so the enemy is dead, and using weapon $$$1$$$ time was enough.In the second test case, the Agent can use the first weapon first, and then the second one. After this, the health of enemy will drop to $$$6-4-2 = 0$$$, meaning he would be killed after using weapons $$$2$$$ times.In the third test case, the Agent can use the weapons in order (third, first, third), decreasing the health value of enemy to $$$11 - 7 - 2 - 7 = -5$$$ after using the weapons $$$3$$$ times. Note that we can't kill the enemy by using the third weapon twice, as even though $$$11-7-7<0$$$, it's not allowed to use the same weapon twice in a row."}, "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 = 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": "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"} {"nl": {"description": "Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $$$n$$$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $$$0$$$, and removing $$$i$$$-th character increases the ambiguity by $$$a_i$$$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $$$4$$$ even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the statement. The second line contains one string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters \u2014 the statement written by Vasya. The third line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 998244353$$$).", "output_spec": "Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.", "sample_inputs": ["6\nhhardh\n3 2 9 11 7 1", "8\nhhzarwde\n3 2 6 9 4 8 7 1", "6\nhhaarr\n1 2 3 4 5 6"], "sample_outputs": ["5", "4", "0"], "notes": "NoteIn the first example, first two characters are removed so the result is ardh.In the second example, $$$5$$$-th character is removed so the result is hhzawde.In the third example there's no need to remove anything."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "8cc22dc6e81bb49b64136e5ff7eb8caf"} {"nl": {"description": "You are given a matrix $$$a$$$ of size $$$n \\times m$$$ consisting of integers.You can choose no more than $$$\\left\\lfloor\\frac{m}{2}\\right\\rfloor$$$ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by $$$k$$$ and this sum is the maximum.In other words, you can choose no more than a half (rounded down) of elements in each row, you have to find the maximum sum of these elements divisible by $$$k$$$.Note that you can choose zero elements (and the sum of such set is $$$0$$$).", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n, m, k \\le 70$$$) \u2014 the number of rows in the matrix, the number of columns in the matrix and the value of $$$k$$$. The next $$$n$$$ lines contain $$$m$$$ elements each, where the $$$j$$$-th element of the $$$i$$$-th row is $$$a_{i, j}$$$ ($$$1 \\le a_{i, j} \\le 70$$$).", "output_spec": "Print one integer \u2014 the maximum sum divisible by $$$k$$$ you can obtain.", "sample_inputs": ["3 4 3\n1 2 3 4\n5 2 2 2\n7 1 1 4", "5 5 4\n1 2 4 2 1\n3 5 1 2 4\n1 5 7 1 2\n3 8 7 1 2\n8 4 7 1 6"], "sample_outputs": ["24", "56"], "notes": "NoteIn the first example, the optimal answer is $$$2$$$ and $$$4$$$ in the first row, $$$5$$$ and $$$2$$$ in the second row and $$$7$$$ and $$$4$$$ in the third row. The total sum is $$$2 + 4 + 5 + 2 + 7 + 4 = 24$$$."}, "positive_code": [{"source_code": "//package codeforces.contests._1433\n\nobject ZeroRemainderSum {\n def main(args: Array[String]): Unit = {\n val Array(n, m, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val matrix = {\n val matrix = new Array[Array[Int]](n)\n (0 until n).foreach(matrix(_) = io.StdIn.readLine.split(\" \").map(_.toInt))\n matrix\n }\n\n val dp = Array.fill(n + 1, m, m / 2 + 1, k)(Int.MinValue)\n\n dp(0)(0)(0)(0) = 0\n\n for {\n i <- 0 until n\n j <- 0 until m\n cM = ((m / 2) min (j + 1)) + 1\n c <- 0 until cM\n r <- 0 until k\n } {\n\n if (dp(i)(j)(c)(r) != Int.MinValue) {\n\n if (j < m - 1) {\n dp(i)(j + 1)(c)(r) = dp(i)(j + 1)(c)(r) max dp(i)(j)(c)(r)\n\n if (c + 1 < cM) {\n val rr = (r + matrix(i)(j)) % k\n dp(i)(j + 1)(c + 1)(rr) = dp(i)(j + 1)(c + 1)(rr) max {\n dp(i)(j)(c)(r) + matrix(i)(j)\n }\n }\n } else { // next row\n dp(i + 1)(0)(0)(r) = dp(i + 1)(0)(0)(r) max dp(i)(j)(c)(r)\n\n val rr = (r + matrix(i)(j)) % k\n if (c + 1 < cM) {\n dp(i + 1)(0)(0)(rr) = dp(i + 1)(0)(0)(rr) max {\n dp(i)(j)(c)(r) + matrix(i)(j)\n }\n }\n }\n }\n }\n\n println(dp(n)(0)(0)(0) max 0)\n\n }\n}\n"}], "negative_code": [], "src_uid": "9b17b560c6b3700a6a387c693d71c5f9"} {"nl": {"description": "Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$2 \\cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the string. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.", "sample_inputs": ["5\n8\nabcaacab\n6\nxyzxyz\n4\nabba\n8\nrprarlap\n10\nkhyyhhyhky"], "sample_outputs": ["2\n-1\n0\n3\n2"], "notes": "NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome."}, "positive_code": [{"source_code": "object C extends App {\r\n\r\n def minimumNumberOfErasing(str: String): Option[Int] = {\r\n val size = str.size\r\n\r\n @annotation.tailrec\r\n def go(left: Int, right: Int, char: Char, count: Int = 0): Option[Int] =\r\n if (left >= right) Some(count)\r\n else\r\n (str(left), str(right)) match {\r\n case (leftChar, rightChar) if leftChar == rightChar => go(left + 1, right - 1, char, count)\r\n case (leftChar, _) if char == leftChar => go(left + 1, right, char, count + 1)\r\n case (_, rightChar) if char == rightChar => go(left, right - 1, char, count + 1)\r\n case _ => None\r\n }\r\n\r\n str.distinct.foldLeft[Option[Int]](None) { (countOpt, char) =>\r\n val candidateOpt = go(0, size - 1, char)\r\n candidateOpt.map { candidate => candidate min countOpt.getOrElse(candidate) }.orElse(countOpt)\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 s = nextLine()\r\n\r\n minimumNumberOfErasing(s) match {\r\n case Some(count) => out.println(count)\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}\r\n"}], "negative_code": [{"source_code": "object C extends App {\r\n\r\n def minimumNumberOfErasing(str: String): Option[Int] = {\r\n val size = str.size\r\n\r\n @annotation.tailrec\r\n def go(left: Int, right: Int, countOpt: Option[Int] = Some(0), erasedOpt: Option[Char] = None): Option[Int] =\r\n if (left >= right) countOpt\r\n else {\r\n val char = str(left)\r\n\r\n str.lastIndexOf(char, right) match {\r\n case end if end <= left =>\r\n erasedOpt match {\r\n case Some(erased) if char != erased => None\r\n case _ => go(left + 1, right, countOpt.map(_ + 1), erasedOpt)\r\n }\r\n case end if end == right => go(left + 1, right - 1, countOpt, erasedOpt)\r\n case end =>\r\n @annotation.tailrec\r\n def inner(index: Int, countOpt: Option[Int], erasedOpt: Option[Char]): (Option[Int], Option[Char]) =\r\n if (index > right) (countOpt, erasedOpt)\r\n else\r\n erasedOpt match {\r\n case Some(erased) if erased != str(index) => (None, None)\r\n case _ => inner(index + 1, countOpt.map(_ + 1), Some(str(index)))\r\n }\r\n\r\n inner(end + 1, countOpt, erasedOpt) match {\r\n case (None, _) => go(left + 1, right, countOpt.map(_ + 1), Some(char))\r\n case (count, erased) => go(left + 1, end - 1, count, erased)\r\n }\r\n }\r\n }\r\n\r\n go(0, size - 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 s = nextLine()\r\n\r\n minimumNumberOfErasing(s) match {\r\n case Some(count) => out.println(count)\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}\r\n"}, {"source_code": "object C extends App {\r\n\r\n def minimumNumberOfErasing(str: String): Option[Int] = {\r\n val size = str.size\r\n\r\n @annotation.tailrec\r\n def go(left: Int, right: Int, countOpt: Option[Int] = Some(0), erasedOpt: Option[Char] = None): Option[Int] =\r\n if (left >= right) countOpt\r\n else {\r\n val char = str(left)\r\n\r\n str.lastIndexOf(char, right) match {\r\n case end if end <= left =>\r\n erasedOpt match {\r\n case Some(erased) if char != erased => None\r\n case _ => go(left + 1, right, countOpt.map(_ + 1), erasedOpt)\r\n }\r\n case end if end == right => go(left + 1, right - 1, countOpt, erasedOpt)\r\n case end =>\r\n @annotation.tailrec\r\n def inner(index: Int, countOpt: Option[Int], erasedOpt: Option[Char]): (Option[Int], Option[Char]) =\r\n if (index > right) (countOpt, erasedOpt)\r\n else\r\n erasedOpt match {\r\n case Some(erased) if erased != str(index) => (None, None)\r\n case _ => inner(index + 1, countOpt.map(_ + 1), Some(str(index)))\r\n }\r\n\r\n inner(end + 1, countOpt, erasedOpt) match {\r\n case (None, _) => go(left + 1, right, countOpt.map(_ + 1), Some(char))\r\n case (count, erased) => go(left + 1, end - 1, count, erased)\r\n }\r\n }\r\n }\r\n\r\n println()\r\n\r\n go(0, size - 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 s = nextLine()\r\n\r\n out.println(minimumNumberOfErasing(s))\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": "8ca8317ce3f678c99dc746cb9b058993"} {"nl": {"description": "Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet: if the letter number is single-digit number (less than $$$10$$$), then just writes it out; if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows: 'c'\u00a0\u2014 is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3); 'o'\u00a0\u2014 is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150); 'd'\u00a0\u2014 is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504); 'e'\u00a0\u2014 is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).", "input_spec": "The first line of the input contains an integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) \u2014 the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ \u2014 the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.", "output_spec": "For each test case output the required string $$$s$$$ \u2014 the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.", "sample_inputs": ["9\n\n6\n\n315045\n\n4\n\n1100\n\n7\n\n1213121\n\n6\n\n120120\n\n18\n\n315045615018035190\n\n7\n\n1111110\n\n7\n\n1111100\n\n5\n\n11111\n\n4\n\n2606"], "sample_outputs": ["code\naj\nabacaba\nll\ncodeforces\naaaak\naaaaj\naaaaa\nzf"], "notes": "NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120."}, "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"}, {"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"}], "negative_code": [], "src_uid": "43081557fe2fbac39dd9b72b137b8fb0"} {"nl": {"description": "You have a statistic of price changes for one product represented as an array of $$$n$$$ positive integers $$$p_0, p_1, \\dots, p_{n - 1}$$$, where $$$p_0$$$ is the initial price of the product and $$$p_i$$$ is how the price was increased during the $$$i$$$-th month.Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $$$p_i$$$ to the price at the start of this month $$$(p_0 + p_1 + \\dots + p_{i - 1})$$$.Your boss said you clearly that the inflation coefficients must not exceed $$$k$$$ %, so you decided to increase some values $$$p_i$$$ in such a way, that all $$$p_i$$$ remain integers and the inflation coefficients for each month don't exceed $$$k$$$ %.You know, that the bigger changes\u00a0\u2014 the more obvious cheating. That's why you need to minimize the total sum of changes.What's the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 100$$$; $$$1 \\le k \\le 100$$$)\u00a0\u2014 the length of array $$$p$$$ and coefficient $$$k$$$. The second line of each test case contains $$$n$$$ integers $$$p_0, p_1, \\dots, p_{n - 1}$$$ ($$$1 \\le p_i \\le 10^9$$$)\u00a0\u2014 the array $$$p$$$.", "output_spec": "For each test case, print the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %.", "sample_inputs": ["2\n4 1\n20100 1 202 202\n3 100\n1 1 1"], "sample_outputs": ["99\n0"], "notes": "NoteIn the first test case, you can, for example, increase $$$p_0$$$ by $$$50$$$ and $$$p_1$$$ by $$$49$$$ and get array $$$[20150, 50, 202, 202]$$$. Then you get the next inflation coefficients: $$$\\frac{50}{20150} \\le \\frac{1}{100}$$$; $$$\\frac{202}{20150 + 50} \\le \\frac{1}{100}$$$; $$$\\frac{202}{20200 + 202} \\le \\frac{1}{100}$$$; In the second test case, you don't need to modify array $$$p$$$, since the inflation coefficients are already good: $$$\\frac{1}{1} \\le \\frac{100}{100}$$$; $$$\\frac{1}{1 + 1} \\le \\frac{100}{100}$$$; "}, "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 = nextInt\n val ps = nextLongs(n)\n\n def can(pd: Long): Boolean = {\n var pPrev = ps(0) + pd\n var ok = true\n for (i <- 1 until n) {\n val p = ps(i)\n// println(pPrev, p, pPrev * (100 + k), (pPrev + p) * 100)\n if (pPrev * (100 + k) < (pPrev + p) * 100) {\n ok = false\n }\n pPrev += p\n }\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(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val sum = binSearch(0, Long.MaxValue / 1000)\n\n out.println(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": "53975eea2503bb47bfd0a5119406aea3"} {"nl": {"description": "The company $$$X$$$ has $$$n$$$ employees numbered from $$$1$$$ through $$$n$$$. Each employee $$$u$$$ has a direct boss $$$p_u$$$ ($$$1 \\le p_u \\le n$$$), except for the employee $$$1$$$ who has no boss. It is guaranteed, that values $$$p_i$$$ form a tree. Employee $$$u$$$ is said to be in charge of employee $$$v$$$ if $$$u$$$ is the direct boss of $$$v$$$ or there is an employee $$$w$$$ such that $$$w$$$ is in charge of $$$v$$$ and $$$u$$$ is the direct boss of $$$w$$$. Also, any employee is considered to be in charge of himself.In addition, for each employee $$$u$$$ we define it's level $$$lv(u)$$$ as follow: $$$lv(1)=0$$$ $$$lv(u)=lv(p_u)+1$$$ for $$$u \\neq 1$$$ In the near future, there are $$$q$$$ possible plans for the company to operate. The $$$i$$$-th plan consists of two integers $$$l_i$$$ and $$$r_i$$$, meaning that all the employees in the range $$$[l_i, r_i]$$$, and only they, are involved in this plan. To operate the plan smoothly, there must be a project manager who is an employee in charge of all the involved employees. To be precise, if an employee $$$u$$$ is chosen as the project manager for the $$$i$$$-th plan then for every employee $$$v \\in [l_i, r_i]$$$, $$$u$$$ must be in charge of $$$v$$$. Note, that $$$u$$$ is not necessary in the range $$$[l_i, r_i]$$$. Also, $$$u$$$ is always chosen in such a way that $$$lv(u)$$$ is as large as possible (the higher the level is, the lower the salary that the company has to pay the employee).Before any plan is operated, the company has JATC take a look at their plans. After a glance, he tells the company that for every plan, it's possible to reduce the number of the involved employees exactly by one without affecting the plan. Being greedy, the company asks JATC which employee they should kick out of the plan so that the level of the project manager required is as large as possible. JATC has already figured out the answer and challenges you to do the same.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\le n \\le 100\\,000$$$, $$$1 \\le q \\le 100\\,000$$$)\u00a0\u2014 the number of employees and the number of plans, respectively. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$) meaning $$$p_i$$$ is the direct boss of employee $$$i$$$. It is guaranteed, that values $$$p_i$$$ form a directed tree with the root of $$$1$$$. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i<r_i \\le n$$$)\u00a0\u2014 the range of the employees, involved in the corresponding plan.", "output_spec": "Print $$$q$$$ lines, each containing two integers\u00a0\u2014 the number of the employee which should be kicked from the corresponding plan and the maximum possible level of the project manager in that case. If there are more than one way to choose that employee, print any of them.", "sample_inputs": ["11 5\n1 1 3 3 3 4 2 7 7 6\n4 6\n4 8\n1 11\n9 11\n8 11"], "sample_outputs": ["4 1\n8 1\n1 0\n11 3\n8 1"], "notes": "NoteIn the example: In the first query, we can choose whether $$$4$$$ or $$$5$$$ or $$$6$$$ and the project manager will be $$$3$$$.In the second query, if we choose any employee other than the employee $$$8$$$, the project manager will be $$$1$$$. If we choose $$$8$$$, the project manager will be $$$3$$$. Since $$$lv(3)=1 > lv(1)=0$$$, choosing $$$8$$$ is the best strategy.In the third query, no matter how we choose the employee, the project manager will always be $$$1$$$.In the fourth query, if we choose $$$9$$$ or $$$10$$$ then the project manager will be $$$3$$$. If we choose $$$11$$$ then the project manager will be $$$7$$$. Since $$$lv(7)=3>lv(3)=1$$$, we choose $$$11$$$ as the answer."}, "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\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 = packUGraph(N, from, to)\n\n val NN = N\n val K = 20\n\n val (depth, parent, _) = traceBfs(g)\n parent(0) = 0\n val anc = Array.ofDim[Int](K, NN)\n rep(NN) { i =>\n anc(0)(i) = parent(i)\n }\n rep(anc.length - 1, 1) { k =>\n rep(NN) { i =>\n anc(k)(i) = anc(k-1)(anc(k-1)(i))\n }\n }\n\n def getParent(v: Int, d: Int): Int = {\n def step(v0: Int, k: Int, d0: Int): Int = {\n if (d0 == 0) v0\n else if (d0 % 2 == 1) step(anc(k)(v0), k + 1, d0 / 2)\n else step(v0, k + 1, d0 / 2)\n }\n\n step(v, 0, d)\n }\n\n val INF = Integer.MAX_VALUE\n def lca(v: Int, u: Int): Int = {\n if (v == INF) u\n else if (u == INF) v\n else {\n def step(v0: Int, u0: Int, k: Int): Int = {\n if (k == -1) {\n anc(0)(v0) // \uff11\u3064\u524d\u306e\u5b50\u3092\u8fd4\u3057\u305f\u304b\u3063\u305f\u3089(v0, u0)\u3092\u8fd4\u3059\n } else if (anc(k)(v0) == anc(k)(u0)) {\n step(v0, u0, k - 1)\n } else {\n step(anc(k)(v0), anc(k)(u0), k - 1)\n }\n }\n\n val d = min(depth(v), depth(u))\n val v0 = getParent(v, depth(v) - d)\n val u0 = getParent(u, depth(u) - d)\n if (v0 == u0) v0 // \u3053\u306e\u6642\u70b9\u3067\u540c\u3058\u3060\u3063\u305f\u3089\u30c0\u30d6\u30ea\u30f3\u30b0\u3067\u8abf\u3079\u308b\u5fc5\u8981\u304c\u306a\u3044\n else step(v0, u0, anc.length - 1)\n }\n }\n\n // \u7bc4\u56f2lca\n val t1 = new SegmentTree(N, INF)(lca)\n\n // (\u5143\u306b\u306a\u308b\u30ce\u30fc\u30c9, lca)\n case class NeighbourLca(v: Int, lca: Int)\n // \u533a\u9593\u306e\u500b\u6570\u306fN-1\n val t2 = new SegmentTree(N - 1, NeighbourLca(INF, INF))({ (u, v) =>\n if (lca(u.lca, v.lca) == u.lca) u else v\n })\n rep(N) { i =>\n t1.update(i, i)\n }\n rep(N - 1) { i =>\n val lca0 = lca(i, i + 1)\n t2.update(i, NeighbourLca(i, lca0))\n }\n\n rep(Q) { _ =>\n val l, r = ni() - 1 // [l, r] \u6700\u4f4e\uff12\u8981\u7d20\u3042\u308b\n\n // del\u3092\u524a\u9664\u3057\u305f\u5834\u5408\u306e\u533a\u9593\u5168\u4f53\u3067\u306eLCA\u306elevel\u3092\u8fd4\u3059\n def tryIt(del: Int): Int = {\n val node = if (del == l) t1.query(l + 1, r + 1)\n else if (del == r) t1.query(l, r)\n else lca(t1.query(l, del), t1.query(del + 1, r + 1))\n depth(node)\n }\n\n val ms = t2.query(l, r) // \u8981\u7d20[l, r] => \u533a\u9593\u3067\u306f[l, r-1]\n val lvl1 = tryIt(ms.v) // \u533a\u9593\u306e\u5de6\u306e\u8981\u7d20\u3092\u524a\u9664\n val lvl2 = tryIt(ms.v + 1) // \u533a\u9593\u306e\u53f3\u3092\u524a\u9664\n if (lvl1 > lvl2) {\n out.println(s\"${ms.v + 1} $lvl1\")\n } else {\n out.println(s\"${ms.v + 2} $lvl2\")\n }\n }\n }\n\n /**\n * @param n \u30ce\u30fc\u30c9\u6570\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 /**\n * @param n \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n */\n class SegmentTree[A: ClassTag](n: Int, zero: A)(f: (A, A) => A) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val dat: Array[A] = Array.fill(2 * N - 1)(zero)\n\n def update(i: Int, a: A): Unit = {\n assert(i < n)\n var k = N - 1 + i\n dat(k) = a\n while(k > 0) {\n k = (k - 1) / 2\n dat(k) = f(dat(2 * k + 1), dat(2 * k + 2))\n }\n }\n\n /**\n * [a, b)\n */\n def query(a: Int, b: Int): A = {\n assert(a <= n && b <= n && a <= b)\n\n def step(k: Int, l: Int, r: Int): A = {\n if (r <= a || b <= l) {\n zero\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 f(vl, vr)\n }\n }\n\n if (a == b) zero\n else 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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n rep(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n rep(n) { i =>\n rep(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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": "256cb0e4fc10187ad6888d0d2d2990bf"} {"nl": {"description": "Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \\le i \\le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the number of shovels and the number of types of packages.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer is a positive integer\u00a0\u2014 the minimum number of packages.", "sample_inputs": ["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"], "sample_outputs": ["2\n8\n1\n999999733\n1"], "notes": "NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels\u00a0\u2014 $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels."}, "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"}, {"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"}], "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"} {"nl": {"description": "There are $$$n$$$ houses in a row. They are numbered from $$$1$$$ to $$$n$$$ in order from left to right. Initially you are in the house $$$1$$$.You have to perform $$$k$$$ moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house $$$x$$$ to the house $$$y$$$, the total distance you walked increases by $$$|x-y|$$$ units of distance, where $$$|a|$$$ is the absolute value of $$$a$$$. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).Your goal is to walk exactly $$$s$$$ units of distance in total.If it is impossible, print \"NO\". Otherwise print \"YES\" and any of the ways to do that. Remember that you should do exactly $$$k$$$ moves.", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$k$$$, $$$s$$$ ($$$2 \\le n \\le 10^9$$$, $$$1 \\le k \\le 2 \\cdot 10^5$$$, $$$1 \\le s \\le 10^{18}$$$) \u2014 the number of houses, the number of moves and the total distance you want to walk.", "output_spec": "If you cannot perform $$$k$$$ moves with total walking distance equal to $$$s$$$, print \"NO\". Otherwise print \"YES\" on the first line and then print exactly $$$k$$$ integers $$$h_i$$$ ($$$1 \\le h_i \\le n$$$) on the second line, where $$$h_i$$$ is the house you visit on the $$$i$$$-th move. For each $$$j$$$ from $$$1$$$ to $$$k-1$$$ the following condition should be satisfied: $$$h_j \\ne h_{j + 1}$$$. Also $$$h_1 \\ne 1$$$ should be satisfied.", "sample_inputs": ["10 2 15", "10 9 45", "10 9 81", "10 9 82"], "sample_outputs": ["YES\n10 4", "YES\n10 1 10 1 2 1 2 1 6", "YES\n10 1 10 1 10 1 10 1 10", "NO"], "notes": null}, "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 = 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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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}"}], "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..There is a glob pattern in the statements (a string consisting of lowercase English letters, characters \"?\" and \"*\"). It is known that character \"*\" occurs no more than once in the pattern.Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.A pattern matches a string if it is possible to replace each character \"?\" with one good lowercase English letter, and the character \"*\" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.The good letters are given to Petya. All the others are bad.", "input_spec": "The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad. The second line contains the pattern\u00a0\u2014 a string s of lowercase English letters, characters \"?\" and \"*\" (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105). It is guaranteed that character \"*\" occurs in s no more than once. The third line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of query strings. n lines follow, each of them contains single non-empty string consisting of lowercase English letters\u00a0\u2014 a query string. It is guaranteed that the total length of all query strings is not greater than 105.", "output_spec": "Print n lines: in the i-th of them print \"YES\" if the pattern matches the i-th query string, and \"NO\" otherwise. You can choose the case (lower or upper) for each letter arbitrary.", "sample_inputs": ["ab\na?a\n2\naaa\naab", "abc\na?a?a*\n4\nabacaba\nabaca\napapa\naaaaax"], "sample_outputs": ["YES\nNO", "NO\nYES\nNO\nYES"], "notes": "NoteIn the first example we can replace \"?\" with good letters \"a\" and \"b\", so we can see that the answer for the first query is \"YES\", and the answer for the second query is \"NO\", because we can't match the third letter.Explanation of the second example. The first query: \"NO\", because character \"*\" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string \"ba\", in which both letters are good. The second query: \"YES\", because characters \"?\" can be replaced with corresponding good letters, and character \"*\" can be replaced with empty string, and the strings will coincide. The third query: \"NO\", because characters \"?\" can't be replaced with bad letters. The fourth query: \"YES\", because characters \"?\" can be replaced with good letters \"a\", and character \"*\" can be replaced with a string of bad letters \"x\". "}, "positive_code": [{"source_code": "object P832B {\n\n // Do NOT use Regex, it takes a lot of time to compile a long pattern\n\n def testGoods(s: Seq[Char], p: Seq[Char], goods: Set[Char]): Boolean = {\n if (s.length != p.length) false\n else !(s zip p).exists {\n case (act, '?') => !goods.contains(act)\n case (act, exp) => act != exp\n }\n }\n\n\n def testBads(s: Seq[Char], goods: Set[Char]): Boolean = {\n !s.exists(goods.contains)\n }\n\n def tester(pattern: String): (String, Set[Char]) => Boolean = pattern.indexOf('*') match {\n case -1 => (line, goods) => testGoods(line, pattern, goods)\n case i => (line, goods) => {\n val j = i + 1 + line.length - pattern.length\n if (i > j) false else testBads(line.substring(i, j), goods) &&\n testGoods(line.substring(0, i), pattern.substring(0, i), goods) &&\n testGoods(line.substring(j), pattern.substring(i+1), goods)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val goods = in.nextLine().toSet\n val test = tester(in.nextLine())\n in.nextLine() // skip n\n for (line <- in) {\n println(if (test(line, goods)) \"YES\" else \"NO\")\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\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"}], "negative_code": [{"source_code": "import scala.io.BufferedSource\nimport scala.util.matching.Regex\n\nobject P832B {\n\n def solve1(p: String, in: Scanner) = { // TLE\n for (line <- in) {\n println(if (line.matches(p)) \"YES\" else \"NO\")\n }\n }\n\n def solve2(p: Regex, in: Scanner) = { // still TLE\n for (line <- in) {\n println(line match {\n case p() => \"YES\"\n case _ => \"NO\"\n })\n }\n }\n\n def testGoods(s: Seq[Char], p: Seq[Char], goods: Set[Char]): Boolean = {\n if (s.length < p.length) false\n else !(s zip p).exists {\n case (act, '?') => !goods.contains(act)\n case (act, exp) => act != exp\n }\n }\n\n\n def testBads(s: Seq[Char], goods: Set[Char]): Boolean = {\n !s.exists(goods.contains)\n }\n\n def tester(pattern: String): (String, Set[Char]) => Boolean = pattern.indexOf('*') match {\n case -1 => (line, goods) => testGoods(line, pattern, goods)\n case i => (line, goods) => {\n val j = i + 1 + line.length - pattern.length\n if (i > j) false else testBads(line.substring(i, j), goods) &&\n testGoods(line.substring(0, i), pattern.substring(0, i), goods) &&\n testGoods(line.substring(j), pattern.substring(i+1), goods)\n }\n }\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(new BufferedSource(System.in).mkString)\n val goods = in.nextLine().toSet\n val test = tester(in.nextLine())\n in.nextLine() // skip n\n for (line <- in) {\n println(if (test(line, goods)) \"YES\" else \"NO\")\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\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": "object P832B {\n\n def main(args: Array[String]): Unit = {\n val in = new Scanner(System.in)\n val goods = in.nextLine()\n val pattern = in.nextLine().replaceAll(\"\\\\?\", s\"[$goods]\")\n .replaceAll(\"\\\\*\", s\"[^$goods]*\")\n in.nextLine() // skip n\n for (line <- in) {\n println(line, pattern)\n println(if (line.matches(pattern)) \"YES\" else \"NO\")\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\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"}], "src_uid": "c6633581d7424d670eaa0f8a5c8cc366"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print \"NO\". Otherwise print \"YES\" and any coloring (i.e. numbers $$$c_1, c_2, \\dots c_n$$$, where $$$1 \\le c_i \\le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 5000$$$) \u2014 the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 5000$$$) \u2014 elements of the array $$$a$$$.", "output_spec": "If there is no answer, print \"NO\". Otherwise print \"YES\" and any coloring (i.e. numbers $$$c_1, c_2, \\dots c_n$$$, where $$$1 \\le c_i \\le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.", "sample_inputs": ["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"], "sample_outputs": ["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"], "notes": "NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples."}, "positive_code": [{"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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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}"}], "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"} {"nl": {"description": "In the $$$2022$$$ year, Mike found two binary integers $$$a$$$ and $$$b$$$ of length $$$n$$$ (both of them are written only by digits $$$0$$$ and $$$1$$$) that can have leading zeroes. In order not to forget them, he wanted to construct integer $$$d$$$ in the following way: he creates an integer $$$c$$$ as a result of bitwise summing of $$$a$$$ and $$$b$$$ without transferring carry, so $$$c$$$ may have one or more $$$2$$$-s. For example, the result of bitwise summing of $$$0110$$$ and $$$1101$$$ is $$$1211$$$ or the sum of $$$011000$$$ and $$$011000$$$ is $$$022000$$$; after that Mike replaces equal consecutive digits in $$$c$$$ by one digit, thus getting $$$d$$$. In the cases above after this operation, $$$1211$$$ becomes $$$121$$$ and $$$022000$$$ becomes $$$020$$$ (so, $$$d$$$ won't have equal consecutive digits). Unfortunately, Mike lost integer $$$a$$$ before he could calculate $$$d$$$ himself. Now, to cheer him up, you want to find any binary integer $$$a$$$ of length $$$n$$$ such that $$$d$$$ will be maximum possible as integer.Maximum possible as integer means that $$$102 > 21$$$, $$$012 < 101$$$, $$$021 = 21$$$ and so on.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the length of $$$a$$$ and $$$b$$$. The second line of each test case contains binary integer $$$b$$$ of length $$$n$$$. The integer $$$b$$$ consists only of digits $$$0$$$ and $$$1$$$. It is guaranteed that the total sum of $$$n$$$ over all $$$t$$$ test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case output one binary integer $$$a$$$ of length $$$n$$$. Note, that $$$a$$$ or $$$b$$$ may have leading zeroes but must have the same length $$$n$$$.", "sample_inputs": ["5\n1\n0\n3\n011\n3\n110\n6\n111000\n6\n001011"], "sample_outputs": ["1\n110\n100\n101101\n101110"], "notes": "NoteIn the first test case, $$$b = 0$$$ and choosing $$$a = 1$$$ gives $$$d = 1$$$ as a result.In the second test case, $$$b = 011$$$ so: if you choose $$$a = 000$$$, $$$c$$$ will be equal to $$$011$$$, so $$$d = 01$$$; if you choose $$$a = 111$$$, $$$c$$$ will be equal to $$$122$$$, so $$$d = 12$$$; if you choose $$$a = 010$$$, you'll get $$$d = 021$$$. If you select $$$a = 110$$$, you'll get $$$d = 121$$$. We can show that answer $$$a = 110$$$ is optimal and $$$d = 121$$$ is maximum possible.In the third test case, $$$b = 110$$$. If you choose $$$a = 100$$$, you'll get $$$d = 210$$$ and it's the maximum possible $$$d$$$.In the fourth test case, $$$b = 111000$$$. If you choose $$$a = 101101$$$, you'll get $$$d = 212101$$$ and it's maximum possible $$$d$$$.In the fifth test case, $$$b = 001011$$$. If you choose $$$a = 101110$$$, you'll get $$$d = 102121$$$ and it's maximum possible $$$d$$$."}, "positive_code": [{"source_code": "object Hemlo {\r\n import scala.io.{StdIn => in}\r\n def main(args: Array[String]): Unit = {\r\n var t: Int = in.readInt()\r\n while (t > 0) {\r\n val n: Int = in.readInt()\r\n val s: String = in.readLine()\r\n var prev: Int = 0\r\n for (i <- 0 until n) {\r\n val current: Int = s(i).toInt - 48\r\n // make 2\r\n if (prev != 2 && current == 1) {\r\n print(1)\r\n prev = 2\r\n }\r\n // make 1\r\n else if (prev != 1) {\r\n if (current == 0)\r\n print(1)\r\n else print(0)\r\n prev = 1\r\n }\r\n // make 0\r\n else {\r\n print(0)\r\n prev = 0\r\n }\r\n }\r\n println()\r\n t -= 1\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "e27620d3a43ab42edf930b37ce214c9e"} {"nl": {"description": "You are given an array $$$a[0 \\ldots n-1]$$$ of length $$$n$$$ which consists of non-negative integers. Note that array indices start from zero.An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $$$i$$$ ($$$0 \\le i \\le n - 1$$$) the equality $$$i \\bmod 2 = a[i] \\bmod 2$$$ holds, where $$$x \\bmod 2$$$ is the remainder of dividing $$$x$$$ by 2.For example, the arrays [$$$0, 5, 2, 1$$$] and [$$$0, 17, 0, 3$$$] are good, and the array [$$$2, 4, 6, 7$$$] is bad, because for $$$i=1$$$, the parities of $$$i$$$ and $$$a[i]$$$ are different: $$$i \\bmod 2 = 1 \\bmod 2 = 1$$$, but $$$a[i] \\bmod 2 = 4 \\bmod 2 = 0$$$.In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).Find the minimum number of moves in which you can make the array $$$a$$$ good, or say that this is not possible.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \\le n \\le 40$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_0, a_1, \\ldots, a_{n-1}$$$ ($$$0 \\le a_i \\le 1000$$$)\u00a0\u2014 the initial array.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimum number of moves to make the given array $$$a$$$ good, or -1 if this is not possible.", "sample_inputs": ["4\n4\n3 2 7 6\n3\n3 2 6\n1\n7\n7\n4 9 2 1 18 3 0"], "sample_outputs": ["2\n1\n-1\n0"], "notes": "NoteIn the first test case, in the first move, you can swap the elements with indices $$$0$$$ and $$$1$$$, and in the second move, you can swap the elements with indices $$$2$$$ and $$$3$$$.In the second test case, in the first move, you need to swap the elements with indices $$$0$$$ and $$$1$$$.In the third test case, you cannot make the array good."}, "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 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"}, {"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"} {"nl": {"description": "A string is called beautiful if no two consecutive characters are equal. For example, \"ababcb\", \"a\" and \"abab\" are beautiful strings, while \"aaaaaa\", \"abaa\" and \"bb\" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \\neq s_{i+1}$$$ should be satisfied for all $$$1 \\leq i \\leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.", "input_spec": "The first line contains positive integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print \"-1\" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them. ", "sample_inputs": ["3\na???cb\na??bbc\na?b?c"], "sample_outputs": ["ababcb\n-1\nacbac"], "notes": "NoteIn the first test case, all possible correct answers are \"ababcb\", \"abcacb\", \"abcbcb\", \"acabcb\" and \"acbacb\". The two answers \"abcbab\" and \"abaabc\" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is \"acbac\"."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y\u2009\u2264\u20092\u00b7x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of measurements Vasya made. The second line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u20095000) \u2014 the results of the measurements. The numbers on the second line are separated by single spaces.", "output_spec": "Print a single integer \u2014 the minimum number of results Vasya will have to remove.", "sample_inputs": ["6\n4 5 3 8 3 7", "4\n4 3 2 4"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4."}, "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 val n=in.nextLine.toInt\n val a=in.nextLine.split(\" \").map(_.toInt)\n\n val dp=new Array[Int](5001)\n\ta.foreach{i=> dp(i)+=1}\n\tvar min=Int.MaxValue\n\t1 to 5000 foreach{i=>\n\t\tvar sum=0\n\t\t1 to 5000 foreach{j=>\n\t\t\tif(j2*i) sum+=dp(j)\n\t\t}\n\t\tmin=Math.min(min,sum)\n\t}\n\n\tout.println(min)\n out.close\n}\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 val n=in.nextLine.toInt\n val a=in.nextLine.split(\" \").map(_.toInt)\n\n val (min,max)=(a.min,a.max)\n out.println(math.min(a.count(_*22*min)))\n out.close\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 val n=in.nextInt\n val a=in.next.split(\" \").map(_.toInt)\n\n val (min,max)=(a.min,a.max)\n out.println(math.min(a.count(_*22*min)))\n out.close\n}\n\n"}], "src_uid": "80cf3ea119fd398e8f003d22a76895a7"} {"nl": {"description": "Timur has a stairway with $$$n$$$ steps. The $$$i$$$-th step is $$$a_i$$$ meters higher than its predecessor. The first step is $$$a_1$$$ meters higher than the ground, and the ground starts at $$$0$$$ meters. The stairs for the first test case. Timur has $$$q$$$ questions, each denoted by an integer $$$k_1, \\dots, k_q$$$. For each question $$$k_i$$$, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length $$$k_i$$$. Timur can only climb the $$$j$$$-th step if his legs are of length at least $$$a_j$$$. In other words, $$$k_i \\geq a_j$$$ for each step $$$j$$$ climbed.Note that you should answer each question independently.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n, q$$$ ($$$1 \\leq n, q \\leq 2\\cdot10^5$$$)\u00a0\u2014 the number of steps and the number of questions, respectively. The second line of each test case contains $$$n$$$ integers ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the height of the steps. The third line of each test case contains $$$q$$$ integers ($$$0 \\leq k_i \\leq 10^9$$$)\u00a0\u2014 the numbers for each question. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2\\cdot10^5$$$, and the sum of $$$q$$$ does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each test case, output a single line containing $$$q$$$ integers, the answer for each question. Please note, that the answer for some questions won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).", "sample_inputs": ["3\n\n4 5\n\n1 2 1 5\n\n1 2 4 9 10\n\n2 2\n\n1 1\n\n0 1\n\n3 1\n\n1000000000 1000000000 1000000000\n\n1000000000"], "sample_outputs": ["1 4 4 9 9 \n0 2 \n3000000000"], "notes": "NoteConsider the first test case, pictured in the statement. If Timur's legs have length $$$1$$$, then he can only climb stair $$$1$$$, so the highest he can reach is $$$1$$$ meter. If Timur's legs have length $$$2$$$ or $$$4$$$, then he can only climb stairs $$$1$$$, $$$2$$$, and $$$3$$$, so the highest he can reach is $$$1+2+1=4$$$ meters. If Timur's legs have length $$$9$$$ or $$$10$$$, then he can climb the whole staircase, so the highest he can reach is $$$1+2+1+5=9$$$ meters. In the first question of the second test case, Timur has no legs, so he cannot go up even a single step. :("}, "positive_code": [{"source_code": "object Scuza {\r\n\r\n def upperBound(lst: Array[Long], x: Long): Int = {\r\n def upperBoundHelp (lst: Array[Long], x: Long, begin: Int, end: Int): Int = {\r\n // printf(\"%d %d %d\\n\", x, begin, end)\r\n if (begin == end) return begin\r\n if (lst(begin) > x) return begin\r\n var mid = (end-begin+1)/2+begin\r\n // printf (\"!%d %d %d\\n\", mid, lst(mid), x)\r\n if (lst(mid)<=x) upperBoundHelp(lst, x, mid+1, end)\r\n else upperBoundHelp(lst, x, begin+1, mid)\r\n }\r\n upperBoundHelp(lst, x, 0, lst.length-1)\r\n }\r\n\r\n def solve_test() = {\r\n val Array(n, q) = scala.io.StdIn.readLine().split(' ').map(_.toInt)\r\n var steps = scala.io.StdIn.readLine().split(' ').map(_.toLong) :+ 1000000010L\r\n var questions = scala.io.StdIn.readLine().split(' ').map(_.toLong)\r\n var steps_heights = steps.foldLeft(List(0L))((acc, x) => x.max(acc.head) :: acc).reverse.toArray\r\n var steps_sum = steps.foldLeft(List(0L))((acc, x) => (x + acc.head) :: acc).reverse.toArray\r\n // for (i <- steps_heights) printf (\"%d \", i)\r\n // printf (\"\\n\")\r\n var lst = questions.map(x => upperBound(steps_heights, x)).map(x => steps_sum(x-1))\r\n for (i <- lst) printf (\"%d \", i)\r\n printf (\"\\n\")\r\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": [], "src_uid": "d5f7228d8d674b8233937702ca044cb0"} {"nl": {"description": "JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into $$$n$$$ parts, places them on a row and numbers them from $$$1$$$ through $$$n$$$. For each part $$$i$$$, he defines the deliciousness of the part as $$$x_i \\in \\{0, 1\\}$$$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $$$i$$$-th part then his enjoyment of the Banh-mi will increase by $$$x_i$$$ and the deliciousness of all the remaining parts will also increase by $$$x_i$$$. The initial enjoyment of JATC is equal to $$$0$$$.For example, suppose the deliciousness of $$$3$$$ parts are $$$[0, 1, 0]$$$. If JATC eats the second part then his enjoyment will become $$$1$$$ and the deliciousness of remaining parts will become $$$[1, \\_, 1]$$$. Next, if he eats the first part then his enjoyment will become $$$2$$$ and the remaining parts will become $$$[\\_, \\_, 2]$$$. After eating the last part, JATC's enjoyment will become $$$4$$$.However, JATC doesn't want to eat all the parts but to save some for later. He gives you $$$q$$$ queries, each of them consisting of two integers $$$l_i$$$ and $$$r_i$$$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $$$[l_i, r_i]$$$ in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 100\\,000$$$). The second line contains a string of $$$n$$$ characters, each character is either '0' or '1'. The $$$i$$$-th character defines the deliciousness of the $$$i$$$-th part. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$)\u00a0\u2014 the segment of the corresponding query.", "output_spec": "Print $$$q$$$ lines, where $$$i$$$-th of them contains a single integer\u00a0\u2014 the answer to the $$$i$$$-th query modulo $$$10^9 + 7$$$.", "sample_inputs": ["4 2\n1011\n1 4\n3 4", "3 2\n111\n1 2\n3 3"], "sample_outputs": ["14\n3", "3\n1"], "notes": "NoteIn the first example: For query $$$1$$$: One of the best ways for JATC to eats those parts is in this order: $$$1$$$, $$$4$$$, $$$3$$$, $$$2$$$. For query $$$2$$$: Both $$$3$$$, $$$4$$$ and $$$4$$$, $$$3$$$ ordering give the same answer. In the second example, any order of eating parts leads to the same answer."}, "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 val pow2 = Array.ofDim[Long](100010)\n pow2(0) = 1\n rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)\n\n def solve(): Unit = {\n val N, Q = ni()\n val A = ns(N) map (_ - '0')\n val cum = cumSum(A)\n\n def calc(n: Int, ones: Int): Long = {\n if (ones == 0) 0\n else {\n val a = (MOD + pow2(ones) - 1) % MOD\n (a + a * (MOD + pow2(n - ones) - 1)) % MOD\n }\n }\n\n rep(Q) { _ =>\n val l, r = ni()\n val ans = calc(r - l + 1, cum(r) - cum(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[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": "88961744a28d7c890264a39a0a798708"} {"nl": {"description": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" \u2014 thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi,\u2009zi\u2009\u2264\u2009100).", "output_spec": "Print the word \"YES\" if the body is in equilibrium, or the word \"NO\" if it is not.", "sample_inputs": ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"], "sample_outputs": ["NO", "YES"], "notes": null}, "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": "\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}"}, {"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 \u00e8 0 \u00e8 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 \u00e8 0 \u00e8 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"} {"nl": {"description": "A sequence a0,\u2009a1,\u2009...,\u2009at\u2009-\u20091 is called increasing if ai\u2009-\u20091\u2009<\u2009ai for each i:\u20090\u2009<\u2009i\u2009<\u2009t.You are given a sequence b0,\u2009b1,\u2009...,\u2009bn\u2009-\u20091 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?", "input_spec": "The first line of the input contains two integer numbers n and d (2\u2009\u2264\u2009n\u2009\u2264\u20092000,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009106). The second line contains space separated sequence b0,\u2009b1,\u2009...,\u2009bn\u2009-\u20091 (1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "Output the minimal number of moves needed to make the sequence increasing.", "sample_inputs": ["4 2\n1 3 3 2"], "sample_outputs": ["3"], "notes": null}, "positive_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(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"}, {"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": "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}"}], "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"} {"nl": {"description": "Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.", "input_spec": "The first line contains two space-separated integers s and n (1\u2009\u2264\u2009s\u2009\u2264\u2009104, 1\u2009\u2264\u2009n\u2009\u2264\u2009103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1\u2009\u2264\u2009xi\u2009\u2264\u2009104, 0\u2009\u2264\u2009yi\u2009\u2264\u2009104) \u2014 the i-th dragon's strength and the bonus for defeating it.", "output_spec": "On a single line print \"YES\" (without the quotes), if Kirito can move on to the next level and print \"NO\" (without the quotes), if he can't.", "sample_inputs": ["2 2\n1 99\n100 0", "10 1\n100 100"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2\u2009+\u200999\u2009=\u2009101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win."}, "positive_code": [{"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"}, {"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": "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"}, {"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}"}], "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"} {"nl": {"description": "The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered. Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.", "input_spec": "The input data consists of three lines, each of them describes the position of one stadium. The lines have the format x,\u2009\u2009y,\u2009\u2009r, where (x,\u2009y) are the coordinates of the stadium's center (\u2009-\u2009\u2009103\u2009\u2264\u2009x,\u2009\u2009y\u2009\u2264\u2009103), and r (1\u2009\u2264\u2009r\u2009\u2009\u2264\u2009103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line. ", "output_spec": "Print the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.", "sample_inputs": ["0 0 10\n60 0 10\n30 30 10"], "sample_outputs": ["30.00000 0.00000"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "9829e1913e64072aadc9df5cddb63573"} {"nl": {"description": "Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.Consider the painting as a n\u2009\u00d7\u2009m rectangular grid. At the beginning an x\u2009\u00d7\u2009y rectangular brush is placed somewhere in the frame, with edges parallel to the frame, (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment.You have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush. ", "input_spec": "The first line of input contains two integers n and m, (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000), denoting the height and width of the painting. The next n lines contain the painting. Each line has m characters. Character 'X' denotes an altered cell, otherwise it's showed by '.'. There will be at least one altered cell in the painting.", "output_spec": "Print the minimum area of the brush in a line, if the painting is possibly altered, otherwise print \u2009-\u20091.", "sample_inputs": ["4 4\nXX..\nXX..\nXXXX\nXXXX", "4 4\n....\n.XXX\n.XXX\n....", "4 5\nXXXX.\nXXXX.\n.XX..\n.XX.."], "sample_outputs": ["4", "2", "-1"], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "e50551fbbd1b2d35da04d73202cc0191"} {"nl": {"description": "For a collection of integers $$$S$$$, define $$$\\operatorname{mex}(S)$$$ as the smallest non-negative integer that does not appear in $$$S$$$.NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.The universe can be represented as a 1-indexed array $$$a$$$ of length $$$n$$$. When NIT snaps his fingers, he does the following operation on the array: He selects positive integers $$$l$$$ and $$$r$$$ such that $$$1\\le l\\le r\\le n$$$. Let $$$w=\\operatorname{mex}(\\{a_l,a_{l+1},\\dots,a_r\\})$$$. Then, for all $$$l\\le i\\le r$$$, set $$$a_i$$$ to $$$w$$$. We say the universe is destroyed if and only if for all $$$1\\le i\\le n$$$, $$$a_i=0$$$ holds.Find the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to $$$0$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1\\le n\\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$0\\le a_i\\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, print one integer \u2014 the answer to the problem.", "sample_inputs": ["4\n\n4\n\n0 0 0 0\n\n5\n\n0 1 2 3 4\n\n7\n\n0 2 3 0 1 2 0\n\n1\n\n1000000000"], "sample_outputs": ["0\n1\n2\n1"], "notes": "NoteIn the first test case, we do $$$0$$$ operations and all elements in the array are already equal to $$$0$$$.In the second test case, one optimal way is doing the operation with $$$l=2$$$, $$$r=5$$$.In the third test case, one optimal way is doing the operation twice, respectively with $$$l=4$$$, $$$r=4$$$ and $$$l=2$$$, $$$r=6$$$.In the fourth test case, one optimal way is doing the operation with $$$l=1$$$, $$$r=1$$$."}, "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 var cou = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n val A = new Array[Long](n)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to n) {\r\n A(i - 1) = tokenizer.nextToken().toInt\r\n }\r\n val a = A.contains(0)\r\n val b = A.toList.count(_ > 0)\r\n if (b == 0) {\r\n println(0)\r\n }\r\n else if (!a){\r\n println(1)\r\n }\r\n else {\r\n cou = 0\r\n var s = 0\r\n for (i <- A) {\r\n if (i == 0) {\r\n s = 0\r\n }\r\n else {\r\n if (s == 0) {\r\n cou+=1\r\n }\r\n s+=1\r\n }\r\n }\r\n if (cou > 1){\r\n println(2)\r\n }\r\n else println(1)\r\n }\r\n }\r\n }\r\n}"}], "negative_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 var cou = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val n = tokenizer.nextToken().toInt\r\n val A = new Array[Long](n)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to n) {\r\n A(i-1) = tokenizer.nextToken().toInt\r\n }\r\n var s = 0\r\n for (i <- A) {\r\n if (i > 0) {\r\n if (s == 0)\r\n {\r\n cou+=1\r\n }\r\n s+=1\r\n }\r\n if (i == 0) {\r\n s = 0\r\n }\r\n }\r\n println(cou)\r\n }\r\n }\r\n}"}], "src_uid": "da3d1b2615d51044a7b43bd0ce939f4c"} {"nl": {"description": "You have a given picture with size $$$w \\times h$$$. Determine if the given picture has a single \"+\" shape or not. A \"+\" shape is described below: A \"+\" shape has one center nonempty cell. There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction. All other cells are empty. Find out if the given picture has single \"+\" shape.", "input_spec": "The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \\le h$$$, $$$w \\le 500$$$)\u00a0\u2014 the height and width of the picture. The $$$i$$$-th of the next $$$h$$$ lines contains string $$$s_{i}$$$ of length $$$w$$$ consisting \".\" and \"*\" where \".\" denotes the empty space and \"*\" denotes the non-empty space.", "output_spec": "If the given picture satisfies all conditions, print \"YES\". Otherwise, print \"NO\". You can output each letter in any case (upper or lower).", "sample_inputs": ["5 6\n......\n..*...\n.****.\n..*...\n..*...", "3 5\n..*..\n****.\n.*...", "7 7\n.......\n...*...\n..****.\n...*...\n...*...\n.......\n.*.....", "5 6\n..**..\n..**..\n******\n..**..\n..**..", "3 7\n.*...*.\n***.***\n.*...*.", "5 10\n..........\n..*.......\n.*.******.\n..*.......\n.........."], "sample_outputs": ["YES", "NO", "NO", "NO", "NO", "NO"], "notes": "NoteIn the first example, the given picture contains one \"+\".In the second example, two vertical branches are located in a different column.In the third example, there is a dot outside of the shape.In the fourth example, the width of the two vertical branches is $$$2$$$.In the fifth example, there are two shapes.In the sixth example, there is an empty space inside of the shape."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $$$i$$$ ($$$1 \\le i \\le n-1$$$), this condition must be satisfied: $$$$$$\\frac{\\max(a[i], a[i+1])}{\\min(a[i], a[i+1])} \\le 2$$$$$$For example, the arrays $$$[1, 2, 3, 4, 3]$$$, $$$[1, 1, 1]$$$ and $$$[5, 10]$$$ are dense. And the arrays $$$[5, 11]$$$, $$$[1, 4, 2]$$$, $$$[6, 6, 1]$$$ are not dense.You are given an array $$$a$$$ of $$$n$$$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.For example, if $$$a=[4,2,10,1]$$$, then the answer is $$$5$$$, and the array itself after inserting elements into it may look like this: $$$a=[4,2,\\underline{\\textbf{3}},\\underline{\\textbf{5}},10,\\underline{\\textbf{6}},\\underline{\\textbf{4}},\\underline{\\textbf{2}},1]$$$ (there are other ways to build such $$$a$$$).", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 50$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 50$$$).", "output_spec": "For each test case, output one integer\u00a0\u2014 the minimum number of numbers that must be added to the array to make it dense.", "sample_inputs": ["6\n4\n4 2 10 1\n2\n1 3\n2\n6 1\n3\n1 4 2\n5\n1 2 3 4 3\n12\n4 31 25 50 30 20 34 46 42 16 15 16"], "sample_outputs": ["5\n1\n2\n1\n0\n3"], "notes": "NoteThe first test case is explained in the statements.In the second test case, you can insert one element, $$$a=[1,\\underline{\\textbf{2}},3]$$$.In the third test case, you can insert two elements, $$$a=[6,\\underline{\\textbf{4}},\\underline{\\textbf{2}},1]$$$.In the fourth test case, you can insert one element, $$$a=[1,\\underline{\\textbf{2}},4,2]$$$.In the fifth test case, the array $$$a$$$ is already dense."}, "positive_code": [{"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 xs = readLine.split(' ').toList.map(x => x.toDouble)\r\n var sum = 0\r\n for ((x, i) <- xs.view.zipWithIndex) {\r\n if (i < xs.length - 1) {\r\n val y = xs(i + 1)\r\n val r = Math.max(x, y) / Math.min(x, y)\r\n if (r > 2) {\r\n val ratio = Math.log(r) / Math.log(2)\r\n val ratio_floor = (Math.log(r) / Math.log(2)).floor\r\n sum += (Math.log(r) / Math.log(2)).floor.toInt\r\n if ( ratio == ratio_floor) sum -= 1\r\n }\r\n }\r\n }\r\n println(sum)\r\n }\r\n}\r\n"}], "negative_code": [{"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 xs = readLine.split(' ').toList.map(x => x.toDouble)\r\n var sum = 0\r\n for ((x, i) <- xs.view.zipWithIndex) {\r\n if (i < xs.length - 1) {\r\n val y = xs(i + 1)\r\n val r = Math.max(x, y) / Math.min(x, y)\r\n if (r > 2) sum += (Math.log(r) / Math.log(2)).floor.toInt\r\n }\r\n }\r\n println(sum)\r\n }\r\n}\r\n"}], "src_uid": "a544dd9fd96379f66a960de6f973dd50"} {"nl": {"description": "Alice and Bob received $$$n$$$ candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of candies that Alice and Bob received. The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$\u00a0\u2014 the weights of the candies. The weight of each candy is either $$$1$$$ or $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output on a separate line: \"YES\", if all candies can be divided into two sets with the same weight; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["5\n2\n1 1\n2\n1 2\n4\n1 2 1 2\n3\n2 2 2\n3\n2 1 2"], "sample_outputs": ["YES\nNO\nYES\nNO\nNO"], "notes": "NoteIn the first test case, Alice and Bob can each take one candy, then both will have a total weight of $$$1$$$.In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight $$$1$$$ and one of weight $$$2$$$.In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair."}, "positive_code": [{"source_code": "import java.io._\r\nimport java.util.Scanner\r\n\r\nimport scala.collection.mutable.ArrayBuffer\r\n\r\nobject Codeforces extends App {\r\n var debug = false\r\n var sc = new Scanner(System.in)\r\n if (new java.io.File(\"input.txt\").exists) {\r\n debug = true\r\n sc = new Scanner(new FileInputStream(\"input.txt\"))\r\n }\r\n\r\n val testCount = sc.nextInt\r\n /* if (debug) {\r\n testCount = sc.nextInt();\r\n }*/\r\n\r\n var n = 0\r\n var A = ArrayBuffer[Int]()\r\n for (t <- 1 to testCount) {\r\n if (debug) {\r\n println(\"Test Case: \" + t)\r\n }\r\n A = ArrayBuffer[Int]()\r\n n = sc.nextInt()\r\n for (i <- 1 to n) {\r\n A += sc.nextInt()\r\n }\r\n val result = solveTestCase()\r\n println(result)\r\n }\r\n\r\n def solveTestCase(): Any = {\r\n var sum = 0\r\n var twos = 0\r\n for (x <- A) {\r\n sum += x\r\n if (x == 2) twos += 1\r\n }\r\n if (sum % 2 == 0) {\r\n if (n - twos > 0 || n % 2 == 0) {\r\n \"YES\"\r\n } else {\r\n \"NO\"\r\n }\r\n } else {\r\n \"NO\"\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "1d9d34dca11a787d6e2345494680e717"} {"nl": {"description": "Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.", "input_spec": "The first line contains three integers m, t, r (1\u2009\u2264\u2009m,\u2009t,\u2009r\u2009\u2264\u2009300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1\u2009\u2264\u2009i\u2009\u2264\u2009m, 1\u2009\u2264\u2009wi\u2009\u2264\u2009300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.", "output_spec": "If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print \u2009-\u20091.", "sample_inputs": ["1 8 3\n10", "2 10 1\n5 8", "1 1 3\n10"], "sample_outputs": ["3", "1", "-1"], "notes": "NoteAnya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is \u2009-\u20091, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes."}, "positive_code": [{"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"}, {"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": "\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"}], "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"} {"nl": {"description": "Luba needs your help again! Luba has n TV sets. She knows that i-th TV set will be working from moment of time li till moment ri, inclusive.Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at least one of TV sets is working won't decrease. Luba will be very upset if she has to switch off a non-redundant TV set.Help Luba by telling her the index of some redundant TV set. If there is no any, print -1.", "input_spec": "The first line contains one integer number n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of TV sets. Then n lines follow, each of them containing two integer numbers li,\u2009ri\u00a0(0\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) denoting the working time of i-th TV set.", "output_spec": "If there is no any redundant TV set, print -1. Otherwise print the index of any redundant TV set (TV sets are indexed from 1 to n). If there are multiple answers, print any of them.", "sample_inputs": ["3\n1 3\n4 6\n1 7", "2\n0 10\n0 10", "3\n1 2\n3 4\n6 8", "3\n1 2\n2 3\n3 4"], "sample_outputs": ["1", "1", "-1", "2"], "notes": "NoteConsider the first sample. Initially all integer moments of time such that at least one TV set is working are from the segment [1;7]. It's easy to see that this segment won't change if we switch off the first TV set (or the second one).Note that in the fourth sample you can switch off the second TV set, since even without it all integer moments such that any of the TV sets is working denote the segment [1;4]."}, "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"}, {"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"}], "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"} {"nl": {"description": "Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.", "input_spec": "The first line contains three integers n,\u2009m,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009105). Each of the next m lines contains three integers ui,\u2009vi,\u2009xi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n;\u00a0ui\u2009\u2260\u2009vi;\u00a01\u2009\u2264\u2009xi\u2009\u2264\u2009109). Each of the next k lines contains two integers si and yi (2\u2009\u2264\u2009si\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009yi\u2009\u2264\u2009109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.", "output_spec": "Output a single integer representing the maximum number of the train routes which can be closed.", "sample_inputs": ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"], "sample_outputs": ["2", "2"], "notes": null}, "positive_code": [{"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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$.Your task is to construct such a string $$$s$$$ of length $$$n$$$ that for each $$$i$$$ from $$$1$$$ to $$$k$$$ there is at least one $$$i$$$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of queries. The next $$$t$$$ lines are contain queries, one per line. The $$$i$$$-th line contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \\le n_i \\le 100, 1 \\le k_i \\le min(n_i, 26)$$$) \u2014 the length of the string in the $$$i$$$-th query and the number of characters in the $$$i$$$-th query.", "output_spec": "Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: any string $$$s_i$$$ satisfying the conditions in the problem statement with constraints from the $$$i$$$-th query.", "sample_inputs": ["3\n7 3\n4 4\n6 2"], "sample_outputs": ["cbcacab\nabcd\nbaabab"], "notes": "NoteIn the first example query the maximum possible minimal frequency is $$$2$$$, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: \"cbcabba\", \"ccbbaaa\" (any permutation of given answers is also correct).In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is $$$1$$$).In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is $$$3$$$)."}, "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, 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "While Duff was resting in the beach, she accidentally found a strange array b0,\u2009b1,\u2009...,\u2009bl\u2009-\u20091 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0,\u2009...,\u2009an\u2009-\u20091 that b can be build from a with formula: bi\u2009=\u2009ai mod n where a mod b denoted the remainder of dividing a by b. Duff is so curious, she wants to know the number of subsequences of b like bi1,\u2009bi2,\u2009...,\u2009bix (0\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ix\u2009<\u2009l), such that: 1\u2009\u2264\u2009x\u2009\u2264\u2009k For each 1\u2009\u2264\u2009j\u2009\u2264\u2009x\u2009-\u20091, For each 1\u2009\u2264\u2009j\u2009\u2264\u2009x\u2009-\u20091, bij\u2009\u2264\u2009bij\u2009+\u20091. i.e this subsequence is non-decreasing. Since this number can be very large, she want to know it modulo 109\u2009+\u20097.Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.", "input_spec": "The first line of input contains three integers, n,\u2009l and k (1\u2009\u2264\u2009n,\u2009k, n\u2009\u00d7\u2009k\u2009\u2264\u2009106 and 1\u2009\u2264\u2009l\u2009\u2264\u20091018). The second line contains n space separated integers, a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 (1\u2009\u2264\u2009ai\u2009\u2264\u2009109 for each 0\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091). ", "output_spec": "Print the answer modulo 1\u2009000\u2009000\u2009007 in one line.", "sample_inputs": ["3 5 3\n5 9 1", "5 10 3\n1 2 3 4 5"], "sample_outputs": ["10", "25"], "notes": "NoteIn the first sample case, . So all such sequences are: , , , , , , , , and ."}, "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.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"}, {"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"} {"nl": {"description": "Polycarpus has an array, consisting of n integers a1,\u2009a2,\u2009...,\u2009an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: he chooses two elements of the array ai, aj (i\u2009\u2260\u2009j); he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai\u2009=\u2009ai\u2009+\u20091 and aj\u2009=\u2009aj\u2009-\u20091. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the array size. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009104) \u2014 the original array.", "output_spec": "Print a single integer \u2014 the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.", "sample_inputs": ["2\n2 1", "3\n1 4 1"], "sample_outputs": ["1", "3"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "You have $$$n$$$ stacks of blocks. The $$$i$$$-th stack contains $$$h_i$$$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $$$i$$$-th stack (if there is at least one block) and put it to the $$$i + 1$$$-th stack. Can you make the sequence of heights strictly increasing?Note that the number of stacks always remains $$$n$$$: stacks don't disappear when they have $$$0$$$ blocks.", "input_spec": "First line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10^4)$$$ \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \\leq n \\leq 100)$$$. The second line of each test case contains $$$n$$$ integers $$$h_i$$$ $$$(0 \\leq h_i \\leq 10^9)$$$ \u2014 starting heights of the stacks. It's guaranteed that the sum of all $$$n$$$ does not exceed $$$10^4$$$.", "output_spec": "For each test case output YES if you can make the sequence of heights strictly increasing and NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).", "sample_inputs": ["6\n2\n1 2\n2\n1 0\n3\n4 4 4\n2\n0 0\n3\n0 1 0\n4\n1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["YES\nYES\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case there is no need to make any moves, the sequence of heights is already increasing.In the second test case we need to move one block from the first stack to the second. Then the heights become $$$0$$$ $$$1$$$.In the third test case we could move one block from the first stack to the second and then from the second to the third, which would make the heights $$$3$$$ $$$4$$$ $$$5$$$.In the fourth test case we can't make a move, but the sequence is not increasing, so the answer is NO.In the fifth test case we can only make one move (from the second to the third stack), which would make the heights $$$0$$$ $$$0$$$ $$$1$$$. Both $$$0$$$ $$$1$$$ $$$0$$$ and $$$0$$$ $$$0$$$ $$$1$$$ are not increasing sequences, so the answer is NO."}, "positive_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\n\r\nobject AShiftingStacks {\r\n def solve(hs: Array[Long]): String = {\r\n val l = hs.length\r\n if (l == 1) \"yes\"\r\n else {\r\n var s = 0L\r\n for (i <- hs.indices) {\r\n s += hs(i)\r\n if (s < i*(i+1)/2) return \"no\"\r\n }\r\n \"yes\"\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\\n2\\n1 2\\n2\\n1 0\\n3\\n4 4 4\\n2\\n0 0\\n3\\n0 1 0\\n4\\n1000000000 1000000000 1000000000 1000000000\".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 file.readLine\r\n val hs = file.readLine.split(\" \").map(_.toLong)\r\n println(solve(hs))\r\n i += 1\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.io.BufferedReader\r\nimport java.io.ByteArrayInputStream\r\nimport java.io.InputStreamReader\r\n\r\nobject AShiftingStacks {\r\n def solve(hs: Array[Long]): String = {\r\n val l = hs.length\r\n if (hs.sum >= ((l-1)*l)/2) \"yes\" else \"no\"\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\\n2\\n1 2\\n2\\n1 0\\n3\\n4 4 4\\n2\\n0 0\\n3\\n0 1 0\\n4\\n1000000000 1000000000 1000000000 1000000000\".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 file.readLine\r\n val hs = file.readLine.split(\" \").map(_.toLong)\r\n println(solve(hs))\r\n i += 1\r\n }\r\n }\r\n}"}], "src_uid": "7a8c4ba98a77097faff625b94889b365"} {"nl": {"description": "Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.The game works as follows: there is a tree of size $$$n$$$, rooted at node $$$1$$$, where each node is initially white. Red and Blue get one turn each. Red goes first. In Red's turn, he can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree red. However, to make the game fair, Red is only allowed to color $$$k$$$ nodes of the tree. In other words, after Red's turn, at most $$$k$$$ of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon. Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let $$$w$$$ be the number of white nodes, $$$r$$$ be the number of red nodes, and $$$b$$$ be the number of blue nodes. The score of the game is $$$w \\cdot (r - b)$$$.Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$; $$$1 \\le k \\le n$$$)\u00a0\u2014 the number of vertices in the tree and the maximum number of red nodes. Next $$$n - 1$$$ lines contains description of edges. The $$$i$$$-th line contains two space separated integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$; $$$u_i \\neq v_i$$$)\u00a0\u2014 the $$$i$$$-th edge of the tree. It's guaranteed that given edges form a tree.", "output_spec": "Print one integer\u00a0\u2014 the resulting score if both Red and Blue play optimally.", "sample_inputs": ["4 2\n1 2\n1 3\n1 4", "5 2\n1 2\n2 3\n3 4\n4 5", "7 2\n1 2\n1 3\n4 2\n3 5\n6 3\n6 7", "4 1\n1 2\n1 3\n1 4"], "sample_outputs": ["1", "6", "4", "-1"], "notes": "NoteIn the first test case, the optimal strategy is as follows: Red chooses to color the subtrees of nodes $$$2$$$ and $$$3$$$. Blue chooses to color the subtree of node $$$4$$$. At the end of this process, nodes $$$2$$$ and $$$3$$$ are red, node $$$4$$$ is blue, and node $$$1$$$ is white. The score of the game is $$$1 \\cdot (2 - 1) = 1$$$.In the second test case, the optimal strategy is as follows: Red chooses to color the subtree of node $$$4$$$. This colors both nodes $$$4$$$ and $$$5$$$. Blue does not have any options, so nothing is colored blue. At the end of this process, nodes $$$4$$$ and $$$5$$$ are red, and nodes $$$1$$$, $$$2$$$ and $$$3$$$ are white. The score of the game is $$$3 \\cdot (2 - 0) = 6$$$.For the third test case: The score of the game is $$$4 \\cdot (2 - 1) = 4$$$."}, "positive_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = b.cost - a.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed).toLong\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == {\r\n 1 + {\r\n par.parentOpt match {\r\n case None => 0\r\n case _ => 1\r\n }\r\n }\r\n }\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = {\r\n if (rem <= numR) {\r\n rem\r\n } else {\r\n rem.min(N/2)\r\n }\r\n }\r\n val ans: Long = (N - (numB + numR)).toLong * (numR - numB).toLong\r\n out.println(ans)\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed).toLong\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == {\r\n 1 + {\r\n par.parentOpt match {\r\n case None => 0\r\n case _ => 1\r\n }\r\n }\r\n }\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = {\r\n if (rem <= numR) {\r\n rem\r\n } else {\r\n rem.min(N/2)\r\n }\r\n }\r\n val ans: Long = (N - (numB + numR)).toLong * (numR - numB).toLong\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = {\r\n if (rem <= numR) {\r\n rem\r\n } else {\r\n rem.min(((rem - numR + numW) / 2) + numR)\r\n }\r\n }\r\n val ans: Long = (N - (numB + numR)).toLong * (numR - numB).toLong\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = {\r\n if (rem <= numR) {\r\n rem\r\n } else {\r\n rem.min(((rem - numR + numW) / 2) + numR)\r\n }\r\n }\r\n val ans: Long = numW.toLong * (numR - numB).toLong\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = {\r\n if (rem <= numR) {\r\n rem\r\n } else {\r\n rem.min(((rem - numR + numW) / 2) + numR)\r\n }\r\n }\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = {\r\n if (rem <= numR) {\r\n rem\r\n } else {\r\n rem.min((rem - numR + numW) / 2) + numR\r\n }\r\n }\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val rem = (N - (numW + numR))\r\n val numB = rem.min((rem + numW) / 2)\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = b.cost - a.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val numB = N - (numW + numR)\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = false\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = b.cost - a.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val numB = N - (numW + numR)\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val numB = N - (numW + numR)\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}, {"source_code": "import java.io._\r\nimport java.util.StringTokenizer\r\n\r\nimport scala.math.max\r\nimport scala.math.min\r\nimport scala.reflect.ClassTag\r\nimport scala.collection.immutable._\r\n\r\n\r\nobject Main {\r\n def main(args: Array[String]): Unit = {\r\n try {\r\n val (in, out) =\r\n if (isOnlineJudge) {\r\n (\r\n new FastScanner(new InputStreamReader(System.in)),\r\n new PrintWriter(System.out)\r\n )\r\n } else {\r\n (\r\n new FastScanner(new FileReader(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/input.txt\"))),\r\n new PrintWriter(new File(\"/home/naman/Desktop/Ramdom/CP/scala/src/output.txt\"))\r\n )\r\n }\r\n new CF1615E(in, out).solve()\r\n out.flush()\r\n out.close()\r\n } catch {\r\n case e: IOException => e.printStackTrace()\r\n }\r\n }\r\n\r\n private[this] val isOnlineJudge = true\r\n class FastScanner(val streamReader: InputStreamReader) {\r\n private[this] val reader = new BufferedReader(streamReader, 32768)\r\n private[this] var tokenizer: StringTokenizer = _\r\n\r\n @inline private[this] final def next(): String = {\r\n while (tokenizer == null || !tokenizer.hasMoreTokens)\r\n tokenizer = new StringTokenizer(reader.readLine)\r\n tokenizer.nextToken\r\n }\r\n\r\n def nextInt(): Int = Integer.parseInt(next())\r\n\r\n def nextLong(): Long = java.lang.Long.parseLong(next())\r\n\r\n def nextChar(): Char = next().charAt(0)\r\n\r\n def ni(): Int = nextInt()\r\n\r\n def nl(): Long = nextLong()\r\n\r\n def nc(): Char = nextChar()\r\n\r\n def ns(): String = next()\r\n\r\n def ns(n: Int): Array[Char] = ns().toCharArray\r\n\r\n def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\r\n\r\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\r\n val A1, A2 = Array.ofDim[Int](n)\r\n REP(n) { i =>\r\n A1(i) = ni() + offset\r\n A2(i) = ni() + offset\r\n }\r\n (A1, A2)\r\n }\r\n\r\n def nm(n: Int, m: Int): Array[Array[Int]] = {\r\n val A = Array.ofDim[Int](n, m)\r\n REP(n) { i =>\r\n REP(m) { j =>\r\n A(i)(j) = ni()\r\n }\r\n }\r\n A\r\n }\r\n\r\n def nal(n: Int): Array[Long] = map(n)(_ => nl())\r\n\r\n def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))\r\n }\r\n\r\n def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = offset\r\n val N = n + offset\r\n while (i < N) {\r\n f(i);\r\n i += 1\r\n }\r\n }\r\n\r\n def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\r\n var i = n - 1 + offset\r\n while (i >= offset) {\r\n f(i);\r\n i -= 1\r\n }\r\n }\r\n\r\n def TO(from: Int, to: Int)(f: Int => Unit): Unit = {\r\n REP(to - from + 1, from)(f)\r\n }\r\n\r\n def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {\r\n val res = Array.ofDim[A](n)\r\n REP(n)(i => res(i) = f(i + offset))\r\n res\r\n }\r\n\r\n def sumL(as: Array[Int]): Long = {\r\n var s = 0L\r\n REP(as.length)(i => s += as(i))\r\n s\r\n }\r\n\r\n def cumSum(as: Array[Int]): Array[Long] = {\r\n val cum = Array.ofDim[Long](as.length + 1)\r\n REP(as.length) { i =>\r\n cum(i + 1) = cum(i) + as(i)\r\n }\r\n cum\r\n }\r\n}\r\n\r\nimport scala.collection.mutable\r\nimport scala.collection.mutable.{ArrayBuffer, ListBuffer}\r\n\r\nobject Node {\r\n implicit object ord extends Ordering[Node] {\r\n def compare(a: Node, b: Node): Int = a.cost - b.cost\r\n }\r\n}\r\n\r\nclass Node{\r\n var parentOpt: Option[Node] = None\r\n var cost = 1\r\n val neighbours: ListBuffer[Node] = ListBuffer.empty\r\n var removed = 0\r\n}\r\n\r\nclass CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {\r\n import Main._\r\n import fScanner._\r\n\r\n def dfs(cur: Node): Unit = {\r\n cur.neighbours.foreach{ nbr =>\r\n if (cur.parentOpt.exists(nbr != _)) {\r\n nbr.parentOpt = Some(cur)\r\n dfs(nbr)\r\n }\r\n }\r\n }\r\n\r\n def solve(): Unit = {\r\n val N = ni()\r\n val K = ni()\r\n\r\n val nodes: ArrayBuffer[Node] = ArrayBuffer.empty\r\n nodes += new Node\r\n\r\n (1 to N).foreach{ _ =>\r\n nodes += new Node\r\n }\r\n\r\n (1 until N).foreach{ _ =>\r\n val u = ni()\r\n val v = ni()\r\n nodes(u).neighbours.append(nodes(v))\r\n nodes(v).neighbours.append(nodes(u))\r\n }\r\n\r\n dfs(nodes(1))\r\n\r\n val initialLeafs =\r\n nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isEmpty)\r\n val numL = initialLeafs.size\r\n// println(s\"numL : ${numL}\")\r\n if (numL <= K) {\r\n val numRed = K.min(numL.max(N/2))\r\n val ans: Long = numRed.toLong * (N - numRed)\r\n out.println(ans)\r\n return\r\n }\r\n\r\n val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)\r\n\r\n var numR = numL\r\n var numW = N - numR\r\n\r\n while(numR > K && pq.nonEmpty) {\r\n val node = pq.dequeue()\r\n if (\r\n node.parentOpt.exists{ par =>\r\n (par.neighbours.size - par.removed) == 1\r\n }\r\n ) {\r\n node.parentOpt.foreach{ par =>\r\n par.cost = node.cost + 1\r\n pq.enqueue(par)\r\n }\r\n }\r\n else {\r\n node.parentOpt.foreach(_.removed += 1)\r\n numR -= 1\r\n numW -= (node.cost - 1)\r\n }\r\n }\r\n\r\n val numB = N - (numW + numR)\r\n val ans: Long = numW.toLong * (numR - numB)\r\n out.println(ans)\r\n }\r\n}"}], "src_uid": "6c5cf702d85ff25cf9e7bfd16534197d"} {"nl": {"description": "AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $$$a$$$ and $$$b$$$, both consist of $$$n$$$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): She chooses two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$), then decreases the $$$i$$$-th element of array $$$a$$$ by $$$1$$$, and increases the $$$j$$$-th element of array $$$a$$$ by $$$1$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index of array $$$a$$$ are $$$a_i - 1$$$ and $$$a_j + 1$$$, respectively. Each element of array $$$a$$$ must be non-negative after each operation. If $$$i = j$$$ this operation doesn't change the array $$$a$$$. AquaMoon wants to make some operations to make arrays $$$a$$$ and $$$b$$$ equal. Two arrays $$$a$$$ and $$$b$$$ are considered equal if and only if $$$a_i = b_i$$$ for all $$$1 \\leq i \\leq n$$$.Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays $$$a$$$ and $$$b$$$ equal.Please note, that you don't have to minimize the number of operations.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\leq a_i \\leq 100$$$). The sum of all $$$a_i$$$ does not exceed $$$100$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$0 \\leq b_i \\leq 100$$$). The sum of all $$$b_i$$$ does not exceed $$$100$$$.", "output_spec": "For each test case print \"-1\" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer $$$m$$$ ($$$0 \\leq m \\leq 100$$$) in the first line \u2014 the number of operations. Then print $$$m$$$ lines, each line consists of two integers $$$i$$$ and $$$j$$$ \u2014 the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with $$$m \\leq 100$$$. If there are multiple possible solutions, you can print any.", "sample_inputs": ["4\n4\n1 2 3 4\n3 1 2 4\n2\n1 3\n2 1\n1\n0\n0\n5\n4 3 2 1 0\n0 1 2 3 4"], "sample_outputs": ["2\n2 1\n3 1\n-1\n0\n6\n1 4\n1 4\n1 5\n1 5\n2 5\n2 5"], "notes": "NoteIn the first example, we do the following operations: $$$i = 2$$$, $$$j = 1$$$: $$$[1, 2, 3, 4] \\rightarrow [2, 1, 3, 4]$$$; $$$i = 3$$$, $$$j = 1$$$: $$$[2, 1, 3, 4] \\rightarrow [3, 1, 2, 4]$$$; In the second example, it's impossible to make two arrays equal."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Hiking club \"Up the hill\" just returned from a walk. Now they are trying to remember which hills they've just walked through.It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop N\u2009-\u20091 to the stop N and successfully finished their expedition.They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill.Help them by suggesting some possible stop heights satisfying numbers from the travel journal.", "input_spec": "In the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number B\u00a0\u2014 the number of days of walking down the hill (A\u2009+\u2009B\u2009+\u20091\u2009=\u2009N, 1\u2009\u2264\u2009N\u2009\u2264\u2009100\u2009000).", "output_spec": "Output N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting.", "sample_inputs": ["0\n1", "2\n1"], "sample_outputs": ["2 1", "1 3 4 2"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "add2285f3f710eb41185d6a83e44b37a"} {"nl": {"description": "Luis has a sequence of $$$n+1$$$ integers $$$a_1, a_2, \\ldots, a_{n+1}$$$. For each $$$i = 1, 2, \\ldots, n+1$$$ it is guaranteed that $$$0\\leq a_i < n$$$, or $$$a_i=n^2$$$. He has calculated the sum of all the elements of the sequence, and called this value $$$s$$$. Luis has lost his sequence, but he remembers the values of $$$n$$$ and $$$s$$$. Can you find the number of elements in the sequence that are equal to $$$n^2$$$?We can show that the answer is unique under the given constraints.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 2\\cdot 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1\\le n< 10^6$$$, $$$0\\le s \\le 10^{18}$$$). It is guaranteed that the value of $$$s$$$ is a valid sum for some sequence satisfying the above constraints.", "output_spec": "For each test case, print one integer\u00a0\u2014 the number of elements in the sequence which are equal to $$$n^2$$$.", "sample_inputs": ["4\n\n7 0\n\n1 1\n\n2 12\n\n3 12"], "sample_outputs": ["0\n1\n3\n1"], "notes": "NoteIn the first test case, we have $$$s=0$$$ so all numbers are equal to $$$0$$$ and there isn't any number equal to $$$49$$$.In the second test case, we have $$$s=1$$$. There are two possible sequences: $$$[0, 1]$$$ or $$$[1, 0]$$$. In both cases, the number $$$1$$$ appears just once. In the third test case, we have $$$s=12$$$, which is the maximum possible value of $$$s$$$ for this case. Thus, the number $$$4$$$ appears $$$3$$$ times in the sequence."}, "positive_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}"}, {"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"} {"nl": {"description": "A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \\dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$0 \\leq m \\leq \\min(10^5,\\frac{n(n-1)}{2})$$$) \u2014 the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \\dots,a_n$$$ ($$$0 \\leq a_i \\leq 10^4$$$) \u2014 the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\leq x,y \\leq n$$$, $$$x \\neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.", "output_spec": "For each test case, print a line containing a single integer \u2013 the minimum possible unhappiness value of a valid party.", "sample_inputs": ["4\n\n1 0\n\n1\n\n3 1\n\n2 1 3\n\n1 3\n\n5 5\n\n1 2 3 4 5\n\n1 2\n\n1 3\n\n1 4\n\n1 5\n\n2 3\n\n5 5\n\n1 1 1 1 1\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n5 1"], "sample_outputs": ["0\n2\n3\n2"], "notes": "NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible: invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$); invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$); invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$); invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$); invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$); invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$). The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\n\r\n\r\nobject Main {\r\n class TestCase(val n : Int, val m : Int, val unhappiness : Map[Int, Int],val relations : Map[Int, Set[Int]]){\r\n def getNbNodes: Int = n\r\n def getNbEdges: Int = m\r\n def getUnhappiness: Map[Int, Int] = unhappiness\r\n def getRelations: Map[Int, Set[Int]] = relations\r\n }\r\n /**\r\n * Read the number of test cases in the first line of the input.\r\n * Next we read the test cases and store them in a list in thi way:\r\n - The first line of each test case contains the number of nodes and edges.\r\n - The second line contains the unhappiness of each node if we remove it.\r\n - The other lines contain the relations between nodes.\r\n * @return A list of test cases.\r\n */\r\n def readInput : List[TestCase] = {\r\n val nbTestCases = readLine.toInt\r\n val testCases = for (i <- 0 to nbTestCases - 1) yield {\r\n val (n, m) = readLine.split(\" \").map(_.toInt).toList match {case List(n, m) => (n, m)}\r\n val unhappiness = readLine.split(\" \").map(_.toInt).toList.zipWithIndex.map{case (unhappiness, index) => (index, unhappiness)}.toMap\r\n val listRelations = (for (u <- 1 to m) yield {\r\n val (node1, node2) = readLine.split(\" \").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}\r\n (node1, node2)\r\n }).toList\r\n var relations = Map[Int, Set[Int]]()\r\n for (relation <- listRelations) {\r\n relations += relation._1 -> (relations.getOrElse(relation._1, Set[Int]()) + relation._2)\r\n relations += relation._2 -> (relations.getOrElse(relation._2, Set[Int]()) + relation._1)\r\n }\r\n new TestCase(n, m, unhappiness, relations)\r\n }\r\n testCases.toList\r\n }\r\n\r\n def printTestCase(testCase : TestCase) : Unit = {\r\n println(\"Number of nodes: \" + testCase.getNbNodes)\r\n println(\"Number of edges: \" + testCase.getNbEdges)\r\n println(\"Unhappiness: \" + testCase.getUnhappiness)\r\n println(\"Relations: \" + testCase.getRelations)\r\n }\r\n\r\n\r\n\r\n def solve(testCase : TestCase) : Unit = {\r\n if (testCase.getNbEdges % 2 == 0) {println(\"0\\n\")}\r\n else {\r\n var minUnhappiness = Int.MaxValue\r\n for(i <- 0 until testCase.getNbNodes) {\r\n if (testCase.relations.getOrElse(i, Set[Int]()).size % 2 == 1) {\r\n minUnhappiness = Math.min(minUnhappiness, testCase.unhappiness(i))\r\n }\r\n else {\r\n for (j <- testCase.relations.getOrElse(i, Set[Int]())) {\r\n val node = testCase.relations.getOrElse(j, List()).size\r\n if (node % 2 == 0) {\r\n minUnhappiness = Integer.min(minUnhappiness, testCase.unhappiness(i) + testCase.unhappiness(j))\r\n }\r\n }\r\n }\r\n\r\n }\r\n println(minUnhappiness + \"\\n\")\r\n }\r\n }\r\n\r\n\r\n\r\n def main(args: Array[String]) = {\r\n val testCases = readInput\r\n for (tCase <- testCases) {solve(tCase)}\r\n }\r\n\r\n}\r\n\r\n\r\n\r\n\r\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\n\r\n\r\nobject Main {\r\n class TestCase(val n : Int, val m : Int, val unhappiness : Map[Int, Int],val relations : Map[Int, Set[Int]]){\r\n def getNbNodes: Int = n\r\n def getNbEdges: Int = m\r\n def getUnhappiness: Map[Int, Int] = unhappiness\r\n def getRelations: Map[Int, Set[Int]] = relations\r\n }\r\n /**\r\n * Read the number of test cases in the first line of the input.\r\n * Next we read the test cases and store them in a list in thi way:\r\n - The first line of each test case contains the number of nodes and edges.\r\n - The second line contains the unhappiness of each node if we remove it.\r\n - The other lines contain the relations between nodes.\r\n * @return A list of test cases.\r\n */\r\n def readInput : List[TestCase] = {\r\n val nbTestCases = readLine.toInt\r\n val testCases = for (i <- 0 to nbTestCases - 1) yield {\r\n val (n, m) = readLine.split(\" \").map(_.toInt).toList match {case List(n, m) => (n, m)}\r\n val unhappiness = readLine.split(\" \").map(_.toInt).toList.zipWithIndex.map{case (unhappiness, index) => (index, unhappiness)}.toMap\r\n val listRelations = (for (u <- 1 to m) yield {\r\n val (node1, node2) = readLine.split(\" \").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}\r\n (node1, node2)\r\n }).toList\r\n var relations = Map[Int, Set[Int]]()\r\n for (relation <- listRelations) {\r\n relations += relation._1 -> (relations.getOrElse(relation._1, Set[Int]()) + relation._2)\r\n relations += relation._2 -> (relations.getOrElse(relation._2, Set[Int]()) + relation._1)\r\n }\r\n new TestCase(n, m, unhappiness, relations)\r\n }\r\n testCases.toList\r\n }\r\n\r\n def printTestCase(testCase : TestCase) : Unit = {\r\n println(\"Number of nodes: \" + testCase.getNbNodes)\r\n println(\"Number of edges: \" + testCase.getNbEdges)\r\n println(\"Unhappiness: \" + testCase.getUnhappiness)\r\n println(\"Relations: \" + testCase.getRelations)\r\n }\r\n\r\n\r\n\r\n def solve(testCase : TestCase) : Unit = {\r\n if (testCase.getNbEdges % 2 == 0) {println(\"0\\n\")}\r\n else {\r\n var minUnhappiness = Int.MaxValue\r\n for(i <- 0 until testCase.getNbNodes) {\r\n if (testCase.relations.getOrElse(i, Set[Int]()).size % 2 == 1) {\r\n println(\"Test case \" + i + \": \" + testCase.unhappiness.get(i))\r\n minUnhappiness = Math.min(minUnhappiness, testCase.unhappiness(i))\r\n }\r\n else {\r\n for (j <- testCase.relations.getOrElse(i, Set[Int]())) {\r\n val node = testCase.relations.getOrElse(j, List()).size\r\n if (node % 2 == 0) {\r\n minUnhappiness = Integer.min(minUnhappiness, testCase.unhappiness(i) + testCase.unhappiness(j))\r\n }\r\n }\r\n }\r\n\r\n }\r\n println(minUnhappiness + \"\\n\")\r\n }\r\n }\r\n\r\n\r\n\r\n def main(args: Array[String]) = {\r\n val testCases = readInput\r\n for (tCase <- testCases) {solve(tCase)}\r\n }\r\n\r\n}\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "import scala.io.StdIn.readLine\r\n\r\n\r\n\r\nobject Main {\r\n class TestCase(val n : Int, val m : Int, val unhappiness : List[(Int, Int)],val relations : Map[Int, List[Int]]){\r\n def getNbNodes: Int = n\r\n def getNbEdges: Int = m\r\n def getUnhappiness: List[(Int, Int)] = unhappiness\r\n def getRelations: Map[Int, List[Int]] = relations\r\n }\r\n /**\r\n * Read the number of test cases in the first line of the input.\r\n * Next we read the test cases and store them in a list in thi way:\r\n - The first line of each test case contains the number of nodes and edges.\r\n - The second line contains the unhappiness of each node if we remove it.\r\n - The other lines contain the relations between nodes.\r\n * @return A list of test cases.\r\n */\r\n def readInput : List[TestCase] = {\r\n val nbTestCases = readLine.toInt\r\n val testCases = for (i <- 0 to nbTestCases - 1) yield {\r\n val (n, m) = readLine.split(\" \").map(_.toInt).toList match {case List(n, m) => (n, m)}\r\n val unhappiness = readLine.split(\" \").map(_.toInt).toList.zipWithIndex.map{case (u, i) => (i, u)}.sortBy(_._2)\r\n val relations : List[(Int,Int)] = (for (u <- 1 to m) yield {\r\n val (node1, node2) = readLine.split(\" \").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}\r\n (node1, node2)\r\n }).toList\r\n val relationsMap = relations.groupBy(_._1).mapValues(_.map(_._2))\r\n new TestCase(n, m, unhappiness, relationsMap)\r\n }\r\n testCases.toList\r\n }\r\n\r\n def printTestCase(testCase : TestCase) : Unit = {\r\n println(\"Number of nodes: \" + testCase.getNbNodes)\r\n println(\"Number of edges: \" + testCase.getNbEdges)\r\n println(\"Unhappiness: \" + testCase.getUnhappiness)\r\n println(\"Relations: \" + testCase.getRelations)\r\n }\r\n\r\n\r\n\r\n def solve(original : TestCase) : Int = {\r\n\r\n def solveRec(last : TestCase, current : TestCase, lastMinUnhappinessNode : Int, currentMinUnhappiness : Int) : Int = {\r\n if (current.getNbEdges % 2 == 0 || current.getNbNodes == 0) {currentMinUnhappiness}\r\n else {\r\n\r\n // Either we remove the smaller unhappinnes generating node from the graph\r\n // Check the node with the smallest unhappiness\r\n val currentMinUnhappinessNode = current.getUnhappiness.head._1\r\n\r\n // We compute the number of edges in the new relations graph\r\n val currentNewNbEdges = current.getNbEdges - current.getRelations.get(currentMinUnhappinessNode).getOrElse(List()).size\r\n\r\n // We remove the unhappiness node from the graph\r\n val currentNewUnhappiness = current.getUnhappiness.tail\r\n\r\n // Remove the node from the relations map and remove the node from the unhappiness list\r\n val currentNewRelations = current.getRelations.map{case (k, v) => (k, v.filter(_ != currentMinUnhappinessNode))} - currentMinUnhappinessNode\r\n\r\n // Check if the new graph is solvable\r\n lazy val sol1 = solveRec(current, new TestCase(current.getNbNodes - 1, currentNewNbEdges, currentNewUnhappiness, currentNewRelations), currentMinUnhappiness, currentMinUnhappiness + current.getUnhappiness.head._2)\r\n\r\n // Or we remove the second smallest unhappinnes generating node from the last graph\r\n // Check if there is at least 2 nodes in the last graph\r\n if(last.getNbNodes < 2) { return sol1 }\r\n\r\n // Check the node with the second smallest unhappiness\r\n val lastMinUnhappinessNode = last.getUnhappiness.tail.head._1\r\n\r\n // We compute the number of edges in the new relations graph\r\n val lastNewNbEdges = last.getNbEdges - last.getRelations.get(lastMinUnhappinessNode).getOrElse(List()).size\r\n\r\n // We remove the unhappiness node from the graph\r\n val lastNewUnhappiness = last.getUnhappiness.take(1) ++ last.getUnhappiness.drop(2)\r\n\r\n // Remove the node from the relations map and remove the node from the unhappiness list\r\n val lastNewRelations = last.getRelations.map{case (k, v) => (k, v.filter(_ != lastMinUnhappinessNode))} - lastMinUnhappinessNode\r\n\r\n // Check if the new graph is solvable\r\n lazy val sol2 = solveRec(current, new TestCase(last.getNbNodes - 1, lastNewNbEdges, lastNewUnhappiness, lastNewRelations), lastMinUnhappinessNode, lastMinUnhappinessNode + last.getUnhappiness.tail.head._2)\r\n\r\n return Integer.min(sol1, sol2)\r\n }\r\n }\r\n solveRec(new TestCase(0, 0, Nil, Map()), original, 0, 0)\r\n }\r\n\r\n\r\n\r\n def main(args: Array[String]) = {\r\n val testCases = readInput\r\n for (tCase <- testCases) {println(solve(tCase))}\r\n }\r\n\r\n}\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "import scala.io.StdIn.readLine\r\n\r\n\r\n\r\nobject Main {\r\n class TestCase(val n : Int, val m : Int, val unhappiness : List[(Int, Int)],val relations : Map[Int, List[Int]]){\r\n def getNbNodes: Int = n\r\n def getNbEdges: Int = m\r\n def getUnhappiness: List[(Int, Int)] = unhappiness\r\n def getRelations: Map[Int, List[Int]] = relations\r\n }\r\n /**\r\n * Read the number of test cases in the first line of the input.\r\n * Next we read the test cases and store them in a list in thi way:\r\n - The first line of each test case contains the number of nodes and edges.\r\n - The second line contains the unhappiness of each node if we remove it.\r\n - The other lines contain the relations between nodes.\r\n * @return A list of test cases.\r\n */\r\n def readInput : List[TestCase] = {\r\n val nbTestCases = readLine.toInt\r\n val testCases = for (i <- 0 to nbTestCases - 1) yield {\r\n val (n, m) = readLine.split(\" \").map(_.toInt).toList match {case List(n, m) => (n, m)}\r\n val unhappiness = readLine.split(\" \").map(_.toInt).toList.zipWithIndex.map{case (u, i) => (i, u)}.sortBy(_._2)\r\n val relations : List[(Int,Int)] = (for (u <- 1 to m) yield {\r\n val (node1, node2) = readLine.split(\" \").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}\r\n (node1, node2)\r\n }).toList\r\n val relationsMap = relations.groupBy(_._1).mapValues(_.map(_._2))\r\n new TestCase(n, m, unhappiness, relationsMap)\r\n }\r\n testCases.toList\r\n }\r\n\r\n\r\n\r\n def solve(original : TestCase) : Int = {\r\n\r\n def solveRec(last : TestCase, current : TestCase, minUnhappiness : Int) : Int = {\r\n if (current.getNbEdges % 2 == 0 || current.getNbNodes == 0) {minUnhappiness}\r\n else {\r\n // Either we remove the smaller unhappinnes generating node from the graph\r\n // Check the node with the smallest unhappiness\r\n val currentMinUnhappinessNode = current.getUnhappiness.head._1\r\n\r\n // We compute the number of edges in the new relations graph\r\n val currentNewNbEdges = current.getNbEdges - current.getRelations.get(currentMinUnhappinessNode).getOrElse(List()).size\r\n\r\n // We remove the unhappiness node from the graph\r\n val currentNewUnhappiness = current.getUnhappiness.tail\r\n\r\n // Remove the node from the relations map and remove the node from the unhappiness list\r\n val currentNewRelations = current.getRelations.map{case (k, v) => (k, v.filter(_ != currentMinUnhappinessNode))} - currentMinUnhappinessNode\r\n\r\n // Check if the new graph is solvable\r\n lazy val sol1 = solveRec(current, new TestCase(current.getNbNodes - 1, currentNewNbEdges, currentNewUnhappiness, currentNewRelations), minUnhappiness + current.getUnhappiness.head._2)\r\n\r\n // Or we remove the second smallest unhappinnes generating node from the last graph\r\n // Check if there is at least 2 nodes in the last graph\r\n if(last.getNbNodes < 2) {Integer.min(minUnhappiness, sol1)}\r\n\r\n // Check the node with the second smallest unhappiness\r\n val lastMinUnhappinessNode = last.getUnhappiness.tail.head._1\r\n\r\n // We compute the number of edges in the new relations graph\r\n val lastNewNbEdges = last.getNbEdges - last.getRelations.get(lastMinUnhappinessNode).getOrElse(List()).size\r\n\r\n // We remove the unhappiness node from the graph\r\n val lastNewUnhappiness = last.getUnhappiness.tail.tail\r\n\r\n // Remove the node from the relations map and remove the node from the unhappiness list\r\n val lastNewRelations = last.getRelations.map{case (k, v) => (k, v.filter(_ != lastMinUnhappinessNode))} - lastMinUnhappinessNode\r\n\r\n // Check if the new graph is solvable\r\n lazy val sol2 = solveRec(current, new TestCase(last.getNbNodes - 1, lastNewNbEdges, lastNewUnhappiness, lastNewRelations), minUnhappiness + last.getUnhappiness.tail.head._2)\r\n\r\n Integer.min(sol1, sol2)\r\n }\r\n }\r\n solveRec(original, original, 0)\r\n }\r\n\r\n\r\n\r\n def main(args: Array[String]) = {\r\n val testCases = readInput\r\n for (tCase <- testCases) {println(solve(tCase))}\r\n }\r\n\r\n}\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "import scala.io.StdIn.readLine\r\n\r\n\r\n\r\nobject Main {\r\n class TestCase(val n : Int, val m : Int, val unhappiness : List[(Int, Int)],val relations : Map[Int, List[Int]]){\r\n def getNbNodes: Int = n\r\n def getNbEdges: Int = m\r\n def getUnhappiness: List[(Int, Int)] = unhappiness\r\n def getRelations: Map[Int, List[Int]] = relations\r\n }\r\n /**\r\n * Read the number of test cases in the first line of the input.\r\n * Next we read the test cases and store them in a list in thi way:\r\n - The first line of each test case contains the number of nodes and edges.\r\n - The second line contains the unhappiness of each node if we remove it.\r\n - The other lines contain the relations between nodes.\r\n * @return A list of test cases.\r\n */\r\n def readInput : List[TestCase] = {\r\n val nbTestCases = readLine.toInt\r\n val testCases = for (i <- 0 to nbTestCases-1) yield {\r\n val (n, m) = readLine.split(\" \").map(_.toInt).toList match {case List(n, m) => (n, m)}\r\n val unhappiness = readLine.split(\" \").map(_.toInt).toList.zipWithIndex.map{case (u, i) => (i, u)}.sortBy(_._2)\r\n val relations : List[(Int,Int)] = (for (u <- 0 to m - 1) yield {\r\n val (node1, node2) = readLine.split(\" \").map(_.toInt).toList match {case List(n1, n2) => (n1 , n2)}\r\n (node1, node2)\r\n }).toList\r\n val relationsMap = relations.groupBy(_._1).mapValues(_.map(_._2))\r\n new TestCase(n, m, unhappiness, relationsMap)\r\n }\r\n testCases.toList\r\n }\r\n\r\n\r\n\r\n def solve(tCase : TestCase) : Int = {\r\n def solveRec(test : TestCase, minUnhappiness : Int) : Int = {\r\n if (test.getNbEdges % 2 == 0) {minUnhappiness}\r\n else {\r\n // Either we remove the smaller unhappinnes generating node from the graph\r\n // Check the node with the smallest unhappiness\r\n val minUnhappinessNode = test.getUnhappiness.head._1\r\n\r\n // We compute the number of edges in the new relations graph\r\n val newNbEdges = test.getNbEdges - test.getRelations.get(minUnhappinessNode).size\r\n\r\n // We remove the unhappiness node from the graph\r\n val newUnhappiness = test.getUnhappiness.tail\r\n\r\n // Remove the node from the relations map and remove the node from the unhappiness list\r\n val newRelations = test.getRelations.map{case (k, v) => (k, v.filter(_ != minUnhappinessNode))} - minUnhappinessNode\r\n\r\n // Check if the new graph is solvable\r\n solveRec(new TestCase(test.getNbNodes - 1, newNbEdges, newUnhappiness, newRelations), minUnhappiness + test.getUnhappiness.head._2)\r\n }\r\n }\r\n solveRec(tCase, 0)\r\n }\r\n\r\n\r\n\r\n def main(args: Array[String]) = {\r\n val testCases = readInput\r\n for (tCase <- testCases) {println(solve(tCase))}\r\n }\r\n\r\n}\r\n\r\n\r\n\r\n\r\n"}], "src_uid": "a9c54d6f952320d75324b30dcb098332"} {"nl": {"description": "Polycarp wants to cook a soup. To do it, he needs to buy exactly $$$n$$$ liters of water.There are only two types of water bottles in the nearby shop \u2014 $$$1$$$-liter bottles and $$$2$$$-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles. You also have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 500$$$) \u2014 the number of queries. The next $$$q$$$ lines contain queries. The $$$i$$$-th query is given as three space-separated integers $$$n_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le n_i \\le 10^{12}, 1 \\le a_i, b_i \\le 1000$$$) \u2014 how many liters Polycarp needs in the $$$i$$$-th query, the cost (in burles) of the bottle of the first type in the $$$i$$$-th query and the cost (in burles) of the bottle of the second type in the $$$i$$$-th query, respectively.", "output_spec": "Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n_i$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a_i$$$ burles and the bottle of the second type costs $$$b_i$$$ burles.", "sample_inputs": ["4\n10 1 3\n7 3 2\n1 1000 1\n1000000000000 42 88"], "sample_outputs": ["10\n9\n1000\n42000000000000"], "notes": null}, "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 = 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}"}, {"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"} {"nl": {"description": "An array of integers $$$p_1, p_2, \\dots, p_n$$$ is called a permutation if it contains each number from $$$1$$$ to $$$n$$$ exactly once. For example, the following arrays are permutations: $$$[3, 1, 2]$$$, $$$[1]$$$, $$$[1, 2, 3, 4, 5]$$$ and $$$[4, 3, 1, 2]$$$. The following arrays are not permutations: $$$[2]$$$, $$$[1, 1]$$$, $$$[2, 3, 4]$$$.Polycarp invented a really cool permutation $$$p_1, p_2, \\dots, p_n$$$ of length $$$n$$$. It is very disappointing, but he forgot this permutation. He only remembers the array $$$q_1, q_2, \\dots, q_{n-1}$$$ of length $$$n-1$$$, where $$$q_i=p_{i+1}-p_i$$$.Given $$$n$$$ and $$$q=q_1, q_2, \\dots, q_{n-1}$$$, help Polycarp restore the invented permutation.", "input_spec": "The first line contains the integer $$$n$$$ ($$$2 \\le n \\le 2\\cdot10^5$$$) \u2014 the length of the permutation to restore. The second line contains $$$n-1$$$ integers $$$q_1, q_2, \\dots, q_{n-1}$$$ ($$$-n < q_i < n$$$).", "output_spec": "Print the integer -1 if there is no such permutation of length $$$n$$$ which corresponds to the given array $$$q$$$. Otherwise, if it exists, print $$$p_1, p_2, \\dots, p_n$$$. Print any such permutation if there are many of them.", "sample_inputs": ["3\n-2 1", "5\n1 1 1 1", "4\n-1 2 2"], "sample_outputs": ["3 1 2", "1 2 3 4 5", "-1"], "notes": null}, "positive_code": [{"source_code": "object _1141C 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 diffs = io.read[Seq, Int](n - 1)\n\n val zero = diffs.scanLeft(0)(_ + _)\n val toAdd = 1 - zero.min\n val added = zero.map(_ + toAdd)\n val ans = if ((1 to n).toSet == added.toSet) {\n added\n } else {\n Seq(-1)\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 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": "b6ac7c30b7efdc7206dbbad5cfb86db7"} {"nl": {"description": "You are given an integer array $$$a_1, a_2, \\ldots, a_n$$$.The array $$$b$$$ is called to be a subsequence of $$$a$$$ if it is possible to remove some elements from $$$a$$$ to get $$$b$$$.Array $$$b_1, b_2, \\ldots, b_k$$$ is called to be good if it is not empty and for every $$$i$$$ ($$$1 \\le i \\le k$$$) $$$b_i$$$ is divisible by $$$i$$$.Find the number of good subsequences in $$$a$$$ modulo $$$10^9 + 7$$$. Two subsequences are considered different if index sets of numbers included in them are different. That is, the values \u200bof the elements \u200bdo not matter in the comparison of subsequences. In particular, the array $$$a$$$ has exactly $$$2^n - 1$$$ different subsequences (excluding an empty subsequence).", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$).", "output_spec": "Print exactly one integer\u00a0\u2014 the number of good subsequences taken modulo $$$10^9 + 7$$$.", "sample_inputs": ["2\n1 2", "5\n2 2 1 22 14"], "sample_outputs": ["3", "13"], "notes": "NoteIn the first example, all three non-empty possible subsequences are good: $$$\\{1\\}$$$, $$$\\{1, 2\\}$$$, $$$\\{2\\}$$$In the second example, the possible good subsequences are: $$$\\{2\\}$$$, $$$\\{2, 2\\}$$$, $$$\\{2, 22\\}$$$, $$$\\{2, 14\\}$$$, $$$\\{2\\}$$$, $$$\\{2, 22\\}$$$, $$$\\{2, 14\\}$$$, $$$\\{1\\}$$$, $$$\\{1, 22\\}$$$, $$$\\{1, 14\\}$$$, $$$\\{22\\}$$$, $$$\\{22, 14\\}$$$, $$$\\{14\\}$$$.Note, that some subsequences are listed more than once, since they occur in the original array multiple times."}, "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 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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 // \u221an \u307e\u3067\u898b\u3064\u304b\u3089\u306a\u304b\u3063\u305f\u3089 n0\u306f\u7d20\u6570\u304b1\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"} {"nl": {"description": "There is a house with $$$n$$$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i = 1$$$ if in the $$$i$$$-th flat the light is on and $$$a_i = 0$$$ otherwise.Vova thinks that people in the $$$i$$$-th flats are disturbed and cannot sleep if and only if $$$1 < i < n$$$ and $$$a_{i - 1} = a_{i + 1} = 1$$$ and $$$a_i = 0$$$.Vova is concerned by the following question: what is the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $$$k$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$3 \\le n \\le 100$$$) \u2014 the number of flats in the house. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$a_i \\in \\{0, 1\\}$$$), where $$$a_i$$$ is the state of light in the $$$i$$$-th flat.", "output_spec": "Print only one integer \u2014 the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the light then nobody will be disturbed.", "sample_inputs": ["10\n1 1 0 1 1 0 1 0 1 0", "5\n1 1 0 0 0", "4\n1 1 1 1"], "sample_outputs": ["2", "0", "0"], "notes": "NoteIn the first example people from flats $$$2$$$ and $$$7$$$ or $$$4$$$ and $$$7$$$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples."}, "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 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}"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "ea62b6f68d25fb17aba8932af8377db0"} {"nl": {"description": "Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.", "input_spec": "The first line contains a single integer $$$n~(1 \\le n \\le 3 \\cdot 10^5)$$$ \u2014 the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\cdots, a_n~(1 \\le a_i \\le 10^9)$$$ \u2014 elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \\le m \\le 3 \\cdot 10^5)$$$ \u2014 the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \\cdots, b_m~(1 \\le b_i \\le 10^9)$$$ - elements of the array $$$B$$$.", "output_spec": "Print a single integer \u2014 the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print \"-1\".", "sample_inputs": ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"], "sample_outputs": ["3", "-1", "3"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1,\u2009y1),\u2009(x2,\u2009y2),\u2009...,\u2009(xn,\u2009yn). Let's define neighbors for some fixed point from the given set (x,\u2009y): point (x',\u2009y') is (x,\u2009y)'s right neighbor, if x'\u2009>\u2009x and y'\u2009=\u2009y point (x',\u2009y') is (x,\u2009y)'s left neighbor, if x'\u2009<\u2009x and y'\u2009=\u2009y point (x',\u2009y') is (x,\u2009y)'s lower neighbor, if x'\u2009=\u2009x and y'\u2009<\u2009y point (x',\u2009y') is (x,\u2009y)'s upper neighbor, if x'\u2009=\u2009x and y'\u2009>\u2009y We'll consider point (x,\u2009y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.", "input_spec": "The first input line contains the only integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200) \u2014 the number of points in the given set. Next n lines contain the coordinates of the points written as \"x y\" (without the quotes) (|x|,\u2009|y|\u2009\u2264\u20091000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.", "output_spec": "Print the only number \u2014 the number of supercentral points of the given set.", "sample_inputs": ["8\n1 1\n4 2\n3 1\n1 2\n0 2\n0 1\n1 0\n1 3", "5\n0 0\n0 1\n1 0\n0 -1\n-1 0"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample the supercentral points are only points (1,\u20091) and (1,\u20092).In the second sample there is one supercental point \u2014 point (0,\u20090)."}, "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{_ =>\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}"}, {"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"} {"nl": {"description": "So the Beautiful Regional Contest (BeRC) has come to an end! $$$n$$$ students took part in the contest. The final standings are already known: the participant in the $$$i$$$-th place solved $$$p_i$$$ problems. Since the participants are primarily sorted by the number of solved problems, then $$$p_1 \\ge p_2 \\ge \\dots \\ge p_n$$$.Help the jury distribute the gold, silver and bronze medals. Let their numbers be $$$g$$$, $$$s$$$ and $$$b$$$, respectively. Here is a list of requirements from the rules, which all must be satisfied: for each of the three types of medals, at least one medal must be awarded (that is, $$$g>0$$$, $$$s>0$$$ and $$$b>0$$$); the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $$$g<s$$$ and $$$g<b$$$, but there are no requirements between $$$s$$$ and $$$b$$$); each gold medalist must solve strictly more problems than any awarded with a silver medal; each silver medalist must solve strictly more problems than any awarded a bronze medal; each bronze medalist must solve strictly more problems than any participant not awarded a medal; the total number of medalists $$$g+s+b$$$ should not exceed half of all participants (for example, if $$$n=21$$$, then you can award a maximum of $$$10$$$ participants, and if $$$n=26$$$, then you can award a maximum of $$$13$$$ participants). The jury wants to reward with medals the total maximal number participants (i.e. to maximize $$$g+s+b$$$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10000$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains an integer $$$n$$$ ($$$1 \\le n \\le 4\\cdot10^5$$$) \u2014 the number of BeRC participants. The second line of a test case contains integers $$$p_1, p_2, \\dots, p_n$$$ ($$$0 \\le p_i \\le 10^6$$$), where $$$p_i$$$ is equal to the number of problems solved by the $$$i$$$-th participant from the final standings. The values $$$p_i$$$ are sorted in non-increasing order, i.e. $$$p_1 \\ge p_2 \\ge \\dots \\ge p_n$$$. The sum of $$$n$$$ over all test cases in the input does not exceed $$$4\\cdot10^5$$$.", "output_spec": "Print $$$t$$$ lines, the $$$j$$$-th line should contain the answer to the $$$j$$$-th test case. The answer consists of three non-negative integers $$$g, s, b$$$. Print $$$g=s=b=0$$$ if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time. Otherwise, print three positive numbers $$$g, s, b$$$ \u2014 the possible number of gold, silver and bronze medals, respectively. The sum of $$$g+s+b$$$ should be the maximum possible. If there are several answers, print any of them. ", "sample_inputs": ["5\n12\n5 4 4 3 2 2 1 1 1 1 1 1\n4\n4 3 2 1\n1\n1000000\n20\n20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1\n32\n64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11"], "sample_outputs": ["1 2 3\n0 0 0\n0 0 0\n2 5 3\n2 6 6"], "notes": "NoteIn the first test case, it is possible to reward $$$1$$$ gold, $$$2$$$ silver and $$$3$$$ bronze medals. In this case, the participant solved $$$5$$$ tasks will be rewarded with the gold medal, participants solved $$$4$$$ tasks will be rewarded with silver medals, participants solved $$$2$$$ or $$$3$$$ tasks will be rewarded with bronze medals. Participants solved exactly $$$1$$$ task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than $$$6$$$ medals because the number of medals should not exceed half of the number of participants. The answer $$$1$$$, $$$3$$$, $$$2$$$ is also correct in this test case.In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val N = ni()\n val P = na(N)\n val med = N / 2\n var g, s, b = 0\n var state = 0\n REP(N / 2) { i =>\n if (i > 0 && P(i) != P(i - 1)) {\n state = state match {\n case 0 => 1\n case 1 if g < s => 2\n case 1 if g >= s => 1\n case 2 => 2\n }\n }\n state match {\n case 0 => g += 1\n case 1 => s += 1\n case 2 => if (P(i) > P(med)) b += 1\n }\n }\n if (g > 0 && s > 0 && b > 0 && g < s && g < b) {\n out.println(s\"$g $s $b\")\n } else {\n out.println(\"0 0 0\")\n }\n }\n }\n}"}], "negative_code": [], "src_uid": "cff809c3d5682e6b3e71b525c5f8f8b4"} {"nl": {"description": "You are given an integer $$$n$$$. In $$$1$$$ move, you can do one of the following actions: erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is \"empty\"); add one digit to the right. The actions may be performed in any order any number of times.Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number $$$301$$$ the digit $$$3$$$, the result is the number $$$01$$$ (not $$$1$$$).You need to perform the minimum number of actions to make the number any power of $$$2$$$ (i.e. there's an integer $$$k$$$ ($$$k \\ge 0$$$) such that the resulting number is equal to $$$2^k$$$). The resulting number must not have leading zeroes.E.g. consider $$$n=1052$$$. The answer is equal to $$$2$$$. First, let's add to the right one digit $$$4$$$ (the result will be $$$10524$$$). Then let's erase the digit $$$5$$$, so the result will be $$$1024$$$ which is a power of $$$2$$$.E.g. consider $$$n=8888$$$. The answer is equal to $$$3$$$. Let's erase any of the digits $$$8$$$ three times. The result will be $$$8$$$ which is a power of $$$2$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$).", "output_spec": "For each test case, output in a separate line one integer $$$m$$$ \u2014 the minimum number of moves to transform the number into any power of $$$2$$$.", "sample_inputs": ["12\n1052\n8888\n6\n75\n128\n1\n301\n12048\n1504\n6656\n1000000000\n687194767"], "sample_outputs": ["2\n3\n1\n3\n0\n0\n2\n1\n3\n4\n9\n2"], "notes": "NoteThe answer for the first test case was considered above.The answer for the second test case was considered above.In the third test case, it's enough to add to the right the digit $$$4$$$ \u2014 the number $$$6$$$ will turn into $$$64$$$.In the fourth test case, let's add to the right the digit $$$8$$$ and then erase $$$7$$$ and $$$5$$$ \u2014 the taken number will turn into $$$8$$$.The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move.In the seventh test case, you can delete first of all the digit $$$3$$$ (the result is $$$01$$$) and then the digit $$$0$$$ (the result is $$$1$$$)."}, "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 transform(a: Array[Char], b: Array[Char]): Int = {\r\n var i = 0\r\n var j = 0\r\n\r\n var c = 0\r\n while (i < a.length) {\r\n while (j < b.length && a(i) != b(j)) {\r\n j += 1\r\n c += 1\r\n }\r\n if (j < b.length) {\r\n i += 1\r\n j += 1\r\n if (j == b.length)\r\n return c + a.length - i\r\n } else return c + a.length - i\r\n }\r\n c + b.length - j\r\n }\r\n\r\n def solve(t: Int = 0): Unit = {\r\n val n = reader.next().toCharArray\r\n var min = Int.MaxValue\r\n //var rs: Array[Char] = null\r\n for (num <- f) {\r\n //val c = transform(num, n)\r\n /*if (min > c)\r\n rs = num*/\r\n min = Math.min(min, transform(num, n))\r\n }\r\n //println(rs.mkString)\r\n writer.println(min)\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[Array[Char]](101)\r\n def main(args: Array[String]) {\r\n for (i <- 0 to 100)\r\n f(i) = (1L << i).toString.toCharArray\r\n multiTest(solve)\r\n //solve()\r\n writer.flush()\r\n //println(transform(2.toString.toCharArray, 1052.toString.toCharArray))\r\n }\r\n}"}], "negative_code": [], "src_uid": "728e0e5e5d8350a2b79e6a4b5bef407b"} {"nl": {"description": "You are given a sequence of positive integers a1,\u2009a2,\u2009...,\u2009an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).", "input_spec": "The first line contains the integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains elements of the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000). All the elements are positive integers.", "output_spec": "Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n. If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.", "sample_inputs": ["5\n1 2 3 4 5", "4\n50 50 50 50"], "sample_outputs": ["1\n3", "4\n1 2 3 4"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1\u2009\u2264\u2009i\u2009\u2264\u20094n) is placed at some position (xi,\u2009yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai,\u2009bi). Moving this mole one time means rotating his position point (xi,\u2009yi) 90 degrees counter-clockwise around it's home point (ai,\u2009bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi (\u2009-\u2009104\u2009\u2264\u2009xi,\u2009yi,\u2009ai,\u2009bi\u2009\u2264\u2009104).", "output_spec": "Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print \"-1\" (without quotes).", "sample_inputs": ["4\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-2 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n-1 1 0 0\n2 2 0 1\n-1 0 0 -2\n3 0 0 -2\n-1 1 -2 0"], "sample_outputs": ["1\n-1\n3\n3"], "notes": "NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole."}, "positive_code": [{"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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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) // \u4e2d\u5fc3\u304b\u3089\u306e\u76f8\u5bfe\u4f4d\u7f6e\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 // \uff12\u4e57\u306e\u5f62\u3092\u7dad\u6301\u3059\u308b\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) // \u4e2d\u5fc3\u304b\u3089\u306e\u76f8\u5bfe\u4f4d\u7f6e\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 // \uff12\u4e57\u306e\u5f62\u3092\u7dad\u6301\u3059\u308b\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) // \u4e2d\u5fc3\u304b\u3089\u306e\u76f8\u5bfe\u4f4d\u7f6e\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 // \uff12\u4e57\u306e\u5f62\u3092\u7dad\u6301\u3059\u308b\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"} {"nl": {"description": "Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations. The total number of stations equals to n. One can fuel the car at the i-th station with no more than ai liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the 1-st and the 2-nd station is b1 kilometers, the distance between the 2-nd and the 3-rd one is b2 kilometers, ..., between the (n\u2009-\u20091)-th and the n-th ones the distance is bn\u2009-\u20091 kilometers and between the n-th and the 1-st one the distance is bn kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all ai is equal to the sum of all bi. The i-th gas station and i-th post office are very close, so the distance between them is 0 kilometers.Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers ai \u2014 amount of gasoline on the i-th station. The third line contains n integers b1,\u2009b2,\u2009...,\u2009bn. They are the distances between the 1-st and the 2-nd gas stations, between the 2-nd and the 3-rd ones, ..., between the n-th and the 1-st ones, respectively. The sum of all bi equals to the sum of all ai and is no more than 109. Each of the numbers ai, bi is no less than 1 and no more than 109.", "output_spec": "Print on the first line the number k \u2014 the number of possible post offices, from which the car can drive one circle along a circular road. Print on the second line k numbers in the ascending order \u2014 the numbers of offices, from which the car can start.", "sample_inputs": ["4\n1 7 2 3\n8 1 1 3", "8\n1 2 1 2 1 2 1 2\n2 1 2 1 2 1 2 1"], "sample_outputs": ["2\n2 4", "8\n1 2 3 4 5 6 7 8"], "notes": null}, "positive_code": [{"source_code": "object P066E extends App {\n def ps(a:List[Int])={\n a.scan(0)(_+_).drop(1)\n }\n def calc(a:List[Int], b:List[Int], n:Int):Set[Int] = {\n val c = (ps(a) zip ps(b)).map(x=>x._1-x._2)\n val x = c.min\n val d = c.zipWithIndex.filter(_._1==x).map(x=>(x._2+1)%n)\n return d.toSet\n }\n\n val n = readInt\n val a = readLine.split(' ').map(_.toInt).toList\n val b = readLine.split(' ').map(_.toInt).toList\n val s1 = calc(a, b, n)\n val s2 = calc(a.reverse, (b.takeRight(1):::b.take(n-1)).reverse, n).map(x=>n-1-x)\n val s = s1.union(s2).map(x=>x+1)\n println(s.size)\n println(s.toArray.sorted.deep.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "cc928c02b337f2b5ad7aed37bb83d139"} {"nl": {"description": "After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.For every ball print the number of the basket where it will go according to Valeric's scheme.Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.", "input_spec": "The first line contains two space-separated integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of balls and baskets, correspondingly.", "output_spec": "Print n numbers, one per line. The i-th line must contain the number of the basket for the i-th ball.", "sample_inputs": ["4 3", "3 1"], "sample_outputs": ["2\n1\n3\n2", "1\n1\n1"], "notes": null}, "positive_code": [{"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\t val n, m = scanner.nextInt()\n\t\t val ansList = List.iterate ((m + 1) / 2, m) { i =>\n\t\t\t if (i <= m / 2) m - i + 1 else m - i\n\t\t }\n\t\t val ans = ansList.toArray\n\t\t for (i <- 0 to n-1) {\n\t\t\t println (ans(i%m))\n\t\t }\n }\n\n}\n"}], "negative_code": [{"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\t val n, m = scanner.nextInt()\n\t\t val ansList = List.iterate ((m + 1) / 2, m) { i =>\n\t\t \t val even = m % 2 == 0\n\t\t\t val big = i > m / 2\n\t\t\t if (even == big) m - i + 1 else m - i\n\t\t }\n\t\t val ans = ansList.toArray\n\t\t for (i <- 0 to n-1) {\n\t\t\t println (ans(i%m))\n\t\t }\n }\n\n}\n"}], "src_uid": "907893a0a78a7444d26bdd793d9c7499"} {"nl": {"description": "There always is something to choose from! And now, instead of \"Noughts and Crosses\", Inna choose a very unusual upgrade of this game. The rules of the game are given below:There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: \"X\" or \"O\". Then the player chooses two positive integers a and b (a\u00b7b\u2009=\u200912), after that he makes a table of size a\u2009\u00d7\u2009b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters \"X\" on all cards. Otherwise, the player loses.Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a,\u2009b that she can choose and win.", "input_spec": "The first line of the input contains integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line. The description of each test is a string consisting of 12 characters, each character is either \"X\", or \"O\". The i-th character of the string shows the character that is written on the i-th card from the start.", "output_spec": "For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a,\u2009b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.", "sample_inputs": ["4\nOXXXOXOOXOOX\nOXOXOXOXOXOX\nXXXXXXXXXXXX\nOOOOOOOOOOOO"], "sample_outputs": ["3 1x12 2x6 4x3\n4 1x12 2x6 3x4 6x2\n6 1x12 2x6 3x4 4x3 6x2 12x1\n0"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $$$a$$$ to make it a good array. Recall that the prefix of the array $$$a=[a_1, a_2, \\dots, a_n]$$$ is a subarray consisting several first elements: the prefix of the array $$$a$$$ of length $$$k$$$ is the array $$$[a_1, a_2, \\dots, a_k]$$$ ($$$0 \\le k \\le n$$$).The array $$$b$$$ of length $$$m$$$ is called good, if you can obtain a non-decreasing array $$$c$$$ ($$$c_1 \\le c_2 \\le \\dots \\le c_{m}$$$) from it, repeating the following operation $$$m$$$ times (initially, $$$c$$$ is empty): select either the first or the last element of $$$b$$$, remove it from $$$b$$$, and append it to the end of the array $$$c$$$. For example, if we do $$$4$$$ operations: take $$$b_1$$$, then $$$b_{m}$$$, then $$$b_{m-1}$$$ and at last $$$b_2$$$, then $$$b$$$ becomes $$$[b_3, b_4, \\dots, b_{m-3}]$$$ and $$$c =[b_1, b_{m}, b_{m-1}, b_2]$$$.Consider the following example: $$$b = [1, 2, 3, 4, 4, 2, 1]$$$. This array is good because we can obtain non-decreasing array $$$c$$$ from it by the following sequence of operations: take the first element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2, 1]$$$, $$$c = [1]$$$; take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2]$$$, $$$c = [1, 1]$$$; take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4]$$$, $$$c = [1, 1, 2]$$$; take the first element of $$$b$$$, so $$$b = [3, 4, 4]$$$, $$$c = [1, 1, 2, 2]$$$; take the first element of $$$b$$$, so $$$b = [4, 4]$$$, $$$c = [1, 1, 2, 2, 3]$$$; take the last element of $$$b$$$, so $$$b = [4]$$$, $$$c = [1, 1, 2, 2, 3, 4]$$$; take the only element of $$$b$$$, so $$$b = []$$$, $$$c = [1, 1, 2, 2, 3, 4, 4]$$$\u00a0\u2014 $$$c$$$ is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of $$$a$$$ to delete (erase), to make $$$a$$$ to be a good array. Note that the required length can be $$$0$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: the length of the shortest prefix of elements you need to erase from $$$a$$$ to make it a good array.", "sample_inputs": ["5\n4\n1 2 3 4\n7\n4 3 3 8 4 5 2\n3\n1 1 1\n7\n1 3 1 4 5 3 2\n5\n5 4 3 2 3"], "sample_outputs": ["0\n4\n0\n2\n3"], "notes": "NoteIn the first test case of the example, the array $$$a$$$ is already good, so we don't need to erase any prefix.In the second test case of the example, the initial array $$$a$$$ is not good. Let's erase first $$$4$$$ elements of $$$a$$$, the result is $$$[4, 5, 2]$$$. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good."}, "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"}, {"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"}], "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"} {"nl": {"description": "You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \\le |a_{2} - a_{3}| \\le \\ldots \\le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \\le n \\le 10^{5}$$$)\u00a0\u2014 the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$ ($$$-10^{9} \\le a_{i} \\le 10^{9}$$$).", "output_spec": "For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.", "sample_inputs": ["2\n6\n5 -2 4 8 6 5\n4\n8 1 4 2"], "sample_outputs": ["5 5 4 6 8 -2\n1 2 4 8"], "notes": "NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \\le |a_{2} - a_{3}| = 1 \\le |a_{3} - a_{4}| = 2 \\le |a_{4} - a_{5}| = 2 \\le |a_{5} - a_{6}| = 10$$$. There are other possible answers like \"5 4 5 6 -2 8\".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \\le |a_{2} - a_{3}| = 2 \\le |a_{3} - a_{4}| = 4$$$. There are other possible answers like \"2 4 8 1\"."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third\u00a0\u2014 at time $$$2 \\cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second\u00a0\u2014 at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.", "input_spec": "The first line contains a single integer $$$k$$$ ($$$1 \\le k \\le 1000$$$)\u00a0\u2014 the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \\le n, x, t \\le 2 \\cdot 10^9$$$)\u00a0\u2014 the number of participants, the start interval and the contest duration.", "output_spec": "Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case.", "sample_inputs": ["4\n4 2 5\n3 1 2\n3 3 10\n2000000000 1 2000000000"], "sample_outputs": ["5\n3\n3\n1999999999000000000"], "notes": "NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest."}, "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n /** Dissatisfaction equals to the number of participants that\r\n * started the contest (or starting it now), but haven't yet\r\n * finished it.\r\n *\r\n * @param n The number of participants\r\n * @param x The start interval\r\n * @param t The contest duration\r\n */\r\n private def dissatisfaction(n: Int, x: Int, t: Int): Long = {\r\n // 1. \u0420\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0432\u0441\u0435 i \u0442\u0430\u043a\u0438\u0435, \u0447\u0442\u043e i * x + t <= (n-1) * x\r\n // i + t/x <= n - 1\r\n // i <= n - 1 - t/x\r\n // i \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 [1, n - 1 - t/x], \u0430 \u0437\u043d\u0430\u0447\u0438\u0442 \u0442\u0430\u043a\u0438\u0445 i \u0440\u043e\u0432\u043d\u043e min(0, n - t/x)\r\n // (i + m) * x <= i * x + t\r\n // i + m <= i + t/x\r\n // m <= t/x, \u0430 \u0437\u043d\u0430\u0447\u0438\u0442 m \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 [1, t/x]\r\n // \u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u043f\u043e\u043b\u0443\u0447\u0438\u043c max(0, n - t/x) * t/x\r\n // 2. \u0412 \u0441\u043b\u0443\u0447\u0430\u0435, \u043a\u043e\u0433\u0434\u0430 (n - 1) * x \u043f\u043e\u043f\u0430\u0434\u0430\u0435\u0442 \u0432 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b [i * x, i * x + t]\r\n // \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c, \u0447\u0442\u043e m \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 n - 1 - i, \u0442.\u0435. 0, 1, 2, ..., (t/x - 1)\r\n // \u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u043f\u043e\u043b\u0443\u0447\u0438\u043c t/x * (t/x - 1) / 2\r\n val d = (t / x).toLong\r\n d * 0L.max(n - d) + d.min(n) * (d.min(n) - 1L) / 2L\r\n }\r\n\r\n val k = readInt()\r\n\r\n (0 until k).foreach { _ =>\r\n val Array(n, x, t) = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = dissatisfaction(n, x, t)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n /** Dissatisfaction equals to the number of participants that\r\n * started the contest (or starting it now), but haven't yet\r\n * finished it.\r\n *\r\n * @param n The number of participants\r\n * @param x The start interval\r\n * @param t The contest duration\r\n */\r\n private def dissatisfaction(n: Int, x: Int, t: Int): Long = {\r\n // 1. \u0420\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0432\u0441\u0435 i \u0442\u0430\u043a\u0438\u0435, \u0447\u0442\u043e i * x + t <= (n-1) * x\r\n // i + t/x <= n - 1\r\n // i <= n - 1 - t/x\r\n // i \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 [1, n - 1 - t/x], \u0430 \u0437\u043d\u0430\u0447\u0438\u0442 \u0442\u0430\u043a\u0438\u0445 i \u0440\u043e\u0432\u043d\u043e min(0, n - t/x)\r\n // (i + m) * x <= i * x + t\r\n // i + m <= i + t/x\r\n // m <= t/x, \u0430 \u0437\u043d\u0430\u0447\u0438\u0442 m \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 [1, t/x]\r\n // \u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u043f\u043e\u043b\u0443\u0447\u0438\u043c max(0, n - t/x) * t/x\r\n // 2. \u0412 \u0441\u043b\u0443\u0447\u0430\u0435, \u043a\u043e\u0433\u0434\u0430 (n - 1) * x \u043f\u043e\u043f\u0430\u0434\u0430\u0435\u0442 \u0432 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b [i * x, i * x + t]\r\n // \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c, \u0447\u0442\u043e m \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 n - 1 - i, \u0442.\u0435. 0, 1, 2, ..., (t/x - 1)\r\n // \u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u043f\u043e\u043b\u0443\u0447\u0438\u043c t/x * (t/x - 1) / 2\r\n val d = (t / x).toLong\r\n d * 0L.max(n - d) + d * (d - 1L) / 2L\r\n }\r\n\r\n val k = readInt()\r\n\r\n (0 until k).foreach { _ =>\r\n val Array(n, x, t) = readLine().split(\" \").map(_.toInt)\r\n\r\n val ans = dissatisfaction(n, x, t)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "4df38c9b42b0f0963a121829080d3571"} {"nl": {"description": "During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.For a given list of pairs of integers $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ their WCD is arbitrary integer greater than $$$1$$$, such that it divides at least one element in each pair. WCD may not exist for some lists.For example, if the list looks like $$$[(12, 15), (25, 18), (10, 24)]$$$, then their WCD can be equal to $$$2$$$, $$$3$$$, $$$5$$$ or $$$6$$$ (each of these numbers is strictly greater than $$$1$$$ and divides at least one number in each pair).You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 150\\,000$$$)\u00a0\u2014 the number of pairs. Each of the next $$$n$$$ lines contains two integer values $$$a_i$$$, $$$b_i$$$ ($$$2 \\le a_i, b_i \\le 2 \\cdot 10^9$$$).", "output_spec": "Print a single integer\u00a0\u2014 the WCD of the set of pairs. If there are multiple possible answers, output any; if there is no answer, print $$$-1$$$.", "sample_inputs": ["3\n17 18\n15 24\n12 15", "2\n10 16\n7 17", "5\n90 108\n45 105\n75 40\n165 175\n33 30"], "sample_outputs": ["6", "-1", "5"], "notes": "NoteIn the first example the answer is $$$6$$$ since it divides $$$18$$$ from the first pair, $$$24$$$ from the second and $$$12$$$ from the third ones. Note that other valid answers will also be accepted.In the second example there are no integers greater than $$$1$$$ satisfying the conditions.In the third example one of the possible answers is $$$5$$$. Note that, for example, $$$15$$$ is also allowed, but it's not necessary to maximize the output."}, "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 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"}, {"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"} {"nl": {"description": "Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days. ", "input_spec": "In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200\u2009000 characters.", "output_spec": "If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009|s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1\u2009\u2264\u2009li\u2009\u2264\u2009|s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.", "sample_inputs": ["0010100", "111"], "sample_outputs": ["3\n3 1 3 4\n3 2 5 6\n1 7", "-1"], "notes": null}, "positive_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\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"}, {"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": "\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"}], "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"} {"nl": {"description": "Vivek has encountered a problem. He has a maze that can be represented as an $$$n \\times m$$$ grid. Each of the grid cells may represent the following: Empty\u00a0\u2014 '.' Wall\u00a0\u2014 '#' Good person \u00a0\u2014 'G' Bad person\u00a0\u2014 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.", "input_spec": "The first line contains one integer $$$t$$$ $$$(1 \\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \\le n, m \\le 50)$$$\u00a0\u2014 the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.", "output_spec": "For each test case, print \"Yes\" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print \"No\" You may print every letter in any case (upper or lower).", "sample_inputs": ["6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB."], "sample_outputs": ["Yes\nYes\nNo\nNo\nYes\nYes"], "notes": "NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$."}, "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(_ => 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"}, {"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"} {"nl": {"description": "Martians are actively engaged in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight from faraway planets, Martians need fast spaceships.A group of scientists conducts experiments to build a fast engine for the new spaceship. In the current experiment, there are $$$n$$$ elementary particles, the $$$i$$$-th of them has type $$$a_i$$$.Denote a subsegment of the particle sequence ($$$a_1, a_2, \\dots, a_n$$$) as a sequence ($$$a_l, a_{l+1}, \\dots, a_r$$$) for some left bound $$$l$$$ and right bound $$$r$$$ ($$$1 \\le l \\le r \\le n$$$). For instance, the sequence $$$(1\\ 4\\ 2\\ 8\\ 5\\ 7)$$$ for $$$l=2$$$ and $$$r=4$$$ has the sequence $$$(4\\ 2\\ 8)$$$ as a subsegment. Two subsegments are considered different if at least one bound of those subsegments differs.Note that the subsegments can be equal as sequences but still considered different. For example, consider the sequence $$$(1\\ 1\\ 1\\ 1\\ 1)$$$ and two of its subsegments: one with $$$l=1$$$ and $$$r=3$$$ and another with $$$l=2$$$ and $$$r=4$$$. Both subsegments are equal to $$$(1\\ 1\\ 1)$$$, but still considered different, as their left and right bounds differ.The scientists want to conduct a reaction to get two different subsegments of the same length. Denote this length $$$k$$$. The resulting pair of subsegments must be harmonious, i.\u00a0e. for some $$$i$$$ ($$$1 \\le i \\le k$$$) it must be true that the types of particles on the $$$i$$$-th position are the same for these two subsegments. For example, the pair $$$(1\\ 7\\ 3)$$$ and $$$(4\\ 7\\ 8)$$$ is harmonious, as both subsegments have $$$7$$$ on the second position. The pair $$$(1\\ 2\\ 3)$$$ and $$$(3\\ 1\\ 2)$$$ is not harmonious.The longer are harmonious subsegments, the more chances for the scientists to design a fast engine. So, they asked you to calculate the maximal possible length of harmonious pair made of different subsegments.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The following are descriptions of the test cases. The first line contains an integer $$$n$$$ ($$$2 \\le n \\le 150\\,000$$$) \u2014 the amount of elementary particles in the sequence. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 150\\,000$$$) \u2014 types of elementary particles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\\cdot10^5$$$.", "output_spec": "For each test, print a single integer, maximal possible length of harmonious pair made of different subsegments. If such pair does not exist, print $$$-1$$$ instead.", "sample_inputs": ["4\n7\n3 1 5 2 1 3 4\n6\n1 1 1 1 1 1\n6\n1 4 2 8 5 7\n2\n15 15"], "sample_outputs": ["4\n5\n-1\n1"], "notes": "NoteThe first test case is shown on the picture below: As you can see from it, you may choose the subsegments $$$(2\\ 1\\ 3\\ 4)$$$ and $$$(3\\ 1\\ 5\\ 2)$$$, which are a harmonious pair. Their length is equal to $$$4$$$, so the answer is $$$4$$$.In the second test case, you need to take two subsegments: one with $$$l=1$$$ and $$$r=5$$$, and one with $$$l=2$$$ and $$$r=6$$$. It's not hard to observe that these segments are a harmonious pair and considered different even though they are both equal to $$$(1\\ 1\\ 1\\ 1\\ 1)$$$.In the third test case, you cannot make a harmonious pair, so the answer is $$$-1$$$."}, "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 c: Long)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 val po = new Array[Int](maxn)\n\n\n for (tt <- 1 to t) {\n val n = readInt()\n var ans = -1\n var a = 0\n for (i <- 1 to 150000) {\n po(i) = 0\n }\n for (i <- 1 to n) {\n a = readInt()\n if (po(a) != 0) {\n ans = max(ans, po(a) + n - i)\n }\n po(a) = i\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}"}], "negative_code": [], "src_uid": "7ac5f084c403bd26802e1b941105d34b"} {"nl": {"description": "Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R\u2009\u00d7\u2009C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. ", "input_spec": "First line contains two integers R (1\u2009\u2264\u2009R\u2009\u2264\u2009500) and C (1\u2009\u2264\u2009C\u2009\u2264\u2009500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.", "output_spec": "If it is impossible to protect all sheep, output a single line with the word \"No\". Otherwise, output a line with the word \"Yes\". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.", "sample_inputs": ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."], "sample_outputs": ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."], "notes": "NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him."}, "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"}, {"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"}], "negative_code": [], "src_uid": "f55c824d8db327e531499ced6c843102"} {"nl": {"description": "User ainta loves to play with cards. He has a cards containing letter \"o\" and b cards containing letter \"x\". He arranges the cards in a row, and calculates the score of the deck by the formula below. At first, the score is 0. For each block of contiguous \"o\"s with length x the score increases by x2. For each block of contiguous \"x\"s with length y the score decreases by y2. \u00a0For example, if a\u2009=\u20096,\u2009b\u2009=\u20093 and ainta have arranged the cards in the order, that is described by string \"ooxoooxxo\", the score of the deck equals 22\u2009-\u200912\u2009+\u200932\u2009-\u200922\u2009+\u200912\u2009=\u20099. That is because the deck has 5 blocks in total: \"oo\", \"x\", \"ooo\", \"xx\", \"o\".User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.", "input_spec": "The first line contains two space-separated integers a and b (0\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009105;\u00a0a\u2009+\u2009b\u2009\u2265\u20091) \u2014 the number of \"o\" cards and the number of \"x\" cards.", "output_spec": "In the first line print a single integer v \u2014 the maximum score that ainta can obtain. In the second line print a\u2009+\u2009b characters describing the deck. If the k-th card of the deck contains \"o\", the k-th character must be \"o\". If the k-th card of the deck contains \"x\", the k-th character must be \"x\". The number of \"o\" characters must be equal to a, and the number of \"x \" characters must be equal to b. If there are many ways to maximize v, print any. Please, do not write the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["2 3", "4 0", "0 4"], "sample_outputs": ["-1\nxoxox", "16\noooo", "-16\nxxxx"], "notes": null}, "positive_code": [{"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 java.util.StringTokenizer(readLine)\n tokenizer.nextToken\n }\n\n val a = readToken.toInt\n val b = readToken.toInt\n var bestA, bestB = 0\n var bestVal: Long = -(1L << 60)\n\n def getBestA(n: Int): Long = {\n val head = a - n + 1\n head.toLong * head + n - 1\n }\n\n def getBestB(n: Int): Long = {\n val small = (b / n).toLong\n val big = small + 1\n val bigCount = b % n\n val smallCount = n - bigCount\n big * big * bigCount + small * small * smallCount\n }\n\n def genAnswerString() = {\n val s = new StringBuilder\n val head = a - bestA + 1\n val small = b / bestB\n val big = small + 1\n val bigCount = b % bestB\n\n var i = 0\n var j = 0\n var flag = 0\n if (bestB > bestA) flag = 1\n\n while (i < bestA || j < bestB) {\n flag match {\n case 0 =>\n if (i == 0) {\n s ++= \"o\" * head\n } else {\n s += 'o'\n }\n i += 1\n case 1 =>\n if (j < bigCount) {\n s ++= \"x\" * big\n } else {\n s ++= \"x\" * small\n }\n j += 1\n }\n flag = 1 - flag\n }\n s\n }\n\n def check(i: Int, j: Int) {\n if (1 <= j && j <= b) {\n val v = getBestA(i) - getBestB(j)\n //println(i, j, v)\n if (v > bestVal) {\n bestVal = v\n bestA = i\n bestB = j\n }\n }\n }\n\n def main(args: Array[String]) {\n if (a == 0) {\n println(-b.toLong * b)\n println(\"x\" * b)\n return\n }\n\n if (b == 0) {\n println(a.toLong * a)\n println(\"o\" * a)\n return\n }\n\n for (i <- 1 to a) {\n check(i, i - 1)\n check(i, i)\n check(i, i + 1)\n }\n println(bestVal)\n println(genAnswerString)\n }\n}"}], "negative_code": [{"source_code": "import java.util\n\nobject Main {\n def main(args: Array[String]) {\n val a = Array(10, 20)\n val b = Array(100, 200)\n println(a ++ b)\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"}], "src_uid": "c9785cd72988c80b72c3d09691e8db6c"} {"nl": {"description": "Given an integer $$$n$$$, find the maximum value of integer $$$k$$$ such that the following condition holds: $$$n$$$ & ($$$n-1$$$) & ($$$n-2$$$) & ($$$n-3$$$) & ... ($$$k$$$) = $$$0$$$ where & denotes the bitwise AND operation.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 3 \\cdot 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$).", "output_spec": "For each test case, output a single integer \u2014 the required integer $$$k$$$.", "sample_inputs": ["3\n2\n5\n17"], "sample_outputs": ["1\n3\n15"], "notes": "NoteIn the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0. $$$5 \\, \\& \\, 4 \\neq 0$$$, $$$5 \\, \\& \\, 4 \\, \\& \\, 3 = 0$$$. Hence, 3 is the answer."}, "positive_code": [{"source_code": "import scala.annotation.tailrec\nimport scala.io.StdIn\nobject CF1527A {\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt\n val list = List.fill(t)(0).map(_ => StdIn.readInt);\n @tailrec\n def bitLength(i: Int = 0, n: Int): Int = {\n if (n < 2) i\n else bitLength(i + 1, n / 2);\n }\n val bl: (Int => Int) = bitLength(0, _)\n @tailrec\n def bitMax(i: Int, acc: Int = 1): Int = {\n if (i <= 0) acc\n else bitMax(i - 1, acc * 2);\n }\n val bm: (Int => Int) = bitMax(_, 1) - 1\n println(list.map(bl).map(bm).mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [], "src_uid": "9b4a8bc76d634935f6a1438e8a93a781"} {"nl": {"description": "The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.The Berland capital's map is represented by an n\u2009\u00d7\u2009m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map. Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.", "input_spec": "The first line contains two space-separated integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of rows and columns in the table, correspondingly. Each of the next n lines contains m characters \u2014 the description of the capital's map. Each character can either be a \".\" (dot), or an \"*\" (asterisk). A character equals \"*\" if the corresponding district has been robbed. Otherwise, it equals \".\". It is guaranteed that the map has exactly three characters \"*\" and we can always find the fourth district that meets the problem requirements. ", "output_spec": "Print two integers \u2014 the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.", "sample_inputs": ["3 2\n.*\n..\n**", "3 3\n*.*\n*..\n..."], "sample_outputs": ["1 1", "2 3"], "notes": null}, "positive_code": [{"source_code": "object SeriesofCrimes181A extends App {\n\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\n val city = (1 to n).map(_ => scanner.next).toArray\n\n val rowOnly1Asterisk = (city.zipWithIndex filter {case (s,_) => s.filter(_ == '*').length==1}).head._2 + 1\n val rowsWithAsterisk = city.filter(_.filter(_ == '*').length>=1)\n val row1 = rowsWithAsterisk.head\n val row2 = rowsWithAsterisk.tail.head\n\n val colOnly1Asterisk = row1.zip(row2).zipWithIndex.filter{\n case (('*','.'),_) => true\n case (('.','*'),_) => true\n case _ => false\n\n }.head._2 + 1\n out.println(s\"$rowOnly1Asterisk $colOnly1Asterisk\")\n\n }\n}"}], "negative_code": [], "src_uid": "e344de8280fb607c556671db9cfbaa9e"} {"nl": {"description": "Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.", "input_spec": "The first line contains two integers n and m \u2014 the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b \u2014 the numbers of students tied by the i-th lace (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n,\u2009a\u2009\u2260\u2009b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.", "output_spec": "Print the single number \u2014 the number of groups of students that will be kicked out from the club.", "sample_inputs": ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"], "sample_outputs": ["0", "2", "1"], "notes": "NoteIn the first sample Anna and Maria won't kick out any group of students \u2014 in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then \u2014 two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one."}, "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 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}"}, {"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"} {"nl": {"description": "Given a string $$$s$$$ of length $$$n$$$ and integer $$$k$$$ ($$$1 \\le k \\le n$$$). The string $$$s$$$ has a level $$$x$$$, if $$$x$$$ is largest non-negative integer, such that it's possible to find in $$$s$$$: $$$x$$$ non-intersecting (non-overlapping) substrings of length $$$k$$$, all characters of these $$$x$$$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $$$i$$$ and $$$j$$$ ($$$1 \\le i \\le j \\le n$$$), denoted as $$$s[i \\dots j]$$$ = \"$$$s_{i}s_{i+1} \\dots s_{j}$$$\".For example, if $$$k = 2$$$, then: the string \"aabb\" has level $$$1$$$ (you can select substring \"aa\"), the strings \"zzzz\" and \"zzbzz\" has level $$$2$$$ (you can select two non-intersecting substrings \"zz\" in each of them), the strings \"abed\" and \"aca\" have level $$$0$$$ (you can't find at least one substring of the length $$$k=2$$$ containing the only distinct character). Zuhair gave you the integer $$$k$$$ and the string $$$s$$$ of length $$$n$$$. You need to find $$$x$$$, the level of the string $$$s$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the string and the value of $$$k$$$. The second line contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.", "output_spec": "Print a single integer $$$x$$$\u00a0\u2014 the level of the string.", "sample_inputs": ["8 2\naaacaabb", "2 1\nab", "4 2\nabab"], "sample_outputs": ["2", "1", "0"], "notes": "NoteIn the first example, we can select $$$2$$$ non-intersecting substrings consisting of letter 'a': \"(aa)ac(aa)bb\", so the level is $$$2$$$.In the second example, we can select either substring \"a\" or \"b\" to get the answer $$$1$$$."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "6c71c828553e43c699237211005873e5"} {"nl": {"description": "One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.", "input_spec": "The first input line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.", "output_spec": "Print a single integer \u2014 the number of problems the friends will implement on the contest.", "sample_inputs": ["3\n1 1 0\n1 1 1\n1 0 0", "2\n1 0 0\n0 1 1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution."}, "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 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": "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": "\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}"}, {"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 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": "\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.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}"}, {"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"}], "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"} {"nl": {"description": "Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.", "input_spec": "The first line contains three integers: n,\u2009s,\u2009t (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009s,\u2009t\u2009\u2264\u2009n) \u2014 the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 the shuffling operation parameters. It is guaranteed that all pi's are distinct. Note that s can equal t.", "output_spec": "If the marble can move from position s to position t, then print on a single line a non-negative integer \u2014 the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.", "sample_inputs": ["4 2 1\n2 3 4 1", "4 3 3\n4 1 3 2", "4 3 4\n1 2 3 4", "3 1 3\n2 1 3"], "sample_outputs": ["3", "0", "-1", "-1"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "b01602b51b9103c0f31c3f50b32aa88d"} {"nl": {"description": "Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$. \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 2. Shoot the cannon in the row $$$2$$$. \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1\u00a0\u2014 the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.", "output_spec": "For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.", "sample_inputs": ["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Vasya has found a piece of paper with an array written on it. The array consists of n integers a1,\u2009a2,\u2009...,\u2009an. Vasya noticed that the following condition holds for the array ai\u2009\u2264\u2009ai\u2009+\u20091\u2009\u2264\u20092\u00b7ai for any positive integer i (i\u2009<\u2009n).Vasya wants to add either a \"+\" or a \"-\" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs \"+\" and \"-\" before each number so that the value of expression s meets the limits 0\u2009\u2264\u2009s\u2009\u2264\u2009a1. Print a sequence of signs \"+\" and \"-\", satisfying the given limits. It is guaranteed that the solution for the problem exists.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the array. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the original array. It is guaranteed that the condition ai\u2009\u2264\u2009ai\u2009+\u20091\u2009\u2264\u20092\u00b7ai fulfills for any positive integer i (i\u2009<\u2009n).", "output_spec": "In a single line print the sequence of n characters \"+\" and \"-\", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0\u2009\u2264\u2009s\u2009\u2264\u2009a1. If there are multiple solutions, you are allowed to print any of them.", "sample_inputs": ["4\n1 2 3 5", "3\n3 3 5"], "sample_outputs": ["+++-", "++-"], "notes": null}, "positive_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: 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 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": "\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"}, {"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"}], "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"} {"nl": {"description": "Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors\u00a0\u2014 1 and k. ", "input_spec": "The only line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000).", "output_spec": "The first line of the output contains a single integer k\u00a0\u2014 maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.", "sample_inputs": ["5", "6"], "sample_outputs": ["2\n2 3", "3\n2 2 2"], "notes": null}, "positive_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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up \u2014 when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le m \\le n \\le 10^5$$$) \u2014 the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le n$$$, all $$$a_i$$$ are unique) \u2014 the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \\le b_i \\le n$$$, all $$$b_i$$$ are unique) \u2014 the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer \u2014 the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.", "sample_inputs": ["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"], "sample_outputs": ["5\n8"], "notes": null}, "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 t = sc.nextInt\n\n (1 to t).foreach(_ => {\n val n = sc.nextInt\n val m = sc.nextInt\n val numMap = mutable.Map[Int, Int]()\n\n (0 until n).foreach(i => {\n val mm = sc.nextInt\n numMap(mm) = i\n })\n\n var max = 0\n\n val ans =\n (0 until m)\n .map(i => {\n val mm = numMap(sc.nextInt)\n\n if (mm <= max) {\n 1\n } else {\n max = mm\n 2 * (mm - i) + 1\n }\n })\n .foldLeft(0L)(_ + _)\n\n println(ans)\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 t = sc.nextInt\n\n (1 to t).foreach(_ => {\n val n = sc.nextInt\n val m = sc.nextInt\n val numMap = mutable.Map[Int, Int]()\n\n (0 until n).foreach(i => {\n val mm = sc.nextInt\n numMap(mm) = i\n })\n\n var max = 0\n\n val ans =\n (0 until m)\n .map(i => {\n val mm = numMap(sc.nextInt)\n\n if (mm <= max) {\n 1\n } else {\n max = mm\n 2 * (mm - i) + 1\n }\n })\n .reduce(_ + _)\n\n println(ans)\n })\n}\n\n"}], "src_uid": "ad434880e047992d2c77e0fe0ce0976f"} {"nl": {"description": "You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n, m \\le 30$$$) \u2014 the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \\le a_{i, j} \\le 1$$$).", "output_spec": "For each test case, print one integer \u2014 the minimum number of cells you have to change so that every path in the matrix is palindromic.", "sample_inputs": ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"], "sample_outputs": ["0\n3\n4\n4"], "notes": "NoteThe resulting matrices in the first three test cases: $$$\\begin{pmatrix} 1 & 1\\\\ 0 & 1 \\end{pmatrix}$$$ $$$\\begin{pmatrix} 0 & 0 & 0\\\\ 0 & 0 & 0 \\end{pmatrix}$$$ $$$\\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \\end{pmatrix}$$$ "}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Array $$$a$$$ contains each odd integer from $$$1$$$ to $$$2n$$$ in an arbitrary order, and array $$$b$$$ contains each even integer from $$$1$$$ to $$$2n$$$ in an arbitrary order.You can perform the following operation on those arrays: choose one of the two arrays pick an index $$$i$$$ from $$$1$$$ to $$$n-1$$$ swap the $$$i$$$-th and the $$$(i+1)$$$-th elements of the chosen array Compute the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$.For two different arrays $$$x$$$ and $$$y$$$ of the same length $$$n$$$, we say that $$$x$$$ is lexicographically smaller than $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, the array $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2n$$$, all $$$a_i$$$ are odd and pairwise distinct) \u2014 array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le 2n$$$, all $$$b_i$$$ are even and pairwise distinct) \u2014 array $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print one integer: the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$. We can show that an answer always exists.", "sample_inputs": ["3\n2\n3 1\n4 2\n3\n5 3 1\n2 4 6\n5\n7 5 9 1 3\n2 4 6 10 8"], "sample_outputs": ["0\n2\n3"], "notes": "NoteIn the first example, the array $$$a$$$ is already lexicographically smaller than array $$$b$$$, so no operations are required.In the second example, we can swap $$$5$$$ and $$$3$$$ and then swap $$$2$$$ and $$$4$$$, which results in $$$[3, 5, 1]$$$ and $$$[4, 2, 6]$$$. Another correct way is to swap $$$3$$$ and $$$1$$$ and then swap $$$5$$$ and $$$1$$$, which results in $$$[1, 5, 3]$$$ and $$$[2, 4, 6]$$$. Yet another correct way is to swap $$$4$$$ and $$$6$$$ and then swap $$$2$$$ and $$$6$$$, which results in $$$[5, 3, 1]$$$ and $$$[6, 2, 4]$$$."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: She will tell you two numbers, l and r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), and you should tell her . Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say \"fuyukai desu\" and then become unhappy.", "input_spec": "The first line contains an integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers: v1,\u2009v2,\u2009...,\u2009vn\u00a0(1\u2009\u2264\u2009vi\u2009\u2264\u2009109) \u2014 costs of the stones. The third line contains an integer m\u00a0(1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009type\u2009\u2264\u20092), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.", "output_spec": "Print m lines. Each line must contain an integer \u2014 the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.", "sample_inputs": ["6\n6 4 2 7 2 7\n3\n2 3 6\n1 3 4\n1 1 6", "4\n5 5 2 3\n10\n1 2 4\n2 1 4\n1 1 1\n2 1 4\n2 1 2\n1 1 1\n1 3 3\n1 1 3\n1 4 4\n1 2 2"], "sample_outputs": ["24\n9\n28", "10\n15\n5\n15\n5\n5\n2\n12\n3\n5"], "notes": "NotePlease note that the answers to the questions may overflow 32-bit integer type."}, "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)\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}"}, {"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"} {"nl": {"description": "Ivan is a novice painter. He has $$$n$$$ dyes of different colors. He also knows exactly $$$m$$$ pairs of colors which harmonize with each other.Ivan also enjoy playing chess. He has $$$5000$$$ rooks. He wants to take $$$k$$$ rooks, paint each of them in one of $$$n$$$ colors and then place this $$$k$$$ rooks on a chessboard of size $$$10^{9} \\times 10^{9}$$$.Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.Ivan wants his arrangement of rooks to have following properties: For any color there is a rook of this color on a board; For any color the set of rooks of this color is connected; For any two different colors $$$a$$$ $$$b$$$ union of set of rooks of color $$$a$$$ and set of rooks of color $$$b$$$ is connected if and only if this two colors harmonize with each other.Please help Ivan find such an arrangement.", "input_spec": "The first line of input contains $$$2$$$ integers $$$n$$$, $$$m$$$ ($$$1 \\le n \\le 100$$$, $$$0 \\le m \\le min(1000, \\,\\, \\frac{n(n-1)}{2})$$$)\u00a0\u2014 number of colors and number of pairs of colors which harmonize with each other. In next $$$m$$$ lines pairs of colors which harmonize with each other are listed. Colors are numbered from $$$1$$$ to $$$n$$$. It is guaranteed that no pair occurs twice in this list.", "output_spec": "Print $$$n$$$ blocks, $$$i$$$-th of them describes rooks of $$$i$$$-th color. In the first line of block print one number $$$a_{i}$$$ ($$$1 \\le a_{i} \\le 5000$$$)\u00a0\u2014 number of rooks of color $$$i$$$. In each of next $$$a_{i}$$$ lines print two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x, \\,\\, y \\le 10^{9}$$$)\u00a0\u2014 coordinates of the next rook. All rooks must be on different cells. Total number of rooks must not exceed $$$5000$$$. It is guaranteed that the solution exists.", "sample_inputs": ["3 2\n1 2\n2 3", "3 3\n1 2\n2 3\n3 1", "3 1\n1 3"], "sample_outputs": ["2\n3 4\n1 4\n4\n1 2\n2 2\n2 4\n5 4\n1\n5 1", "1\n1 1\n1\n1 2\n1\n1 3", "1\n1 1\n1\n2 2\n1\n3 1"], "notes": "NoteRooks arrangements for all three examples (red is color $$$1$$$, green is color $$$2$$$ and blue is color $$$3$$$)."}, "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 P = Array.ofDim[(Int, Int)](M)\n rep(M) { i =>\n val a, b = ni() - 1\n P(i) = (min(a, b), max(a, b))\n }\n\n val ans = Array.fill[ArrayBuffer[(Int, Int)]](N)(ArrayBuffer())\n rep(N) { i =>\n ans(i) += ((100 * i + i, 100 * i + i))\n }\n rep(M) { i =>\n val (a, b) = P(i)\n val xa = 100 * a + a\n val ya = 100 * a + b\n val xb = 100 * b + a\n val yb = 100 * b + b\n ans(a) += ((xa, ya))\n ans(b) += ((xb, yb))\n ans(a) += ((xb, ya)) // \u7d50\u5408\u3059\u308b\u3068\u3053\u308d\n }\n\n rep(N) { i =>\n out.println(ans(i).length)\n ans(i) foreach { case (x, y) =>\n out.println(s\"${x+1} ${y+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): 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": "29476eefb914b445f1421d99d928fd5a"} {"nl": {"description": "Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{n}$$$ ($$$1 \\le a_i \\le 10^4$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print \"YES\". Otherwise, print \"NO\".", "sample_inputs": ["2\n3\n1 5 4\n2\n100 10000"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "33a31edb75c9b0cf3a49ba97ad677632"} {"nl": {"description": "Let's call a positive integer composite if it has at least one divisor other than $$$1$$$ and itself. For example: the following numbers are composite: $$$1024$$$, $$$4$$$, $$$6$$$, $$$9$$$; the following numbers are not composite: $$$13$$$, $$$1$$$, $$$2$$$, $$$3$$$, $$$37$$$. You are given a positive integer $$$n$$$. Find two composite integers $$$a,b$$$ such that $$$a-b=n$$$.It can be proven that solution always exists.", "input_spec": "The input contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^7$$$): the given integer.", "output_spec": "Print two composite integers $$$a,b$$$ ($$$2 \\leq a, b \\leq 10^9, a-b=n$$$). It can be proven, that solution always exists. If there are several possible solutions, you can print any. ", "sample_inputs": ["1", "512"], "sample_outputs": ["9 8", "4608 4096"], "notes": null}, "positive_code": [{"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 (a, b) =\n if(n == 1) (9,8)\n else (3 * n, 2 * n)\n\n println(s\"$a $b\")\n\n}\n"}], "negative_code": [{"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 val a = 3 * n\n val b = 3 * n\n\n println(s\"$a $b\")\n\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 val a = 3 * n\n val b = 2 * n\n\n println(s\"$a $b\")\n\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 (a, b) =\n if(n == 1) (8,9)\n else (3 * n, 2 * n)\n\n println(s\"$a $b\")\n\n}\n"}], "src_uid": "59d5e5ed2bc4b316e950e2a4dbc99d68"} {"nl": {"description": "This is an interactive problem.In good old times dwarves tried to develop extrasensory abilities: Exactly n dwarves entered completely dark cave. Each dwarf received a hat\u00a0\u2014 white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves. Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information. The task for dwarves was to got diverged into two parts\u00a0\u2014 one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color\u00a0\u2014 black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive\u00a0\u2014 the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.", "input_spec": null, "output_spec": null, "sample_inputs": ["5\n\n\n\nblack\n\n\n\nblack\n\n\n\nwhite\n\n\n\nwhite\n\n\n\nblack"], "sample_outputs": ["0 0\n\n\n\n3 1\n\n\n\n2 3\n\n\n\n4 4\n\n\n\n0 2\n\n\n\n1 3 4 1"], "notes": "NoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no \"extra\" line breaks should appear.The following picture illustrates the first test. "}, "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\n /**\n * y\u306e\u9ad8\u3055\u306e\u5de6\u53f3\u3092\u5de6\u304b\u3089\u767d,\u53f3\u304b\u3089\u9ed2\u3067\u57cb\u3081\u3066\u3044\u3063\u3066\u3001\u4e2d\u9593\u306e\u672a\u5b9a\u7fa9\u90e8\u5206\u3092\u8fd4\u3059\n */\n def ask(y: Int, cnt: Int): (Int, Int) = {\n var l = 0\n var h = 1e9.toInt\n rep(cnt) { _ =>\n val mid = (h + l) / 2\n println(s\"$mid $y\")\n ns() match {\n case \"black\" => h = mid\n case \"white\" => l = mid\n }\n }\n (l, h)\n }\n\n val (x0_l, x0_r) = ask(0, N/2)\n val (x1_l, x1_r) = ask(5e8.toInt, N - N/2)\n\n println(s\"${(x0_l + x0_r)/2} 0 ${(x1_l+ x1_r)/2} ${5e8.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}"}], "negative_code": [], "src_uid": "574347ab83379e5b08618d2b275b0d96"} {"nl": {"description": "Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0,\u2009len(s)\u2009-\u20091]. He tells Vasya this string s, and then shifts it k letters to the left, i.\u00a0e. creates a new string t\u2009=\u2009sk\u2009+\u20091sk\u2009+\u20092... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.", "input_spec": "The only string contains the string s of length l (3\u2009\u2264\u2009l\u2009\u2264\u20095000), consisting of small English letters only.", "output_spec": "Print the only number\u00a0\u2014 the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10\u2009-\u20096. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if ", "sample_inputs": ["technocup", "tictictactac", "bbaabaabbb"], "sample_outputs": ["1.000000000000000", "0.333333333333333", "0.100000000000000"], "notes": "NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is \"t\" or \"c\", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is \"i\" or \"a\", then he can open the fourth letter and determine the shift uniquely."}, "positive_code": [{"source_code": "object B extends App {\n\n val s = readLine.map(_ - 'a')\n val l = s.length\n\n val positionsOfLetter = s.zipWithIndex.groupBy(_._1).map {\n case (key, values) =>\n key -> values.map(_._2)\n }\n\n var goodCount = 0\n\n for (first <- positionsOfLetter.keys) {\n var max = 0\n for (i <- 1 until l) {\n val counts = Array.fill('z' - 'a' + 1){ 0 }\n for (k <- positionsOfLetter(first)) {\n counts(s((i + k) % l)) += 1\n }\n max = Math.max(max, counts.count(_ == 1))\n }\n goodCount += max\n }\n\n println(goodCount.toDouble / l)\n}\n"}], "negative_code": [{"source_code": "import java.util\n\nobject B extends App {\n\n val s = readLine.map(_ - 'a')\n val l = s.length\n val letters = s.distinct\n\n def get(i: Int): Int = s((i + l) % l )\n\n val sByLet = s.groupBy(identity).map {\n case (k, v) => k -> v.size\n }\n\n val counts = Array.fill(letters.max + 1, letters.max + 1, l)(0)\n\n for (k <- 0 until l) {\n val first = get(k)\n //util.Arrays.fo(counts, 0)\n for (i <- 1 until l) {\n counts(first)(get(i + k))(i) += 1\n //if (counts(first)(get(i + k))(i) > 1) good = false\n }\n }\n\n var goodCount = 0d\n\n for (k <- 0 until l) {\n val first = get(k)\n var good = false\n for (i <- 1 until l) {\n if (counts(first)(get(i + k))(i) == 1) good = true\n }\n //println(k, first, good)\n if (good) goodCount += 1d // sByLet(first)\n }\n\n val res = goodCount / l\n\n println(res)\n}\n"}], "src_uid": "4c92218ccbab7d142c2cbb6dd54c510a"} {"nl": {"description": "Pavel has several sticks with lengths equal to powers of two.He has $$$a_0$$$ sticks of length $$$2^0 = 1$$$, $$$a_1$$$ sticks of length $$$2^1 = 2$$$, ..., $$$a_{n-1}$$$ sticks of length $$$2^{n-1}$$$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 300\\,000$$$)\u00a0\u2014 the number of different lengths of sticks. The second line contains $$$n$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_{n-1}$$$ ($$$1 \\leq a_i \\leq 10^9$$$), where $$$a_i$$$ is the number of sticks with the length equal to $$$2^i$$$.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible number of non-degenerate triangles that Pavel can make.", "sample_inputs": ["5\n1 2 2 2 2", "3\n1 1 1", "3\n3 3 3"], "sample_outputs": ["3", "0", "3"], "notes": "NoteIn the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^4, 2^4)$$$, $$$(2^1, 2^3, 2^3)$$$, $$$(2^1, 2^2, 2^2)$$$.In the second example, Pavel cannot make a single triangle.In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^0, 2^0)$$$, $$$(2^1, 2^1, 2^1)$$$, $$$(2^2, 2^2, 2^2)$$$."}, "positive_code": [{"source_code": "object E extends App {\n\n val numCount = scala.io.StdIn.readLine()\n\n val stickCounts = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val answer = solve(stickCounts, 0L, 0L)\n\n println(answer)\n\n private def solve(list: List[Int], count: Long, debt: Long): Long = {\n// println(s\"Before: left: $list, count: $count, debt $debt\")\n list match {\n case Nil => count - debt\n case x :: xs => {\n val forDebt = Math.min(x / 2, debt)\n val (updDebt, xAfterDebt) = (debt - forDebt, x - (forDebt * 2))\n\n val forFull = xAfterDebt / 3\n val (updCount, xAfterFull) = (count + forFull, xAfterDebt - (forFull * 3))\n\n solve(xs, updCount + xAfterFull, updDebt + xAfterFull)\n }\n }\n }\n}"}], "negative_code": [{"source_code": "object E extends App {\n val numCount = scala.io.StdIn.readLine()\n\n val stickCounts = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n val (simplifiedSeq, count) = simplify(stickCounts)\n\n val answer = solve(simplifiedSeq, count, 0L)\n\n println(answer)\n\n private def simplify(list: List[Int]): (List[Int], Long) = {\n var accCount = 0L\n val accList = list.map { el =>\n accCount += (el / 3)\n el % 3\n }\n (accList, accCount)\n }\n\n private def solve(seq: List[Int], count: Long, debt: Long): Long = {\n seq match {\n case Nil => count - debt\n case x :: xs => {\n if (x == 2 && debt > 0) solve(xs, count, debt - 1)\n else solve(xs, count + x, debt + x)\n }\n }\n }\n}"}], "src_uid": "a8f3e94845cb15a483ce8f774779efac"} {"nl": {"description": "Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $$$a=[1, 3, 3, 7]$$$ is good because there is the element $$$a_4=7$$$ which equals to the sum $$$1 + 3 + 3$$$.You are given an array $$$a$$$ consisting of $$$n$$$ integers. Your task is to print all indices $$$j$$$ of this array such that after removing the $$$j$$$-th element from the array it will be good (let's call such indices nice).For example, if $$$a=[8, 3, 5, 2]$$$, the nice indices are $$$1$$$ and $$$4$$$: if you remove $$$a_1$$$, the array will look like $$$[3, 5, 2]$$$ and it is good; if you remove $$$a_4$$$, the array will look like $$$[8, 3, 5]$$$ and it is good. You have to consider all removals independently, i.\u2009e. remove the element, check if the resulting array is good, and return the element into the array.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$) \u2014 elements of the array $$$a$$$.", "output_spec": "In the first line print one integer $$$k$$$ \u2014 the number of indices $$$j$$$ of the array $$$a$$$ such that after removing the $$$j$$$-th element from the array it will be good (i.e. print the number of the nice indices). In the second line print $$$k$$$ distinct integers $$$j_1, j_2, \\dots, j_k$$$ in any order \u2014 nice indices of the array $$$a$$$. If there are no such indices in the array $$$a$$$, just print $$$0$$$ in the first line and leave the second line empty or do not print it at all.", "sample_inputs": ["5\n2 5 1 2 2", "4\n8 3 5 2", "5\n2 1 2 4 3"], "sample_outputs": ["3\n4 1 5", "2\n1 4", "0"], "notes": "NoteIn the first example you can remove any element with the value $$$2$$$ so the array will look like $$$[5, 1, 2, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 1 + 2 + 2$$$).In the second example you can remove $$$8$$$ so the array will look like $$$[3, 5, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 3 + 2$$$). You can also remove $$$2$$$ so the array will look like $$$[8, 3, 5]$$$. The sum of this array is $$$16$$$ and there is an element equals to the sum of remaining elements ($$$8 = 3 + 5$$$).In the third example you cannot make the given array good by removing exactly one element."}, "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": "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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself.Let's describe this problem in a mathematical way. Consider a timeline from time $$$1$$$ to $$$n$$$. The $$$i$$$-th red envelope will be available from time $$$s_i$$$ to $$$t_i$$$, inclusive, and contain $$$w_i$$$ coins. If Bob chooses to collect the coins in the $$$i$$$-th red envelope, he can do it only in an integer point of time between $$$s_i$$$ and $$$t_i$$$, inclusive, and he can't collect any more envelopes until time $$$d_i$$$ (inclusive) after that. Here $$$s_i \\leq t_i \\leq d_i$$$ holds.Bob is a greedy man, he collects coins greedily \u2014 whenever he can collect coins at some integer time $$$x$$$, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter $$$d$$$ is the largest. If there are still multiple choices, Bob will choose one from them randomly.However, Alice \u2014 his daughter \u2014 doesn't want her father to get too many coins. She could disturb Bob at no more than $$$m$$$ integer time moments. If Alice decides to disturb Bob at time $$$x$$$, he could not do anything at time $$$x$$$ and resumes his usual strategy at the time $$$x + 1$$$ (inclusive), which may lead to missing some red envelopes.Calculate the minimum number of coins Bob would get if Alice disturbs him optimally.", "input_spec": "The first line contains three non-negative integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$0 \\leq m \\leq 200$$$, $$$1 \\leq k \\leq 10^5$$$), denoting the length of the timeline, the number of times Alice can disturb Bob and the total number of red envelopes, respectively. The following $$$k$$$ lines describe those $$$k$$$ red envelopes. The $$$i$$$-th line contains four positive integers $$$s_i$$$, $$$t_i$$$, $$$d_i$$$ and $$$w_i$$$ ($$$1 \\leq s_i \\leq t_i \\leq d_i \\leq n$$$, $$$1 \\leq w_i \\leq 10^9$$$)\u00a0\u2014 the time segment when the $$$i$$$-th envelope is available, the time moment Bob can continue collecting after collecting the $$$i$$$-th envelope, and the number of coins in this envelope, respectively.", "output_spec": "Output one integer \u2014 the minimum number of coins Bob would get if Alice disturbs him optimally.", "sample_inputs": ["5 0 2\n1 3 4 5\n2 5 5 8", "10 1 6\n1 1 2 4\n2 2 6 2\n3 3 3 3\n4 4 4 5\n5 5 5 7\n6 6 6 9", "12 2 6\n1 5 5 4\n4 6 6 2\n3 8 8 3\n2 9 9 5\n6 10 10 7\n8 12 12 9"], "sample_outputs": ["13", "2", "11"], "notes": "NoteIn the first sample, Alice has no chance to disturb Bob. Therefore Bob will collect the coins in the red envelopes at time $$$1$$$ and $$$5$$$, collecting $$$13$$$ coins in total.In the second sample, Alice should disturb Bob at time $$$1$$$. Therefore Bob skips the first envelope, collects the second one and can not do anything after that. So the answer is $$$2$$$."}, "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 S, T, D, W = Array.ofDim[Int](K)\n REP(K) { i =>\n S(i) = ni() - 1\n T(i) = ni() - 1\n D(i) = ni() - 1\n W(i) = ni()\n }\n\n // Bob\u304c\u304a\u306e\u304a\u306e\u306e\u6642\u70b9\u3067\u9078\u3076\u9078\u629e\u80a2\n def calcGreedy: Array[Int] = {\n import java.util\n import java.util.Comparator\n\n val choise = Array.fill[Int](N)(-1)\n val t = new util.TreeSet[Integer](new Comparator[Integer] {\n // (W, D, id) \u306edesc\n override def compare(o1: Integer, o2: Integer): Int = {\n if (W(o1) == W(o2)) {\n if (D(o1) == D(o2))\n o2.compareTo(o1)\n else\n Integer.compare(D(o2), D(o1))\n } else Integer.compare(W(o2), W(o1))\n }\n })\n\n val starts, ends = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(K) { i =>\n starts(S(i)) += i\n ends(T(i)) += i\n }\n\n REP(N) { i =>\n val ss = starts(i)\n REP(ss.length) { j =>\n t.add(ss(j))\n }\n\n if (!t.isEmpty) choise(i) = t.first()\n\n val es = ends(i)\n REP(es.length) { j =>\n t.remove(es(j))\n }\n }\n\n choise\n }\n\n val choise = calcGreedy\n// debug(choise)\n\n val INF = Long.MaxValue / 2\n\n // i=N\u306f\u6642\u9593\u3092\u8d85\u3048\u305f\u5411\u3053\u3046\u5074\u3092\u307e\u3068\u3081\u305f\u3082\u306e\n val dp = Array.fill[Long](N + 1, M + 1)(INF)\n dp(0)(M) = 0\n REP(N) { i =>\n REP(M + 1) { m =>\n if (m > 0) dp(i + 1)(m - 1) = min(dp(i + 1)(m - 1), dp(i)(m)) // skip\n\n // \u9077\u79fb\n if (choise(i) != -1) {\n val k = choise(i)\n\n // \u6642\u9593\u3092\u6ea2\u308c\u3066\u3082\u9078\u3076\u3053\u3068\u306f\u3067\u304d\u308b\n val dest = min(D(k) + 1, N)\n dp(dest)(m) = min(dp(dest)(m), dp(i)(m) + W(k))\n } else {\n // \u9078\u3076\u3082\u306e\u304c\u306a\u3044\u306e\u3067\u5358\u306b\u6642\u9593\u304c\u904e\u304e\u308b\n dp(i + 1)(m) = min(dp(i + 1)(m), dp(i)(m))\n }\n }\n }\n\n// REP(N + 1) { i =>\n// debug(dp(i))\n// }\n\n val ans = dp(N).min\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, M, K = ni()\n val S, T, D, W = Array.ofDim[Int](K)\n REP(K) { i =>\n S(i) = ni() - 1\n T(i) = ni() - 1\n D(i) = ni()\n W(i) = ni()\n }\n\n // Bob\u304c\u304a\u306e\u304a\u306e\u306e\u6642\u70b9\u3067\u9078\u3076\u9078\u629e\u80a2\n def calcGreedy: Array[Int] = {\n import java.util\n import java.util.Comparator\n\n val choise = Array.fill[Int](N)(-1)\n val t = new util.TreeSet[Integer](new Comparator[Integer] {\n // (W, D, id) \u306edesc\n override def compare(o1: Integer, o2: Integer): Int = {\n if (W(o1) == W(o2)) {\n if (D(o1) == D(o2))\n Integer.compare(o2, o1)\n else\n Integer.compare(D(o2), D(o1))\n } else Integer.compare(W(o2), W(o1))\n }\n })\n\n val starts, ends = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(K) { i =>\n starts(S(i)) += i\n ends(T(i)) += i\n }\n\n REP(N) { i =>\n val ss = starts(i)\n val es = ends(i)\n REP(ss.length) { j =>\n t.add(ss(j))\n }\n\n if (!t.isEmpty) choise(i) = t.first()\n\n REP(es.length) { j =>\n t.remove(es(j))\n }\n }\n\n choise\n }\n\n val choise = calcGreedy\n // debug(choise)\n\n val INF = Long.MaxValue / 2\n\n // i=N\u306f\u6642\u9593\u3092\u8d85\u3048\u305f\u5411\u3053\u3046\u5074\u3092\u307e\u3068\u3081\u305f\u3082\u306e\n val dp = Array.fill[Long](N + 1, M + 1)(INF)\n dp(0)(M) = 0\n REP(N) { i =>\n REP(M + 1) { m =>\n if (m > 0) dp(i + 1)(m - 1) = min(dp(i + 1)(m - 1), dp(i)(m)) // skip\n\n // \u9077\u79fb\n if (choise(i) != -1) {\n val k = choise(i)\n\n // \u6642\u9593\u3092\u6ea2\u308c\u3066\u3082\u9078\u3076\u3053\u3068\u306f\u3067\u304d\u308b\n val dest = min(i + D(k), N)\n dp(dest)(m) = min(dp(dest)(m), dp(i)(m) + W(k))\n } else {\n // \u9078\u3076\u3082\u306e\u304c\u306a\u3044\u306e\u3067\u5358\u306b\u6642\u9593\u304c\u904e\u304e\u308b\n dp(i + 1)(m) = min(dp(i + 1)(m), dp(i)(m))\n }\n }\n }\n\n // REP(N + 1) { i =>\n // debug(dp(i))\n // }\n\n val ans = dp(N).min\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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 S, T, D, W = Array.ofDim[Int](K)\n REP(K) { i =>\n S(i) = ni() - 1\n T(i) = ni() - 1\n D(i) = ni()\n W(i) = ni()\n }\n\n // Bob\u304c\u304a\u306e\u304a\u306e\u306e\u6642\u70b9\u3067\u9078\u3076\u9078\u629e\u80a2\n def calcGreedy: Array[Int] = {\n import java.util\n import java.util.Comparator\n\n val choise = Array.fill[Int](N)(-1)\n val t = new util.TreeSet[Integer](new Comparator[Integer] {\n // (W, D) \u306edesc\n override def compare(o1: Integer, o2: Integer): Int = {\n if (W(o1) == W(o2)) Integer.compare(D(o2), D(o1))\n else Integer.compare(W(o2), W(o1))\n }\n })\n\n val starts, ends = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n REP(K) { i =>\n starts(S(i)) += i\n ends(T(i)) += i\n }\n\n REP(N) { i =>\n val ss = starts(i)\n val es = ends(i)\n REP(ss.length) { j =>\n t.add(ss(j))\n }\n\n if (!t.isEmpty) choise(i) = t.first()\n\n REP(es.length) { j =>\n t.remove(es(j))\n }\n }\n\n choise\n }\n\n val choise = calcGreedy\n// debug(choise)\n\n val INF = Long.MaxValue / 2\n\n // i=N\u306f\u6642\u9593\u3092\u8d85\u3048\u305f\u5411\u3053\u3046\u5074\u3092\u307e\u3068\u3081\u305f\u3082\u306e\n val dp = Array.fill[Long](N + 1, M + 1)(INF)\n dp(0)(M) = 0\n REP(N) { i =>\n REP(M + 1) { m =>\n if (m > 0) dp(i + 1)(m - 1) = min(dp(i + 1)(m - 1), dp(i)(m)) // skip\n\n // \u9077\u79fb\n if (choise(i) != -1) {\n val k = choise(i)\n\n // \u6642\u9593\u3092\u6ea2\u308c\u3066\u3082\u9078\u3076\u3053\u3068\u306f\u3067\u304d\u308b\n val dest = min(i + D(k), N)\n dp(dest)(m) = min(dp(dest)(m), dp(i)(m) + W(k))\n } else {\n // \u9078\u3076\u3082\u306e\u304c\u306a\u3044\u306e\u3067\u5358\u306b\u6642\u9593\u304c\u904e\u304e\u308b\n dp(i + 1)(m) = min(dp(i + 1)(m), dp(i)(m))\n }\n }\n }\n\n// REP(N + 1) { i =>\n// debug(dp(i))\n// }\n\n val ans = dp(N).min\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}"}], "src_uid": "7c4c594185ed0f6a31d49e292e6f85dc"} {"nl": {"description": "There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one \"slice\" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \\ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$n \\le k \\le 10^9$$$) \u2014 the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \\dots, h_n$$$ ($$$1 \\le h_i \\le 2 \\cdot 10^5$$$) \u2014 the initial heights of towers.", "output_spec": "Print one integer \u2014 the minimum number of good slices you have to do to make all towers have the same heigth.", "sample_inputs": ["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$)."}, "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 H = na(N)\n val ms = H.min\n val mx = H.max\n val H2 = Array.ofDim[Int](mx + 1)\n rep(N) { i =>\n H2(H(i)) += 1\n }\n\n var ans = 0\n var cnt = 0\n var num = 0\n rep_r(mx - ms, ms + 1) { h =>\n num += H2(h)\n if (cnt + num > K) {\n ans += 1\n cnt = num\n } else {\n cnt += num\n }\n }\n\n if (cnt > 0) ans += 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, K = ni()\n val H = na(N)\n val ms = H.min\n val mx = H.max\n val H2 = Array.ofDim[Int](mx + 1)\n rep(N) { i =>\n H2(H(i)) += 1\n }\n\n var ans = 0\n var cnt = 0\n var num = 0\n rep_r(mx - ms, ms + 1) { h =>\n num += H2(h)\n if (cnt + num >= K) {\n ans += 1\n cnt = num\n } else {\n cnt += num\n }\n }\n\n if (cnt > 0) ans += 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}"}], "src_uid": "676729309dfbdf4c9d9d7c457a129608"} {"nl": {"description": "A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.Applying the simplest variant of median smoothing to the sequence of numbers a1,\u2009a2,\u2009...,\u2009an will result a new sequence b1,\u2009b2,\u2009...,\u2009bn obtained by the following algorithm: b1\u2009=\u2009a1, bn\u2009=\u2009an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence. For i\u2009=\u20092,\u2009...,\u2009n\u2009-\u20091 value bi is equal to the median of three values ai\u2009-\u20091, ai and ai\u2009+\u20091. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.", "input_spec": "The first input line of the input contains a single integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000)\u00a0\u2014 the length of the initial sequence. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (ai\u2009=\u20090 or ai\u2009=\u20091), giving the initial sequence itself.", "output_spec": "If the sequence will never become stable, print a single number \u2009-\u20091. Otherwise, first print a single integer\u00a0\u2014 the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space \u00a0\u2014 the resulting sequence itself.", "sample_inputs": ["4\n0 0 1 1", "5\n0 1 0 1 0"], "sample_outputs": ["0\n0 0 1 1", "2\n0 0 0 0 0"], "notes": "NoteIn the second sample the stabilization occurs in two steps: , and the sequence 00000 is obviously stable."}, "positive_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": "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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number $$$x$$$. A perfect longcat is a cat with a number equal $$$2^m - 1$$$ for some non-negative integer $$$m$$$. For example, the numbers $$$0$$$, $$$1$$$, $$$3$$$, $$$7$$$, $$$15$$$ and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on $$$x$$$: (Operation A): you select any non-negative integer $$$n$$$ and replace $$$x$$$ with $$$x \\oplus (2^n - 1)$$$, with $$$\\oplus$$$ being a bitwise XOR operator. (Operation B): replace $$$x$$$ with $$$x + 1$$$. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $$$40$$$ operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than $$$40$$$ operations.", "input_spec": "The only line contains a single integer $$$x$$$ ($$$1 \\le x \\le 10^6$$$).", "output_spec": "The first line should contain a single integer $$$t$$$ ($$$0 \\le t \\le 40$$$)\u00a0\u2014 the number of operations to apply. Then for each odd-numbered operation print the corresponding number $$$n_i$$$ in it. That is, print $$$\\lceil \\frac{t}{2} \\rceil$$$ integers $$$n_i$$$ ($$$0 \\le n_i \\le 30$$$), denoting the replacement $$$x$$$ with $$$x \\oplus (2^{n_i} - 1)$$$ in the corresponding step. If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.", "sample_inputs": ["39", "1", "7"], "sample_outputs": ["4\n5 3", "0", "0"], "notes": "NoteIn the first test, one of the transforms might be as follows: $$$39 \\to 56 \\to 57 \\to 62 \\to 63$$$. Or more precisely: Pick $$$n = 5$$$. $$$x$$$ is transformed into $$$39 \\oplus 31$$$, or $$$56$$$. Increase $$$x$$$ by $$$1$$$, changing its value to $$$57$$$. Pick $$$n = 3$$$. $$$x$$$ is transformed into $$$57 \\oplus 7$$$, or $$$62$$$. Increase $$$x$$$ by $$$1$$$, changing its value to $$$63 = 2^6 - 1$$$. In the second and third test, the number already satisfies the goal requirement."}, "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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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 // \u5de6\u304b\u3089\u6700\u521d\u306b0\u306b\u306a\u308b\u5834\u6240\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 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\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}"}], "negative_code": [], "src_uid": "2510469c09d7d145078e65de81640ddc"} {"nl": {"description": "You are given an $$$n \\times m$$$ table, consisting of characters \u00abA\u00bb, \u00abG\u00bb, \u00abC\u00bb, \u00abT\u00bb. Let's call a table nice, if every $$$2 \\times 2$$$ square contains all four distinct characters. Your task is to find a nice table (also consisting of \u00abA\u00bb, \u00abG\u00bb, \u00abC\u00bb, \u00abT\u00bb), that differs from the given table in the minimum number of characters.", "input_spec": "First line contains two positive integers $$$n$$$ and $$$m$$$\u00a0\u2014 number of rows and columns in the table you are given ($$$2 \\leq n, m, n \\times m \\leq 300\\,000$$$). Then, $$$n$$$ lines describing the table follow. Each line contains exactly $$$m$$$ characters \u00abA\u00bb, \u00abG\u00bb, \u00abC\u00bb, \u00abT\u00bb.", "output_spec": "Output $$$n$$$ lines, $$$m$$$ characters each. This table must be nice and differ from the input table in the minimum number of characters.", "sample_inputs": ["2 2\nAG\nCT", "3 5\nAGCAG\nAGCAG\nAGCAG"], "sample_outputs": ["AG\nCT", "TGCAT\nCATGC\nTGCAT"], "notes": "NoteIn the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice."}, "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 AnswerMat(set: Int, flgs: Array[Boolean])\n val S = \"AGCT\"\n def select2(set: Int, which: Boolean) = {\n val a_p2 = Integer.highestOneBit(set)\n val b_p2 = set ^ a_p2\n val a = S(log2(a_p2))\n val b = S(log2(b_p2))\n if (which) Array(a, b) else Array(b, a)\n }\n\n def mkMatrix(n: Int, m: Int, ans: AnswerMat): Array[Array[Char]] = {\n val mat = Array.ofDim[Char](n, m)\n REP(n) { r =>\n val even = ans.set\n val odd = ((1 << 4) - 1) ^ ans.set\n val set = if (r % 2 == 0) even else odd\n val C = select2(set, ans.flgs(r))\n REP(m) { c =>\n mat(r)(c) = C(c % 2)\n }\n }\n mat\n }\n\n def solve(): Unit = {\n val N, M = ni()\n val Matrix = nm_c(N, M)\n\n def calc(n: Int, m: Int, mat: Array[Array[Char]]): (Int, AnswerMat) = {\n /**\n * @return (change count, AB, BA\u3069\u3063\u3061\u3067\u3044\u3063\u305f\u304b)\n */\n def calcRowMinChanged(r: Int, row: Int): (Int, Boolean) = {\n def calcRowChanged(C: Array[Char]) = {\n var changed = 0\n REP(m) { c =>\n if (mat(r)(c) != C(c % 2)) changed += 1\n }\n changed\n }\n\n val c1 = calcRowChanged(select2(row, false))\n val c2 = calcRowChanged(select2(row, true))\n if (c1 < c2) (c1, false)\n else (c2, true)\n }\n\n var cnt = 1e6.toInt\n var ans: Option[AnswerMat] = None\n REP(1 << 4) { set =>\n if (Integer.bitCount(set) == 2) {\n val even = set\n val odd = ((1 << 4) - 1) ^ set\n var changed = 0\n val flgs = Array.ofDim[Boolean](n)\n REP(n) { r =>\n val row = if (r % 2 == 0) even else odd\n val (rowChanged, flg) = calcRowMinChanged(r, row)\n flgs(r) = flg\n changed += rowChanged\n }\n\n if (cnt > changed) {\n cnt = changed\n ans = Some(AnswerMat(set, flgs))\n }\n }\n }\n\n (cnt, ans.get)\n }\n\n val (c1, ans1) = calc(N, M, Matrix)\n val (c2, ans2) = calc(M, N, swap(N, M, Matrix))\n// debug(s\"$c1 $c2\")\n val ans = if (c1 <= c2) {\n mkMatrix(N, M, ans1)\n } else {\n swap(M, N, mkMatrix(M, N, ans2))\n }\n REP(N) { r =>\n out.println(ans(r).mkString)\n }\n }\n\n /**\n * log2\u3057\u3066\u5c0f\u6570\u70b9\u5207\u308a\u6368\u3066\u305f\u3082\u306e\n */\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n i\n }\n\n def swap(n: Int, m: Int, mat: Array[Array[Char]]): Array[Array[Char]] = {\n val res = Array.ofDim[Char](m, n)\n REP(m) { r =>\n REP(n) { c =>\n res(r)(c) = mat(c)(r)\n }\n }\n res\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": "d80a963af909638d5504dbc6adb2ba38"} {"nl": {"description": "Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).Implement this feature to help Polycarp test his editor.", "input_spec": "The first line contains two integers, w and h (1\u2009\u2264\u2009w,\u2009h\u2009\u2264\u2009100) \u2014 the width and height of an image in pixels. The picture is given in h lines, each line contains w characters \u2014 each character encodes the color of the corresponding pixel of the image. The line consists only of characters \".\" and \"*\", as the image is monochrome.", "output_spec": "Print 2w lines, each containing 2h characters \u2014 the result of consecutive implementing of the three transformations, described above.", "sample_inputs": ["3 2\n.*.\n.*.", "9 20\n**.......\n****.....\n******...\n*******..\n..******.\n....****.\n......***\n*.....***\n*********\n*********\n*********\n*********\n....**...\n...****..\n..******.\n.********\n****..***\n***...***\n**.....**\n*.......*"], "sample_outputs": ["....\n....\n****\n****\n....\n....", "********......**********........********\n********......**********........********\n********........********......********..\n********........********......********..\n..********......********....********....\n..********......********....********....\n..********......********..********......\n..********......********..********......\n....********....****************........\n....********....****************........\n....********....****************........\n....********....****************........\n......******************..**********....\n......******************..**********....\n........****************....**********..\n........****************....**********..\n............************......**********\n............************......**********"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai,\u2009aj) over all pairs (i,\u2009j) such that 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200000) \u2014 the number of elements in a. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the array. ", "output_spec": "Print one integer \u2014 the sum of d(ai,\u2009aj) over all pairs (i,\u2009j) such that 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n.", "sample_inputs": ["5\n1 2 3 1 3", "4\n6 6 5 5", "4\n6 6 4 4"], "sample_outputs": ["4", "0", "-8"], "notes": "NoteIn the first example: d(a1,\u2009a2)\u2009=\u20090; d(a1,\u2009a3)\u2009=\u20092; d(a1,\u2009a4)\u2009=\u20090; d(a1,\u2009a5)\u2009=\u20092; d(a2,\u2009a3)\u2009=\u20090; d(a2,\u2009a4)\u2009=\u20090; d(a2,\u2009a5)\u2009=\u20090; d(a3,\u2009a4)\u2009=\u2009\u2009-\u20092; d(a3,\u2009a5)\u2009=\u20090; d(a4,\u2009a5)\u2009=\u20092. "}, "positive_code": [{"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 nums = readLongLine()\n\n val table = new mutable.HashMap[Long, Int]()\n\n var i = nums.length - 1\n var numSum = 0L\n var numCount = 0\n var totalSum = BigInt(0)\n while (i >= 0) {\n val num = nums(i)\n val eq = table.getOrElse(num, 0)\n val more = table.getOrElse(num + 1, 0)\n val less = table.getOrElse(num - 1, 0)\n val adjustedSum = numSum - (eq * num) - (more * (num + 1)) - (less * (num - 1))\n val adjustedCount = numCount - eq - more - less\n totalSum += adjustedSum - (adjustedCount * num)\n\n table.put(num, eq + 1)\n numSum += num\n numCount += 1\n i -= 1\n }\n println(totalSum)\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": [], "src_uid": "c7cca8c6524991da6ea1b423a8182d24"} {"nl": {"description": "Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \\le s[p_{i + 1}]$$$ and $$$s[q_i] \\le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5, 1 \\le k \\le 26$$$) \u2014 the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) \u2014 the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \\dots, q_n$$$ ($$$1 \\le q_i \\le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) \u2014 the permutation $$$q$$$.", "output_spec": "If it is impossible to find the suitable string, print \"NO\" on the first line. Otherwise print \"YES\" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.", "sample_inputs": ["3 2\n1 2 3\n1 3 2"], "sample_outputs": ["YES\nabb"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contest1213\n\nobject UnstableStringSort {\n\n val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val seq1, seq2 = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def loop(i: Int,\n l1: List[Int],\n l1Seen: Set[Int],\n l1Expected: Set[Int],\n l2: List[Int],\n l2Seen: Set[Int],\n l2Expected: Set[Int],\n result: List[Int]): List[Int] = {\n if (l1Expected.isEmpty && l2Expected.isEmpty) {\n if (i == n)\n result\n else {\n val l1NewSeen = Set(l1.head)\n val l1NewExpected = Set(l2.head) - l1.head\n val l2NewSeen = Set(l2.head)\n val l2NewExpected = Set(l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n i :: result\n )\n }\n } else {\n val l1NewSeen = l1Seen + l1.head\n val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected\n else l1Expected + l2.head) - l1.head\n val l2NewSeen = l2Seen + l2.head\n val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected\n else l2Expected + l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n result\n )\n }\n }\n\n println {\n val subsequenceIndices = (n :: loop(\n 0,\n seq1.toList,\n Set.empty,\n Set.empty,\n seq2.toList,\n Set.empty,\n Set.empty,\n Nil\n )).reverse\n if (subsequenceIndices.size - 1 < k)\n \"NO\"\n else {\n println(\"YES\")\n val res = subsequenceIndices\n .sliding(2)\n .zipWithIndex\n .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }\n .mkString(\"\")\n\n assert((0 to n - 2).forall(i => res(i) <= res(i + 1)))\n\n val p = new Array[Char](n)\n\n (0 until n).foreach { i =>\n p(seq1(i) - 1) = res(i)\n }\n\n p.mkString(\"\")\n }\n }\n\n }\n\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contest1213\n\nobject UnstableStringSort {\n\n val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val seq1, seq2 = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def loop(i: Int,\n l1: List[Int],\n l1Seen: Set[Int],\n l1Expected: Set[Int],\n l2: List[Int],\n l2Seen: Set[Int],\n l2Expected: Set[Int],\n result: List[Int]): List[Int] = {\n if (l1Expected.isEmpty && l2Expected.isEmpty) {\n if (i == n)\n result\n else {\n val l1NewSeen = Set(l1.head)\n val l1NewExpected = Set(l2.head) - l1.head\n val l2NewSeen = Set(l2.head)\n val l2NewExpected = Set(l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n i :: result\n )\n }\n } else {\n val l1NewSeen = l1Seen + l1.head\n val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected\n else l1Expected + l2.head) - l1.head\n val l2NewSeen = l2Seen + l2.head\n val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected\n else l2Expected + l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n result\n )\n }\n }\n\n println {\n val subsequenceIndices = (n :: loop(\n 0,\n seq1.toList,\n Set.empty,\n Set.empty,\n seq2.toList,\n Set.empty,\n Set.empty,\n Nil\n )).reverse\n if (subsequenceIndices.size - 1 < k)\n \"NO\"\n else {\n println(\"YES\")\n val res = subsequenceIndices\n .sliding(2)\n .zipWithIndex\n .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }\n .mkString(\"\")\n\n assert((0 to n - 2).forall(i => res(i) <= res(i + 1)))\n\n val p = new Array[Char](n)\n\n (0 until n).foreach { i =>\n p(i) = res(seq1(i) - 1)\n }\n\n p.mkString(\"\")\n }\n }\n\n }\n\n}\n"}, {"source_code": "//package codeforces.contest1213\n\nobject UnstableStringSort {\n\n val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val seq1, seq2 = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def loop(i: Int,\n l1: List[Int],\n l1Seen: Set[Int],\n l1Expected: Set[Int],\n l2: List[Int],\n l2Seen: Set[Int],\n l2Expected: Set[Int],\n result: List[Int]): List[Int] = {\n if (l1Expected.isEmpty && l2Expected.isEmpty) {\n if (i == n)\n result\n else {\n val l1NewSeen = Set(l1.head)\n val l1NewExpected = Set(l2.head) - l1.head\n val l2NewSeen = Set(l2.head)\n val l2NewExpected = Set(l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n i :: result\n )\n }\n } else {\n val l1NewSeen = l1Seen + l1.head\n val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected\n else l1Expected + l2.head) - l1.head\n val l2NewSeen = l2Seen + l2.head\n val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected\n else l2Expected + l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n result\n )\n }\n }\n\n println {\n val subsequenceIndices = (n :: loop(\n 0,\n seq1.toList,\n Set.empty,\n Set.empty,\n seq2.toList,\n Set.empty,\n Set.empty,\n Nil\n )).reverse\n if (subsequenceIndices.size - 1 < k)\n \"NO\"\n else {\n println(\"YES\")\n val res = subsequenceIndices\n .sliding(2)\n .zipWithIndex\n .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }\n .mkString(\"\")\n\n// val p, q = new Array[Char](n)\n//\n// (0 until n).foreach { i =>\n// p(i) = res(seq1(i) - 1)\n// q(i) = res(seq2(i) - 1)\n// }\n//\n// assert(p.sliding(2).forall { case Array(l, r) => l <= r })\n// assert(q.sliding(2).forall { case Array(l, r) => l <= r })\n\n res\n }\n }\n\n }\n\n}\n\n/*\n\n8 5\n1 4 3 5 2 6 7 8\n1 5 4 2 3 7 6 8\n */\n"}, {"source_code": "//package codeforces.contest1213\n\nobject UnstableStringSort {\n\n val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val seq1, seq2 = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @scala.annotation.tailrec\n def loop(i: Int,\n l1: List[Int],\n l1Seen: Set[Int],\n l1Expected: Set[Int],\n l2: List[Int],\n l2Seen: Set[Int],\n l2Expected: Set[Int],\n result: List[Int]): List[Int] = {\n if (l1Expected.isEmpty && l2Expected.isEmpty) {\n if (i == n)\n result\n else {\n val l1NewSeen = Set(l1.head)\n val l1NewExpected = Set(l2.head) - l1.head\n val l2NewSeen = Set(l2.head)\n val l2NewExpected = Set(l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n i :: result\n )\n }\n } else {\n val l1NewSeen = l1Seen + l1.head\n val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected\n else l1Expected + l2.head) - l1.head\n val l2NewSeen = l2Seen + l2.head\n val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected\n else l2Expected + l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n result\n )\n }\n }\n\n println {\n val subsequenceIndices = (n :: loop(\n 0,\n seq1.toList,\n Set.empty,\n Set.empty,\n seq2.toList,\n Set.empty,\n Set.empty,\n Nil\n )).reverse\n if (subsequenceIndices.size - 1 < k)\n \"NO\"\n else {\n println(\"YES\")\n val res = subsequenceIndices\n .sliding(2)\n .zipWithIndex\n .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }\n .mkString(\"\")\n\n assert(res.length == n)\n\n val p = new Array[Char](n)\n\n (0 until n).foreach { i =>\n p(i) = res(seq1(i) - 1)\n }\n\n //assert((0 to n - 2).forall(i => p(i) <= p(i + 1)))\n\n p.mkString(\"\")\n }\n }\n\n }\n\n}\n\n/*\n\n8 5\n1 4 3 5 2 6 7 8\n1 5 4 2 3 7 6 8\n */\n"}, {"source_code": "//package codeforces.contest1213\n\nobject UnstableStringSort {\n\n val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)\n\n def main(args: Array[String]): Unit = {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n val seq1, seq2 = io.StdIn.readLine.split(\" \").map(_.toInt).toList\n\n @scala.annotation.tailrec\n def loop(i: Int,\n l1: List[Int],\n l1Seen: Set[Int],\n l1Expected: Set[Int],\n l2: List[Int],\n l2Seen: Set[Int],\n l2Expected: Set[Int],\n result: List[Int]): List[Int] = {\n if (l1Expected.isEmpty && l2Expected.isEmpty) {\n if (i == n)\n result\n else {\n val l1NewSeen = Set(l1.head)\n val l1NewExpected = Set(l2.head) - l1.head\n val l2NewSeen = Set(l2.head)\n val l2NewExpected = Set(l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n i :: result\n )\n }\n } else {\n val l1NewSeen = l1Seen + l1.head\n val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected\n else l1Expected + l2.head) - l1.head\n val l2NewSeen = l2Seen + l2.head\n val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected\n else l2Expected + l1.head) - l2.head\n loop(\n i + 1,\n l1.tail,\n l1NewSeen,\n l1NewExpected,\n l2.tail,\n l2NewSeen,\n l2NewExpected,\n result\n )\n }\n }\n\n println {\n val subsequenceIndices = (n :: loop(\n 0,\n seq1,\n Set.empty,\n Set.empty,\n seq2,\n Set.empty,\n Set.empty,\n Nil\n )).reverse\n if (subsequenceIndices.size - 1 < k)\n \"NO\"\n else {\n println(\"YES\")\n subsequenceIndices\n .sliding(2)\n .zipWithIndex\n .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }\n .mkString(\"\")\n }\n }\n\n }\n\n}\n\n/*\n\n8 5\n1 4 3 5 2 6 7 8\n1 5 4 2 3 7 6 8\n */\n"}], "src_uid": "591846c93bd221b732c4645e50fae617"} {"nl": {"description": "There is a string $$$s$$$ of length $$$3$$$, consisting of uppercase and lowercase English letters. Check if it is equal to \"YES\" (without quotes), where each letter can be in any case. For example, \"yES\", \"Yes\", \"yes\" are all allowable.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of testcases. The description of each test consists of one line containing one string $$$s$$$ consisting of three characters. Each character of $$$s$$$ is either an uppercase or lowercase English letter.", "output_spec": "For each test case, output \"YES\" (without quotes) if $$$s$$$ satisfies the condition, and \"NO\" (without quotes) otherwise. You can output \"YES\" and \"NO\" in any case (for example, strings \"yES\", \"yes\" and \"Yes\" will be recognized as a positive response).", "sample_inputs": ["10\n\nYES\n\nyES\n\nyes\n\nYes\n\nYeS\n\nNoo\n\norZ\n\nyEz\n\nYas\n\nXES"], "sample_outputs": ["YES\nYES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO"], "notes": "NoteThe first five test cases contain the strings \"YES\", \"yES\", \"yes\", \"Yes\", \"YeS\". All of these are equal to \"YES\", where each character is either uppercase or lowercase."}, "positive_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 println(\"YES\")\r\n } else {\r\n println(\"NO\")\r\n }\r\n }\r\n \r\n }\r\n}"}, {"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"} {"nl": {"description": "An African crossword is a rectangular table n\u2009\u00d7\u2009m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.", "output_spec": "Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.", "sample_inputs": ["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"], "sample_outputs": ["abcd", "codeforces"], "notes": null}, "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 map = in.take(n).map(_.toCharArray).toArray\n var answer = List.empty[Char]\n (0 until n).foreach { i =>\n (0 until m).foreach { j =>\n if ((0 until m).exists {\n k => k != j && map(i)(k) == map(i)(j)\n } || (0 until n).exists {\n k => k != i && map(k)(j) == map(i)(j)\n }) {\n\n } else {\n answer ::= map(i)(j)\n }\n }\n }\n\n println(answer.reverse.mkString)\n\n\n}"}], "negative_code": [], "src_uid": "9c90974a0bb860a5e180760042fd5045"} {"nl": {"description": "Let's call a number k-good if it contains all digits not exceeding k (0,\u2009...,\u2009k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).", "input_spec": "The first line contains integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 0\u2009\u2264\u2009k\u2009\u2264\u20099). The i-th of the following n lines contains integer ai without leading zeroes (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the number of k-good numbers in a.", "sample_inputs": ["10 6\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560", "2 1\n1\n10"], "sample_outputs": ["10", "1"], "notes": null}, "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": "\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"}, {"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.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": "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 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,\u2009...,\u2009k). 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 \u2190 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 \u2190 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,\u2009...,\u2009k). 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 \u2190 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 \u2190 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}"}, {"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": "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}"}], "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 \u2190 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 \u2190 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == (k + 1) && arr.forall(p \u21d2 (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 \u2190 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 \u2190 1 to n } {\n val arr = scan.nextLine.toCharArray.distinct\n if (arr.length == (k + 1) && arr.forall(p \u21d2 (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"} {"nl": {"description": "You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once?", "input_spec": "The only line of the input contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009100\u2009000) consisting of lowercase English letters.", "output_spec": "Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring.", "sample_inputs": ["codeforces", "abacaba"], "sample_outputs": ["bncdenqbdr", "aaacaba"], "notes": "NoteString s is lexicographically smaller than some other string t of the same length if there exists some 1\u2009\u2264\u2009i\u2009\u2264\u2009|s|, such that s1\u2009=\u2009t1,\u2009s2\u2009=\u2009t2,\u2009...,\u2009si\u2009-\u20091\u2009=\u2009ti\u2009-\u20091, and si\u2009<\u2009ti."}, "positive_code": [{"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"}, {"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": "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"}, {"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"}], "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"} {"nl": {"description": "After a long day, Alice and Bob decided to play a little game. The game board consists of $$$n$$$ cells in a straight line, numbered from $$$1$$$ to $$$n$$$, where each cell contains a number $$$a_i$$$ between $$$1$$$ and $$$n$$$. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell $$$i$$$ to cell $$$j$$$ only if the following two conditions are satisfied: the number in the new cell $$$j$$$ must be strictly larger than the number in the old cell $$$i$$$ (i.e. $$$a_j > a_i$$$), and the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. $$$|i-j|\\bmod a_i = 0$$$). Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$). Furthermore, there are no pair of indices $$$i \\neq j$$$ such that $$$a_i = a_j$$$.", "output_spec": "Print $$$s$$$\u00a0\u2014 a string of $$$n$$$ characters, where the $$$i$$$-th character represents the outcome of the game if the token is initially placed in the cell $$$i$$$. If Alice wins, then $$$s_i$$$ has to be equal to \"A\"; otherwise, $$$s_i$$$ has to be equal to \"B\". ", "sample_inputs": ["8\n3 6 5 4 2 7 1 8", "15\n3 11 2 5 10 9 7 13 15 8 4 12 6 1 14"], "sample_outputs": ["BAAAABAB", "ABAAAABBBAABAAB"], "notes": "NoteIn the first sample, if Bob puts the token on the number (not position): $$$1$$$: Alice can move to any number. She can win by picking $$$7$$$, from which Bob has no move. $$$2$$$: Alice can move to $$$3$$$ and $$$5$$$. Upon moving to $$$5$$$, Bob can win by moving to $$$8$$$. If she chooses $$$3$$$ instead, she wins, as Bob has only a move to $$$4$$$, from which Alice can move to $$$8$$$. $$$3$$$: Alice can only move to $$$4$$$, after which Bob wins by moving to $$$8$$$. $$$4$$$, $$$5$$$, or $$$6$$$: Alice wins by moving to $$$8$$$. $$$7$$$, $$$8$$$: Alice has no move, and hence she loses immediately. "}, "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 topo = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n val win = Array.ofDim[Char](N) // number\u30d9\u30fc\u30b9\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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\dots, p_n$$$. Recall that sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Find three indices $$$i$$$, $$$j$$$ and $$$k$$$ such that: $$$1 \\le i < j < k \\le n$$$; $$$p_i < p_j$$$ and $$$p_j > p_k$$$. Or say that there are no such indices.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 200$$$)\u00a0\u2014 the number of test cases. Next $$$2T$$$ lines contain test cases\u00a0\u2014 two lines per test case. The first line of each test case contains the single integer $$$n$$$ ($$$3 \\le n \\le 1000$$$)\u00a0\u2014 the length of the permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$; $$$p_i \\neq p_j$$$ if $$$i \\neq j$$$)\u00a0\u2014 the permutation $$$p$$$.", "output_spec": "For each test case: if there are such indices $$$i$$$, $$$j$$$ and $$$k$$$, print YES (case insensitive) and the indices themselves; if there are no such indices, print NO (case insensitive). If there are multiple valid triples of indices, print any of them.", "sample_inputs": ["3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 3 1 2 4"], "sample_outputs": ["YES\n2 3 4\nYES\n3 5 6\nNO"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "Tokitsukaze and CSL are playing a little game of stones.In the beginning, there are $$$n$$$ piles of stones, the $$$i$$$-th pile of which has $$$a_i$$$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?Consider an example: $$$n=3$$$ and sizes of piles are $$$a_1=2$$$, $$$a_2=3$$$, $$$a_3=0$$$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $$$[1, 3, 0]$$$ and it is a good move. But if she chooses the second pile then the state will be $$$[2, 2, 0]$$$ and she immediately loses. So the only good move for her is to choose the first pile. Supposing that both players always take their best moves and never make mistakes, who will win the game?Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_1, a_2, \\ldots, a_n \\le 10^9$$$), which mean the $$$i$$$-th pile has $$$a_i$$$ stones.", "output_spec": "Print \"sjfnb\" (without quotes) if Tokitsukaze will win, or \"cslnb\" (without quotes) if CSL will win. Note the output characters are case-sensitive.", "sample_inputs": ["1\n0", "2\n1 0", "2\n2 2", "3\n2 3 1"], "sample_outputs": ["cslnb", "cslnb", "sjfnb", "sjfnb"], "notes": "NoteIn the first example, Tokitsukaze cannot take any stone, so CSL will win.In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.In the third example, Tokitsukaze will win. Here is one of the optimal ways: Firstly, Tokitsukaze can choose the first pile and take a stone from that pile. Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately. Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose. In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n val C = mutable.Map[Int, Int]().withDefaultValue(0)\n REP(N) { i =>\n C(A(i)) += 1\n }\n\n val preCondition = (0 until N forall { i => A(i) >= i }) && {\n val cnt3 = C.count(_._2 > 2)\n val cnt2 = C.count(_._2 == 2)\n cnt3 == 0 && {\n cnt2 == 0 || (cnt2 == 1 && {\n val k = C.find(_._2 == 2).get._1\n debug(s\"cnt2 k:$k\")\n C(k - 1) == 0\n })\n }\n }\n\n if (!preCondition) {\n // 0 1 2 3 4 \u306e\u9806\u756a\u306b\u4e26\u3079\u308c\u306a\u3044\u5834\u5408\u306f\u306a\u306b\u3092\u3068\u3063\u3066\u3082\u91cd\u8907\u3059\u308b\n out.println(\"cslnb\")\n return\n }\n\n val sum = sumL(A)\n val last = N.toLong * (N - 1) / 2\n\n debug(s\"sum:$sum last:$last\")\n if ((sum - last) % 2 == 0) {\n out.println(\"cslnb\")\n } else {\n out.println(\"sjfnb\")\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}\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n val C = mutable.Map[Int, Int]().withDefaultValue(0)\n REP(N) { i =>\n C(A(i)) += 1\n }\n\n val preCondition = (0 until N forall { i => A(i) >= i }) && {\n C.values.forall(_ < 3)\n }\n\n if (!preCondition) {\n // 0 1 2 3 4 \u306e\u9806\u756a\u306b\u4e26\u3079\u308c\u306a\u3044\u5834\u5408\u306f\u306a\u306b\u3092\u3068\u3063\u3066\u3082\u91cd\u8907\u3059\u308b\n out.println(\"cslnb\")\n return\n }\n\n val sum = sumL(A)\n val last = N.toLong * (N - 1) / 2\n\n debug(s\"sum:$sum last:$last\")\n if ((sum - last) % 2 == 0) {\n out.println(\"cslnb\")\n } else {\n out.println(\"sjfnb\")\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}\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n val C = mutable.Map[Int, Int]().withDefaultValue(0)\n REP(N) { i =>\n C(A(i)) += 1\n }\n\n val preCondition = (0 until N forall { i => A(i) >= i }) && {\n C.forall {\n case (k, v) => v < 3 && !(v == 2 && C(k - 1) > 0)\n }\n }\n\n if (!preCondition) {\n // 0 1 2 3 4 \u306e\u9806\u756a\u306b\u4e26\u3079\u308c\u306a\u3044\u5834\u5408\u306f\u306a\u306b\u3092\u3068\u3063\u3066\u3082\u91cd\u8907\u3059\u308b\n out.println(\"cslnb\")\n return\n }\n\n val sum = sumL(A)\n val last = N.toLong * (N - 1) / 2\n\n debug(s\"sum:$sum last:$last\")\n if ((sum - last) % 2 == 0) {\n out.println(\"cslnb\")\n } else {\n out.println(\"sjfnb\")\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}\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n sort(A)\n\n val preCondition = 0 until N forall { i => A(i) >= i }\n if (!preCondition) {\n // 0 1 2 3 4 \u306e\u9806\u756a\u306b\u4e26\u3079\u308c\u306a\u3044\u5834\u5408\u306f\u306a\u306b\u3092\u3068\u3063\u3066\u3082\u91cd\u8907\u3059\u308b\n out.println(\"cslnb\")\n return\n }\n\n val sum = sumL(A)\n val last = N.toLong * (N - 1) / 2\n\n debug(s\"sum:$sum last:$last\")\n if ((sum - last) % 2 == 0) {\n out.println(\"cslnb\")\n } else {\n out.println(\"sjfnb\")\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}"}], "src_uid": "dc225c801f55b8d7b40ebcc71b417edb"} {"nl": {"description": "Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj\u2009<\u2009ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of cards Conan has. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105), where ai is the number on the i-th card.", "output_spec": "If Conan wins, print \"Conan\" (without quotes), otherwise print \"Agasa\" (without quotes).", "sample_inputs": ["3\n4 5 7", "2\n1 1"], "sample_outputs": ["Conan", "Agasa"], "notes": "NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a sequence $$$a_1, a_2, \\dots, a_n$$$ consisting of $$$n$$$ integers.You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $$$k$$$ times.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \\le n \\le 10^{5}, 1 \\le k \\le 10^{14})$$$ \u2014 the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^{9})$$$.", "output_spec": "Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $$$k$$$ times.", "sample_inputs": ["4 5\n3 1 7 5", "3 10\n100 100 100", "10 9\n4 5 5 7 5 4 5 2 4 3"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes $$$[3, 3, 5, 5]$$$, and the difference between maximum and minimum is $$$2$$$. You still can perform one operation after that, but it's useless since you can't make the answer less than $$$2$$$.In the second example all elements are already equal, so you may get $$$0$$$ as the answer even without applying any operations."}, "positive_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: 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"}, {"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"} {"nl": {"description": "Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i\u2009+\u20091)-th weight for any i (1\u2009\u2264\u2009i\u2009<\u2009m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on \u200b\u200bthe scales or to say that it can't be done.", "input_spec": "The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i\u2009\u2265\u20091) character in the line equals \"1\" if Xenia has i kilo weights, otherwise the character equals \"0\". The second line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u20091000).", "output_spec": "In the first line print \"YES\", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line \"NO\". If you can put m weights on the scales, then print in the next line m integers \u2014 the weights' weights in the order you put them on the scales. If there are multiple solutions, you can print any of them.", "sample_inputs": ["0000000101\n3", "1000000000\n2"], "sample_outputs": ["YES\n8 10 8", "NO"], "notes": null}, "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 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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n, 1\u2009\u2264\u2009k\u2009\u2264\u2009m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names \"CBDAD\" and \"AABRD\" and swap their prefixes with the length of 3, the result will be names \"AABAD\" and \"CBDRD\".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The first input line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.", "output_spec": "Print the single number \u2014 the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["2 3\nAAB\nBAA", "4 5\nABABA\nBCGDG\nAAAAA\nYABSA"], "sample_outputs": ["4", "216"], "notes": "NoteIn the first sample Vasya can get the following names in the position number 1: \"AAB\", \"AAA\", \"BAA\" and \"BAB\"."}, "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"}, {"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"}], "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"} {"nl": {"description": "During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.Now she has a table filled with integers. The table consists of n rows and m columns. By ai,\u2009j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai,\u2009j\u2009\u2264\u2009ai\u2009+\u20091,\u2009j for all i from 1 to n\u2009-\u20091.Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai,\u2009j\u2009\u2264\u2009ai\u2009+\u20091,\u2009j for all i from l to r\u2009-\u20091 inclusive.Alyona is too small to deal with this task and asks you to help!", "input_spec": "The first line of the input contains two positive integers n and m (1\u2009\u2264\u2009n\u00b7m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table. Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai,\u2009j (1\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u2009109). The next line of the input contains an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of task that teacher gave to Alyona. The i-th of the next k lines contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print \"Yes\" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print \"No\".", "sample_inputs": ["5 4\n1 2 3 5\n3 1 3 2\n4 5 2 3\n5 5 3 2\n4 4 3 4\n6\n1 1\n2 5\n4 5\n3 5\n1 3\n1 5"], "sample_outputs": ["Yes\nNo\nYes\nYes\nYes\nNo"], "notes": "NoteIn the sample, the whole table is not sorted in any column. However, rows 1\u20133 are sorted in column 1, while rows 4\u20135 are sorted in column 3."}, "positive_code": [{"source_code": "//package solutions\n\nimport java.io.InputStream\nimport java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * @author traff\n */\n\n\nobject SolTaskC extends App {\n\n class FastScanner() {\n\n import java.io.{BufferedReader, FileReader, 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 def this(is: InputStream) {\n this()\n br = new BufferedReader(new InputStreamReader(is))\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 override def main(args: Array[String]): Unit = {\n val out = new PrintWriter(System.out)\n\n // run(new FastScanner(), out)\n run(new Scanner(System.in), out)\n out.close()\n }\n\n // def run(s: FastScanner, out: PrintWriter): Unit = {\n def run(s: Scanner, out: PrintWriter): Unit = {\n val n = s.nextInt()\n val m = s.nextInt()\n\n var a = new Array[Array[Int]](m)\n\n for (i <- 0 until m) {\n a(i) = new Array[Int](n + 2)\n }\n\n\n for (j <- 2 to n + 1) {\n for (i <- 0 until m) {\n a(i)(j) = s.nextInt()\n }\n }\n\n\n for (i <- 0 until m) {\n var k = 0\n a(i)(0) = 0\n for (j <- 3 to n + 1) {\n if (a(i)(j) < a(i)(j - 1)) {\n k = j\n }\n a(i)(j - 2) = k - 2\n }\n }\n\n val min_a = Array.fill(n)(Integer.MAX_VALUE)\n\n for (i <- 0 to n -1) {\n for (j <- 0 until m) {\n if (a(j)(i) < min_a(i)) {\n min_a(i) = a(j)(i)\n }\n }\n }\n\n\n val k = s.nextInt()\n\n for (i <- 1 to k) {\n val l = s.nextInt()\n var r = s.nextInt()\n\n if (min_a(r - 1) < l) {\n out.println(\"Yes\")\n } else {\n out.println(\"No\")\n }\n }\n }\n}\n"}], "negative_code": [{"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\n class FastScanner() {\n\n import java.io.{BufferedReader, FileReader, 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 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 = s.nextInt()\n val m = s.nextInt()\n\n var a = new Array[Array[Int]](m)\n\n for (i <- 0 until m) {\n a(i) = new Array[Int](n+2)\n }\n\n\n for (j <- 2 to n+1) {\n for (i <- 0 until m) {\n a(i)(j) = s.nextInt()\n }\n }\n\n\n for (i <- 0 until m) {\n\n var k = 0\n a(i)(0) = 0\n for (j <- 3 to n+1) {\n if (a(i)(j) < a(i)(j - 1)) {\n k = j\n }\n a(i)(j-2) = k\n }\n }\n\n\n val k = s.nextInt()\n\n for (i <- 1 to k) {\n val l = s.nextInt()\n var r = s.nextInt()\n\n if (a.exists(p => p(r - 1) < l)) {\n out.println(\"Yes\")\n } else {\n out.println(\"No\")\n }\n }\n }\n}\n"}], "src_uid": "f5e57cdca91f36f9b2b20eabbe0d355d"} {"nl": {"description": "In this problem we consider a very simplified model of Barcelona city.Barcelona can be represented as a plane with streets of kind $$$x = c$$$ and $$$y = c$$$ for every integer $$$c$$$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $$$(x, y)$$$ for which $$$ax + by + c = 0$$$.One can walk along streets, including the avenue. You are given two integer points $$$A$$$ and $$$B$$$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $$$B$$$ from $$$A$$$.", "input_spec": "The first line contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$-10^9\\leq a, b, c\\leq 10^9$$$, at least one of $$$a$$$ and $$$b$$$ is not zero) representing the Diagonal Avenue. The next line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9\\leq x_1, y_1, x_2, y_2\\leq 10^9$$$) denoting the points $$$A = (x_1, y_1)$$$ and $$$B = (x_2, y_2)$$$.", "output_spec": "Find the minimum possible travel distance between $$$A$$$ and $$$B$$$. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["1 1 -3\n0 3 3 0", "3 1 -9\n0 3 3 -1"], "sample_outputs": ["4.2426406871", "6.1622776602"], "notes": "NoteThe first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot. "}, "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}"}, {"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"}], "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"} {"nl": {"description": "There are k sensors located in the rectangular room of size n\u2009\u00d7\u2009m meters. The i-th sensor is located at point (xi,\u2009yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0,\u20090) and (n,\u2009m). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0,\u20090) the laser ray is released in the direction of point (1,\u20091). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1,\u20091) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print \u2009-\u20091 for such sensors.", "input_spec": "The first line of the input contains three integers n, m and k (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009100\u2009000)\u00a0\u2014 lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n\u2009-\u20091, 1\u2009\u2264\u2009yi\u2009\u2264\u2009m\u2009-\u20091)\u00a0\u2014 coordinates of the sensors. It's guaranteed that no two sensors are located at the same point.", "output_spec": "Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or \u2009-\u20091 if this will never happen. ", "sample_inputs": ["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"], "sample_outputs": ["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"], "notes": "NoteIn the first sample, the ray will consequently pass through the points (0,\u20090), (1,\u20091), (2,\u20092), (3,\u20093). Thus, it will stop at the point (3,\u20093) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0,\u20090), (1,\u20091), (2,\u20092), (3,\u20093), (2,\u20094), (1,\u20093), (0,\u20092), (1,\u20091), (2,\u20090), (3,\u20091), (2,\u20092), (1,\u20093), (0,\u20094). The ray will stop at the point (0,\u20094) after 12 seconds. It will reflect at the points (3,\u20093), (2,\u20094), (0,\u20092), (2,\u20090) and (3,\u20091). "}, "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"}, {"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"}], "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"} {"nl": {"description": "Ivan has $$$n$$$ songs on his phone. The size of the $$$i$$$-th song is $$$a_i$$$ bytes. Ivan also has a flash drive which can hold at most $$$m$$$ bytes in total. Initially, his flash drive is empty.Ivan wants to copy all $$$n$$$ songs to the flash drive. He can compress the songs. If he compresses the $$$i$$$-th song, the size of the $$$i$$$-th song reduces from $$$a_i$$$ to $$$b_i$$$ bytes ($$$b_i < a_i$$$).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $$$m$$$. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $$$m$$$).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print \"-1\". Otherwise print the minimum number of songs Ivan needs to compress.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^5, 1 \\le m \\le 10^9$$$) \u2014 the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next $$$n$$$ lines contain two integers each: the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le 10^9$$$, $$$a_i > b_i$$$) \u2014 the initial size of the $$$i$$$-th song and the size of the $$$i$$$-th song after compression.", "output_spec": "If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print \"-1\". Otherwise print the minimum number of the songs to compress.", "sample_inputs": ["4 21\n10 8\n7 4\n3 1\n5 4", "4 16\n10 8\n7 4\n3 1\n5 4"], "sample_outputs": ["2", "-1"], "notes": "NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to $$$8 + 7 + 1 + 5 = 21 \\le 21$$$. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal $$$8 + 4 + 3 + 5 = 20 \\le 21$$$. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to $$$10 + 4 + 3 + 5 = 22 > 21$$$).In the second example even if Ivan compresses all the songs the sum of sizes will be equal $$$8 + 4 + 1 + 4 = 17 > 16$$$."}, "positive_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, 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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}"}, {"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}"}], "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"} {"nl": {"description": "You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \\bmod y = a,$$$$$$ $$$$$$y \\bmod z = b,$$$$$$ $$$$$$z \\bmod x = c.$$$$$$Here $$$p \\bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \\le a < b < c \\le 10^8$$$).", "output_spec": "For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \\le x, y, z \\le 10^{18}$$$) such that $$$x \\bmod y = a$$$, $$$y \\bmod z = b$$$, $$$z \\bmod x = c$$$. You can output any correct answer.", "sample_inputs": ["4\n1 3 4\n127 234 421\n2 7 8\n59 94 388"], "sample_outputs": ["12 11 4\n1063 234 1484\n25 23 8\n2221 94 2609"], "notes": "NoteIn the first test case:$$$$$$x \\bmod y = 12 \\bmod 11 = 1;$$$$$$$$$$$$y \\bmod z = 11 \\bmod 4 = 3;$$$$$$$$$$$$z \\bmod x = 4 \\bmod 12 = 4.$$$$$$"}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2,\u20096,\u20091,\u20092,\u20093) is the number 2, and a median of array (0,\u200996,\u200917,\u200923) \u2014 the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.", "input_spec": "The first input line contains two space-separated integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009500, 1\u2009\u2264\u2009x\u2009\u2264\u2009105) \u2014 the initial array's length and the required median's value. The second line contains n space-separated numbers \u2014 the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.", "output_spec": "Print the only integer \u2014 the minimum number of elements Petya needs to add to the array so that its median equals x.", "sample_inputs": ["3 10\n10 20 30", "3 4\n1 2 3"], "sample_outputs": ["1", "4"], "notes": "NoteIn the first sample we can add number 9 to array (10,\u200920,\u200930). The resulting array (9,\u200910,\u200920,\u200930) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4."}, "positive_code": [{"source_code": "\nobject Median extends App {\n val input = io.Source.stdin.getLines\n val (n, median) = {\n val line = input.next.split(\" \").map(_.toInt)\n (line(0), line(1))\n }\n val arr = input.next.split(\" \").map(_.toInt)\n var less = 0\n var greater = 0\n arr foreach { n =>\n if(n > median) greater += 1\n else if(n < median) less += 1\n }\n val numToAdd = List(\n 2 * greater - n,\n 2 * less - n + 1,\n 0).max\n println(numToAdd)\n}"}], "negative_code": [{"source_code": "\nobject Median extends App {\n val input = io.Source.stdin.getLines\n val (n, median) = {\n val line = input.next.split(\" \").map(_.toInt)\n (line(0), line(1))\n }\n val arr = input.next.split(\" \").map(_.toInt)\n var less = 0\n var greater = 0\n arr foreach { n =>\n if(n > median) greater += 1\n else if(n < median) less += 1\n }\n val numToAdd = List(\n 2 * greater - n - 1,\n 2 * less - n - 1).max\n println(numToAdd)\n}"}, {"source_code": "\nobject Median extends App {\n val input = io.Source.stdin.getLines\n val (n, median) = {\n val line = input.next.split(\" \").map(_.toInt)\n (line(0), line(1))\n }\n val arr = input.next.split(\" \").map(_.toInt)\n var less = 0\n var greater = 0\n arr foreach { n =>\n if(n > median) greater += 1\n else if(n < median) less += 1\n }\n val numToAdd = List(\n 2 * greater - n,\n 2 * less - n + 1).max\n println(numToAdd)\n}"}, {"source_code": "\nobject Median extends App {\n val input = io.Source.stdin.getLines\n val (n, median) = {\n val line = input.next.split(\" \").map(_.toInt)\n (line(0), line(1))\n }\n val arr = input.next.split(\" \").map(_.toInt)\n var less = 0\n var eq = 0\n var greater = 0\n arr foreach { n =>\n if(n > median) greater += 1\n else if(n < median) less += 1\n else eq += 1\n }\n val numToAdd = List(\n n - 2 * (greater + eq),\n n - 2 * (less + eq),\n if(eq == 0) 1 else 0).max\n println(numToAdd)\n}"}, {"source_code": "\nobject Median extends App {\n val input = io.Source.stdin.getLines\n val (n, median) = {\n val line = input.next.split(\" \").map(_.toInt)\n (line(0), line(1))\n }\n val arr = input.next.split(\" \").map(_.toInt)\n var less = 0\n var greater = 0\n arr foreach { n =>\n if(n > median) greater += 1\n else if(n < median) less += 1\n }\n val numToAdd = List(\n 2 * greater - n,\n 2 * less - n - 1).max\n println(numToAdd)\n}"}], "src_uid": "1a73bda2b9c2038d6ddf39918b90da61"} {"nl": {"description": "There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $$$1$$$ to $$$n$$$, the junction $$$1$$$ is called the root.A subtree of a junction $$$v$$$ is a set of junctions $$$u$$$ such that the path from $$$u$$$ to the root must pass through $$$v$$$. Note that $$$v$$$ itself is included in a subtree of $$$v$$$.A leaf is such a junction that its subtree contains exactly one junction.The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $$$t$$$ that all light bulbs in the subtree of $$$t$$$ have different colors.Arkady is interested in the following question: for each $$$k$$$ from $$$1$$$ to $$$n$$$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $$$k$$$?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of junctions in the tree. The second line contains $$$n - 1$$$ integers $$$p_2$$$, $$$p_3$$$, ..., $$$p_n$$$ ($$$1 \\le p_i < i$$$), where $$$p_i$$$ means there is a branch between junctions $$$i$$$ and $$$p_i$$$. It is guaranteed that this set of branches forms a tree.", "output_spec": "Output $$$n$$$ integers. The $$$i$$$-th of them should be the minimum number of colors needed to make the number of happy junctions be at least $$$i$$$.", "sample_inputs": ["3\n1 1", "5\n1 1 3 3"], "sample_outputs": ["1 1 2", "1 1 1 2 3"], "notes": "NoteIn the first example for $$$k = 1$$$ and $$$k = 2$$$ we can use only one color: the junctions $$$2$$$ and $$$3$$$ will be happy. For $$$k = 3$$$ you have to put the bulbs of different colors to make all the junctions happy.In the second example for $$$k = 4$$$ you can, for example, put the bulbs of color $$$1$$$ in junctions $$$2$$$ and $$$4$$$, and a bulb of color $$$2$$$ into junction $$$5$$$. The happy junctions are the ones with indices $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ then."}, "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(n) = readInts(1)\n val ps = readInts(n - 1).map(_ - 1)\n\n val childBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n\n for (i <- 0 until n - 1) {\n childBuilders(ps(i)) += i + 1\n }\n\n val children = childBuilders.map(_.result())\n val counts = Array.fill(n)(0)\n\n def dfs(u: Int): Int = {\n if (children(u).isEmpty) {\n counts(u) = 1\n } else {\n var i = 0\n while (i < children(u).length) {\n counts(u) += dfs(children(u)(i))\n i += 1\n }\n }\n counts(u)\n }\n\n dfs(0)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(counts.sorted.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "291bfc61026dddf6c53f4cd9a8aa2baa"} {"nl": {"description": "A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities \u2014 roads cannot be constructed between these pairs of cities.Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.", "input_spec": "The first line consists of two integers n and m . Then m lines follow, each consisting of two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n. It is guaranteed that every pair of cities will appear at most once in the input.", "output_spec": "You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009bi), which means that a road should be constructed between cities ai and bi. If there are several solutions, you may print any of them.", "sample_inputs": ["4 1\n1 3"], "sample_outputs": ["3\n1 2\n4 2\n2 3"], "notes": "NoteThis is one possible solution of the example: These are examples of wrong solutions: The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads. Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3."}, "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"}, {"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}"}], "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"} {"nl": {"description": "You are given a positive integer $$$n$$$, it is guaranteed that $$$n$$$ is even (i.e. divisible by $$$2$$$).You want to construct the array $$$a$$$ of length $$$n$$$ such that: The first $$$\\frac{n}{2}$$$ elements of $$$a$$$ are even (divisible by $$$2$$$); the second $$$\\frac{n}{2}$$$ elements of $$$a$$$ are odd (not divisible by $$$2$$$); all elements of $$$a$$$ are distinct and positive; the sum of the first half equals to the sum of the second half ($$$\\sum\\limits_{i=1}^{\\frac{n}{2}} a_i = \\sum\\limits_{i=\\frac{n}{2} + 1}^{n} a_i$$$). If there are multiple answers, you can print any. It is not guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of the array. It is guaranteed that that $$$n$$$ is even (i.e. divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 \"NO\" (without quotes), if there is no suitable answer for the given test case or \"YES\" in the first line and any suitable array $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) satisfying conditions from the problem statement on the second line.", "sample_inputs": ["5\n2\n4\n6\n8\n10"], "sample_outputs": ["NO\nYES\n2 4 1 5\nNO\nYES\n2 4 6 8 1 3 5 11\nNO"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "You have an array a[1],\u2009a[2],\u2009...,\u2009a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): choose two indexes, i and j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n; (j\u2009-\u2009i\u2009+\u20091) is a prime number); swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp\u2009=\u2009a[i],\u2009a[i]\u2009=\u2009a[j],\u2009a[j]\u2009=\u2009tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n distinct integers a[1],\u2009a[2],\u2009...,\u2009a[n] (1\u2009\u2264\u2009a[i]\u2009\u2264\u2009n).", "output_spec": "In the first line, print integer k (0\u2009\u2264\u2009k\u2009\u2264\u20095n) \u2014 the number of used operations. Next, print the operations. Each operation must be printed as \"i j\" (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n; (j\u2009-\u2009i\u2009+\u20091) is a prime). If there are multiple answers, you can print any of them.", "sample_inputs": ["3\n3 2 1", "2\n1 2", "4\n4 2 3 1"], "sample_outputs": ["1\n1 3", "0", "3\n2 4\n1 2\n2 4"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.ArrayBuffer\nimport java.io.PrintWriter\n\n/**\n * Created by hama_du on 2014/05/18.\n */\nobject ProblemC extends App {\n val in = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n val result = new ArrayBuffer[(Int,Int)]()\n\n val n = in.nextInt()\n val a = (0 until n).map(_ => in.nextInt()-1).toArray\n val positions = new Array[Int](n)\n (0 until n).foreach(i => {\n positions(a(i)) = i\n })\n val primes = generatePrimes(100000)\n\n (n-1 until 0 by -1).foreach(idx => {\n val needToMove = (idx - positions(idx))\n solve(needToMove).foreach(p => {\n result += ((positions(idx)+1, positions(idx)+p))\n swap(positions(idx), positions(idx)+p-1, positions, a)\n })\n })\n\n\n out.println(result.size)\n result.foreach(p => {\n out.println(p._1 + \" \" + p._2)\n })\n out.flush()\n\n def swap(p: Int, q: Int, positions: Array[Int], a: Array[Int]) {\n val x = a(p)\n val y = a(q)\n a(p) = y\n a(q) = x\n positions(x) = q\n positions(y) = p\n }\n\n def primeTable(p: Int, primes: Array[Boolean]) {\n if (p*p < primes.length) {\n if (primes(p)) {\n for (i <- p*2 until primes.length by p) {\n primes(i) = false\n }\n }\n primeTable(p+1, primes)\n }\n }\n\n def generatePrimes(upto: Int): Array[Int] = {\n val primes = Array.fill[Boolean](upto)(true)\n primes(0) = false\n primes(1) = false\n primeTable(2, primes)\n (0 until upto).map(i => i).filter(p => primes(p)).toArray\n }\n\n\n def solve(sum: Int): List[Int] = {\n if (sum == 0) {\n List()\n } else {\n val picked = binarySearch(-1, primes.size, sum, primes)\n picked :: solve(sum - (picked - 1))\n }\n }\n\n def binarySearch(min: Int, max: Int, find: Int, primes: Array[Int]): Int = {\n if (max - min <= 1) {\n primes(min)\n } else {\n val med = (min + max) / 2\n if (primes(med) - 1 <= find) {\n binarySearch(med, max, find, primes)\n } else {\n binarySearch(min, med, find, primes)\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "c943a6413441651ec9f420ef44ea48d0"} {"nl": {"description": "Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once: Polycarp chooses $$$k$$$ ($$$0 \\le k \\le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \\ldots, i_k$$$); Polycarp distributes their $$$a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies: Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output: the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way; \"-1\" if no such value $$$k$$$ exists. ", "sample_inputs": ["5\n4\n4 5 2 5\n2\n0 4\n5\n10 8 5 1 4\n1\n10000\n7\n1 1 1 1 1 1 1"], "sample_outputs": ["2\n1\n-1\n0\n0"], "notes": null}, "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(_.toLong)\r\n\r\n val s = an.sum\r\n\r\n val ans =\r\n if (s % n != 0) -1\r\n else {\r\n val g = s / n\r\n an.count(_ > g)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "b8554e64b92b1b9458955da7d55eba62"} {"nl": {"description": "Alice and Bob are playing a game on a line with $$$n$$$ cells. There are $$$n$$$ cells labeled from $$$1$$$ through $$$n$$$. For each $$$i$$$ from $$$1$$$ to $$$n-1$$$, cells $$$i$$$ and $$$i+1$$$ are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $$$x_1, x_2, \\ldots, x_k$$$ in order. In the $$$i$$$-th question, Bob asks Alice if her token is currently on cell $$$x_i$$$. That is, Alice can answer either \"YES\" or \"NO\" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer \"NO\" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given $$$n$$$ and Bob's questions $$$x_1, \\ldots, x_k$$$. You would like to count the number of scenarios that let Alice answer \"NO\" to all of Bob's questions. Let $$$(a,b)$$$ denote a scenario where Alice starts at cell $$$a$$$ and ends at cell $$$b$$$. Two scenarios $$$(a_i, b_i)$$$ and $$$(a_j, b_j)$$$ are different if $$$a_i \\neq a_j$$$ or $$$b_i \\neq b_j$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n,k \\leq 10^5$$$)\u00a0\u2014 the number of cells and the number of questions Bob asked. The second line contains $$$k$$$ integers $$$x_1, x_2, \\ldots, x_k$$$ ($$$1 \\leq x_i \\leq n$$$)\u00a0\u2014 Bob's questions.", "output_spec": "Print a single integer, the number of scenarios that let Alice answer \"NO\" to all of Bob's questions.", "sample_inputs": ["5 3\n5 1 4", "4 8\n1 2 3 4 4 3 2 1", "100000 1\n42"], "sample_outputs": ["9", "0", "299997"], "notes": "NoteThe notation $$$(i,j)$$$ denotes a scenario where Alice starts at cell $$$i$$$ and ends at cell $$$j$$$.In the first example, the valid scenarios are $$$(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$$$. For example, $$$(3,4)$$$ is valid since Alice can start at cell $$$3$$$, stay there for the first three questions, then move to cell $$$4$$$ after the last question. $$$(4,5)$$$ is valid since Alice can start at cell $$$4$$$, stay there for the first question, the move to cell $$$5$$$ for the next two questions. Note that $$$(4,5)$$$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all $$$(i,j)$$$ where $$$|i-j| \\leq 1$$$ except for $$$(42, 42)$$$ are valid scenarios."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "Professor Ibrahim has prepared the final homework for his algorithm\u2019s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group\u2019s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color\u2019s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$1 \\leq k \\leq 256$$$), the number of pixels in the image, and the maximum size of a group, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$0 \\leq p_i \\leq 255$$$), where $$$p_i$$$ is the color of the $$$i$$$-th pixel.", "output_spec": "Print $$$n$$$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.", "sample_inputs": ["4 3\n2 14 3 4", "5 2\n0 2 1 255 254"], "sample_outputs": ["0 12 3 3", "0 1 1 254 254"], "notes": "NoteOne possible way to group colors and assign keys for the first sample:Color $$$2$$$ belongs to the group $$$[0,2]$$$, with group key $$$0$$$.Color $$$14$$$ belongs to the group $$$[12,14]$$$, with group key $$$12$$$.Colors $$$3$$$ and $$$4$$$ belong to group $$$[3, 5]$$$, with group key $$$3$$$.Other groups won't affect the result so they are not listed here."}, "positive_code": [{"source_code": "import scala.io.StdIn;\n\nobject Main {\n def main(args: Array[String]): Unit = {\n val Array(n, k) = IO.readInts\n val xs = IO.readInts\n\n var m = Map[Int, Int]()\n\n def getGroupKey(x: Int) = m.get(x).getOrElse(x)\n\n val result = for (x <- xs) yield {\n if (m.contains(x)) {\n m(x)\n } else {\n val Some(newKey) =\n ((x - k + 1) to x) find(getGroupKey(_) > Math.max(x - k, -1)) \n val newUsed = newKey to x \n m = m ++ (newUsed map (_->newKey))\n newKey\n }\n }\n\n println(result.mkString(\" \"))\n }\n} \n\nobject IO {\n def readInts = readLine split(\" \") map (_.toInt)\n def readLongs = readLine split(\" \") map (_.toLong)\n def readDoubles = readLine split(\" \") map (_.toDouble)\n}\n\n"}], "negative_code": [], "src_uid": "deed251d324f7bbe53eefa94f92c3bbc"} {"nl": {"description": "The only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of $$$n$$$ students. Students will take the exam one-by-one in order from $$$1$$$-th to $$$n$$$-th. Rules of the exam are following: The $$$i$$$-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly $$$t_i$$$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is $$$M$$$ minutes ($$$\\max t_i \\le M$$$), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student $$$i$$$, you should count the minimum possible number of students who need to fail the exam so the $$$i$$$-th student has enough time to pass the exam.For each student $$$i$$$, find the answer independently. That is, if when finding the answer for the student $$$i_1$$$ some student $$$j$$$ should leave, then while finding the answer for $$$i_2$$$ ($$$i_2>i_1$$$) the student $$$j$$$ student does not have to go home.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$M$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le M \\le 2 \\cdot 10^7$$$)\u00a0\u2014 the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $$$n$$$ integers $$$t_i$$$ ($$$1 \\le t_i \\le 100$$$)\u00a0\u2014 time in minutes that $$$i$$$-th student spends to answer to a ticket. It's guaranteed that all values of $$$t_i$$$ are not greater than $$$M$$$.", "output_spec": "Print $$$n$$$ numbers: the $$$i$$$-th number must be equal to the minimum number of students who have to leave the exam in order to $$$i$$$-th student has enough time to pass the exam.", "sample_inputs": ["7 15\n1 2 3 4 5 6 7", "5 100\n80 40 40 40 60"], "sample_outputs": ["0 0 0 0 0 2 3", "0 1 1 2 3"], "notes": "NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed $$$M=15$$$ (the sum is $$$1+2+3+4+5=15$$$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $$$0$$$.In order for the $$$6$$$-th student to pass the exam, it is necessary that at least $$$2$$$ students must fail it before (for example, the $$$3$$$-rd and $$$4$$$-th, then the $$$6$$$-th will finish its exam in $$$1+2+5+6=14$$$ minutes, which does not exceed $$$M$$$).In order for the $$$7$$$-th student to pass the exam, it is necessary that at least $$$3$$$ students must fail it before (for example, the $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th, then the $$$7$$$-th will finish its exam in $$$1+3+4+7=15$$$ minutes, which does not exceed $$$M$$$)."}, "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[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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val T = na(N)\n val C = Array.ofDim[Int](101)\n val ans = Array.ofDim[Int](N)\n REP(N) { i =>\n var remain = M - T(i)\n var cnt = 0\n REP(100, 1) { j =>\n val unit = min(remain / j, C(j))\n remain -= unit * j\n cnt += unit\n }\n ans(i) = max(0, i - cnt)\n C(T(i)) += 1\n }\n\n out.println(ans.mkString(\" \"))\n }\n}"}], "negative_code": [], "src_uid": "fe3a6f0d33b1b5b8018e1810ba8ebdd6"} {"nl": {"description": "In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time \"0 hours\", instead of it \"n hours\" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.Help platform select such an hour, that the number of people who will participate in the contest is maximum. ", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of hours in day. The second line contains n space-separated integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u200910\u2009000), where ai is the number of people in the i-th timezone who want to participate in the contest. The third line contains two space-separated integers s and f (1\u2009\u2264\u2009s\u2009<\u2009f\u2009\u2264\u2009n).", "output_spec": "Output a single integer\u00a0\u2014 the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.", "sample_inputs": ["3\n1 2 3\n1 3", "5\n1 2 3 4 1\n1 3"], "sample_outputs": ["3", "4"], "notes": "NoteIn the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.In second example only people from the third and the fourth timezones will participate."}, "positive_code": [{"source_code": "object CF939C extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val a = Array.fill[Int](n)(sc.nextInt)\n val s, f = sc.nextInt\n val participate = (1 to n) map (checkTime)\n val ans = (nextJoin(0, List(countJoin(0))))\n val am = ans.max\n println(n - (ans lastIndexWhere(_ == am)))\n\n def checkTime(n:Int) = {\n n >= s && n < f\n }\n\n def countJoin(j:Int) = {\n ((0 until n) map (i => participate((i + j) % n)) zipWithIndex) filter (_._1) map (i => a(i._2)) sum\n }\n\n def nextJoin(offset:Int, p:Seq[Int]):Seq[Int] = {\n //println(p, (f-2-offset+n) % n, (s-2-offset+n) % n, a((f-2-offset+n) % n), a((s-2-offset+n) % n))\n val here = p.head - a((f-2-offset+n) % n) + a((s-2-offset+n) % n)\n if(offset == n-1) p else nextJoin(offset+1, here +: p)\n }\n}\n"}], "negative_code": [{"source_code": "object CF939C extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt\n val a = Array.fill[Int](n)(sc.nextInt)\n val s, f = sc.nextInt\n val participate = (1 to n) map (checkTime)\n val ans = (nextJoin(0, List(countJoin(0))))\n val am = ans.max\n println(n - (ans indexWhere(_ == am)))\n\n def checkTime(n:Int) = {\n n >= s && n < f\n }\n\n def countJoin(j:Int) = {\n ((0 until n) map (i => participate((i + j) % n)) zipWithIndex) filter (_._1) map (i => a(i._2)) sum\n }\n\n def nextJoin(offset:Int, p:List[Int]):List[Int] = {\n //println(p, (f-2-offset+n) % n, (s-2-offset+n) % n, a((f-2-offset+n) % n), a((s-2-offset+n) % n))\n val here = p.head - a((f-2-offset+n) % n) + a((s-2-offset+n) % n)\n if(offset == n-1) p else nextJoin(offset+1, here +: p)\n }\n}"}, {"source_code": "object CF939C 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 s, f = sc.nextInt\n val participate = (1 to n) map (checkTime)\n val ans = (nextJoin(0, Seq(countJoin(0))))\n val am = ans.max\n println((ans indexWhere(_ == am)) + 1)\n\n def checkTime(n:Int) = {\n n >= s && n < f\n }\n\n def countJoin(j:Int) = {\n ((0 until n) map (i => participate((i + j) % n)) zipWithIndex) filter (_._1) map (i => a(i._2)) sum\n }\n\n def nextJoin(offset:Int, p:Seq[Int]):Seq[Int] = {\n //println(p, (f-2-offset+n) % n, (s-2-offset+n) % n, a((f-2-offset+n) % n), a((s-2-offset+n) % n))\n val here = p.head - a((f-2-offset+n) % n) + a((s-2-offset+n) % n)\n if(offset == n-1) p else nextJoin(offset+1, here +: p)\n }\n}"}], "src_uid": "7f3d3112f662caac747ca9c32de4e658"} {"nl": {"description": "Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone: Initially he stands in the end of the queue in front of the first entrance. Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$)\u00a0\u2014 the number of people in queues. These numbers do not include Allen.", "output_spec": "Print a single integer\u00a0\u2014 the number of entrance that Allen will use.", "sample_inputs": ["4\n2 3 2 0", "2\n10 10", "6\n5 2 6 5 7 4"], "sample_outputs": ["3", "1", "6"], "notes": "NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\\textbf{2}, 3, 2, 0] \\to [1, \\textbf{2}, 1, 0] \\to [0, 1, \\textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\\textbf{10}, 10] \\to [9, \\textbf{9}] \\to [\\textbf{8}, 8] \\to [7, \\textbf{7}] \\to [\\textbf{6}, 6] \\to \\\\ [5, \\textbf{5}] \\to [\\textbf{4}, 4] \\to [3, \\textbf{3}] \\to [\\textbf{2}, 2] \\to [1, \\textbf{1}] \\to [\\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\\textbf{5}, 2, 6, 5, 7, 4] \\to [4, \\textbf{1}, 5, 4, 6, 3] \\to [3, 0, \\textbf{4}, 3, 5, 2] \\to \\\\ [2, 0, 3, \\textbf{2}, 4, 1] \\to [1, 0, 2, 1, \\textbf{3}, 0] \\to [0, 0, 1, 0, 2, \\textbf{0}]$$$."}, "positive_code": [{"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"}, {"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": "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}"}], "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"} {"nl": {"description": "You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \\le x, y \\le r$$$, $$$x \\ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 998244353$$$) \u2014 inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.", "output_spec": "Print $$$T$$$ lines, each line should contain the answer \u2014 two integers $$$x$$$ and $$$y$$$ such that $$$l \\le x, y \\le r$$$, $$$x \\ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.", "sample_inputs": ["3\n1 10\n3 14\n1 10"], "sample_outputs": ["1 7\n3 9\n5 10"], "notes": null}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n\u2009-\u20091 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day \u0410 and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of rooms in the University. The next n\u2009-\u20091 lines describe the corridors. The i-th of these lines (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of queries. Next m lines describe the queries. The j-th of these lines (1\u2009\u2264\u2009j\u2009\u2264\u2009m) contains two integers xj and yj (1\u2009\u2264\u2009xj,\u2009yj\u2009\u2264\u2009n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.", "output_spec": "In the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.", "sample_inputs": ["4\n1 2\n1 3\n2 4\n1\n2 3", "4\n1 2\n2 3\n2 4\n2\n1 2\n1 3"], "sample_outputs": ["1", "0\n2"], "notes": "Notein the first sample there is only one room at the same distance from rooms number 2 and 3 \u2014 room number 1."}, "positive_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 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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "One day, at the \"Russian Code Cup\" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member \u2014 Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.", "input_spec": "The first line contains two integers \u2014 n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20091000).", "output_spec": "In the first line print an integer m \u2014 number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n; ai\u2009\u2260\u2009bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.", "sample_inputs": ["3 1"], "sample_outputs": ["3\n1 2\n2 3\n3 1"], "notes": null}, "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 if (n >= 2 * k + 1) {\n val res = (1 to n).flatMap { i =>\n (1 to k).map { j =>\n if (i + j > n)\n (i, i + j - n)\n else\n (i, i + j)\n }\n }\n println(n * k)\n println(res.map(t => s\"${t._1} ${t._2}\").mkString(\"\\n\"))\n }\n else println(-1)\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 (n >= k + 1) {\n val res = (1 to n).flatMap { i =>\n (1 to k).map { j =>\n if (i + j > n)\n (i, i + j - n)\n else\n (i, i + j)\n }\n }\n println(n * k)\n println(res.map(t => s\"${t._1} ${t._2}\").mkString(\"\\n\"))\n }\n else println(-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 if (n >= k + 1) {\n val res = (1 to n).flatMap { i =>\n (1 to k).map { j =>\n if (i + j > n)\n (i, i + j - n)\n else\n (i, i + j)\n }\n }\n println(res.map(t => s\"${t._1} ${t._2}\").mkString(\"\\n\"))\n }\n else println(-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 if (n >= k * (k - 1) / 2) {\n val res = (1 to n).flatMap { i =>\n (1 to k).map { j =>\n if (i + j > n)\n (i, i + j - n)\n else\n (i, i + j)\n }\n }\n println(n * k)\n println(res.map(t => s\"${t._1} ${t._2}\").mkString(\"\\n\"))\n }\n else println(-1)\n}"}], "src_uid": "14570079152bbf6c439bfceef9816f7e"} {"nl": {"description": "You have a long stick, consisting of $$$m$$$ segments enumerated from $$$1$$$ to $$$m$$$. Each segment is $$$1$$$ centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $$$t$$$ placed at some position $$$s$$$ will cover segments $$$s, s+1, \\ldots, s+t-1$$$.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most $$$k$$$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n \\le 10^5$$$, $$$n \\le m \\le 10^9$$$, $$$1 \\le k \\le n$$$)\u00a0\u2014 the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le m$$$)\u00a0\u2014 the positions of the broken segments. These integers are given in increasing order, that is, $$$b_1 < b_2 < \\ldots < b_n$$$.", "output_spec": "Print the minimum total length of the pieces.", "sample_inputs": ["4 100 2\n20 30 75 80", "5 100 3\n1 2 4 60 87"], "sample_outputs": ["17", "6"], "notes": "NoteIn the first example, you can use a piece of length $$$11$$$ to cover the broken segments $$$20$$$ and $$$30$$$, and another piece of length $$$6$$$ to cover $$$75$$$ and $$$80$$$, for a total length of $$$17$$$.In the second example, you can use a piece of length $$$4$$$ to cover broken segments $$$1$$$, $$$2$$$ and $$$4$$$, and two pieces of length $$$1$$$ to cover broken segments $$$60$$$ and $$$87$$$."}, "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 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"}, {"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"} {"nl": {"description": "This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \\le i,j \\le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$. Can he succeed?Note that he has to perform this operation exactly once. He has to perform this operation.", "input_spec": "The first line contains a single integer $$$k$$$ ($$$1 \\leq k \\leq 10$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 10^4$$$), the length of the strings $$$s$$$ and $$$t$$$. Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.", "output_spec": "For each test case, output \"Yes\" if Ujan can make the two strings equal and \"No\" otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n5\nsouse\nhouhe\n3\ncat\ndog\n2\naa\naz\n3\nabc\nbca"], "sample_outputs": ["Yes\nNo\nNo\nNo"], "notes": "NoteIn the first test case, Ujan can swap characters $$$s_1$$$ and $$$t_4$$$, obtaining the word \"house\".In the second test case, it is not possible to make the strings equal using exactly one swap of $$$s_i$$$ and $$$t_j$$$."}, "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": "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"}, {"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": "\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"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ with $$$n$$$ integers. You can perform the following operation at most $$$k$$$ times: Choose two indices $$$i$$$ and $$$j$$$, in which $$$i \\,\\bmod\\, k = j \\,\\bmod\\, k$$$ ($$$1 \\le i < j \\le n$$$). Swap $$$a_i$$$ and $$$a_j$$$. After performing all operations, you have to select $$$k$$$ consecutive elements, and the sum of the $$$k$$$ elements becomes your score. Find the maximum score you can get.Here $$$x \\bmod y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 600$$$)\u00a0\u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 100$$$)\u00a0\u2014 the length of the array and the number in the statement above. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$) \u00a0\u2014 the array itself.", "output_spec": "For each test case, print the maximum score you can get, one per line.", "sample_inputs": ["5\n\n3 2\n\n5 6 0\n\n1 1\n\n7\n\n5 3\n\n7 0 4 0 4\n\n4 2\n\n2 7 3 4\n\n3 3\n\n1000000000 1000000000 999999997"], "sample_outputs": ["11\n7\n15\n10\n2999999997"], "notes": "NoteIn the first test case, we can get a score of $$$11$$$ if we select $$$a_1, a_2$$$ without performing any operations.In the third test case, we can get a score of $$$15$$$ if we first swap $$$a_1$$$ with $$$a_4$$$ and then select $$$a_3, a_4, a_5$$$. "}, "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}"}, {"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"}], "negative_code": [], "src_uid": "f974c33780a933a6076c0559e48b7552"} {"nl": {"description": "General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u200950; 1\u2009\u2264\u2009k\u2009\u2264\u2009 ) \u2014 the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107) \u2014 the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.", "output_spec": "Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) \u2014 the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1,\u2009i,\u2009p2,\u2009i,\u2009...,\u2009pci,\u2009i \u2014 the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them.", "sample_inputs": ["3 3\n1 2 3", "2 1\n7 12"], "sample_outputs": ["1 1\n1 2\n2 3 2", "1 12"], "notes": null}, "positive_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, k = sc.nextInt()\n val a = Array.tabulate(n)(_ => sc.nextInt())\n\n val mm = Map[Int, List[Int]]()\n\n for (i <- 0 until n if mm.size <= k) {\n val nm = mm map { x => (x._1 + a(i), x._2 :+ a(i)) } filter { x => !mm.contains(x._1) }\n mm ++= nm\n mm(a(i)) = List(a(i))\n }\n\n mm.take(k) foreach { x =>\n println(x._2.size + \" \" + x._2.mkString(\" \"))\n }\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, k = sc.nextInt()\n val a = Array.tabulate(n)(_ => sc.nextInt())\n\n val mm = Map[Int, List[Int]]()\n\n for (i <- 0 until n if mm.size <= k) {\n val nm = mm map { x => (x._1 + a(i), x._2 :+ (i+1)) } filter { x => !mm.contains(x._1) }\n mm ++= nm\n mm(a(i)) = List(i+1)\n }\n\n mm.take(k) foreach { x =>\n println(x._2.size + \" \" + x._2.mkString(\" \"))\n }\n}\n"}], "src_uid": "2b77aa85a192086316a7f87ce140112d"} {"nl": {"description": "Polycarp likes arithmetic progressions. A sequence $$$[a_1, a_2, \\dots, a_n]$$$ is called an arithmetic progression if for each $$$i$$$ ($$$1 \\le i < n$$$) the value $$$a_{i+1} - a_i$$$ is the same. For example, the sequences $$$[42]$$$, $$$[5, 5, 5]$$$, $$$[2, 11, 20, 29]$$$ and $$$[3, 2, 1, 0]$$$ are arithmetic progressions, but $$$[1, 0, 1]$$$, $$$[1, 3, 9]$$$ and $$$[2, 3, 1]$$$ are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers $$$[b_1, b_2, \\dots, b_n]$$$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $$$1$$$, an element can be increased by $$$1$$$, an element can be left unchanged.Determine a minimum possible number of elements in $$$b$$$ which can be changed (by exactly one), so that the sequence $$$b$$$ becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals $$$0$$$.", "input_spec": "The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 100\\,000)$$$ \u2014 the number of elements in $$$b$$$. The second line contains a sequence $$$b_1, b_2, \\dots, b_n$$$ $$$(1 \\le b_i \\le 10^{9})$$$.", "output_spec": "If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer \u2014 the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).", "sample_inputs": ["4\n24 21 14 10", "2\n500 500", "3\n14 5 1", "5\n1 3 6 9 12"], "sample_outputs": ["3", "0", "-1", "1"], "notes": "NoteIn the first example Polycarp should increase the first number on $$$1$$$, decrease the second number on $$$1$$$, increase the third number on $$$1$$$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $$$[25, 20, 15, 10]$$$, which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $$$[0, 3, 6, 9, 12]$$$, which is an arithmetic progression."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "79b0794f81acc1c882649d96b1c7f8da"} {"nl": {"description": "You are given an array $$$d_1, d_2, \\dots, d_n$$$ consisting of $$$n$$$ integer numbers.Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then:$$$$$$sum_1 = \\sum\\limits_{1 \\le i \\le a}d_i,$$$$$$ $$$$$$sum_2 = \\sum\\limits_{a + 1 \\le i \\le a + b}d_i,$$$$$$ $$$$$$sum_3 = \\sum\\limits_{a + b + 1 \\le i \\le a + b + c}d_i.$$$$$$The sum of an empty array is $$$0$$$.Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \\dots, d_n$$$ ($$$1 \\le d_i \\le 10^9$$$) \u2014 the elements of the array $$$d$$$.", "output_spec": "Print a single integer \u2014 the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).", "sample_inputs": ["5\n1 3 1 1 4", "5\n1 3 2 1 4", "3\n4 1 2"], "sample_outputs": ["5", "4", "0"], "notes": "NoteIn the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$.In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$.In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$."}, "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 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}"}, {"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"} {"nl": {"description": "This is an interactive problem.You're given a tree consisting of $$$n$$$ nodes, rooted at node $$$1$$$. A tree is a connected graph with no cycles.We chose a hidden node $$$x$$$. In order to find this node, you can ask queries of two types: d $$$u$$$ ($$$1 \\le u \\le n$$$). We will answer with the distance between nodes $$$u$$$ and $$$x$$$. The distance between two nodes is the number of edges in the shortest path between them. s $$$u$$$ ($$$1 \\le u \\le n$$$). We will answer with the second node on the path from $$$u$$$ to $$$x$$$. However, there's a plot twist. If $$$u$$$ is not an ancestor of $$$x$$$, you'll receive \"Wrong answer\" verdict! Node $$$a$$$ is called an ancestor of node $$$b$$$ if $$$a \\ne b$$$ and the shortest path from node $$$1$$$ to node $$$b$$$ passes through node $$$a$$$. Note that in this problem a node is not an ancestor of itself.Can you find $$$x$$$ in no more than $$$36$$$ queries? The hidden node is fixed in each test beforehand and does not depend on your queries.", "input_spec": "The first line contains the integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \\le u,v \\le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.", "output_spec": "To print the answer, print \"! x\" (without quotes).", "sample_inputs": ["5\n1 2\n1 3\n3 4\n3 5\n3\n5"], "sample_outputs": ["d 2\ns 3\n! 5"], "notes": "NoteIn the first example, the hidden node is node $$$5$$$. We first ask about the distance between node $$$x$$$ and node $$$2$$$. The answer is $$$3$$$, so node $$$x$$$ is either $$$4$$$ or $$$5$$$. We then ask about the second node in the path from node $$$3$$$ to node $$$x$$$. Note here that node $$$3$$$ is an ancestor of node $$$5$$$. We receive node $$$5$$$ as the answer. Finally, we report that the hidden node is node $$$5$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n\n def query(v: Int, tpe: Char): Int = {\n out.println(s\"$tpe ${v+1}\")\n out.flush()\n ni()\n }\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (depth, parent, queue) = traceBfs(g)\n val sz = Array.fill[Int](N)(1)\n REP_r(N) { i =>\n val v = queue(i)\n if (parent(v) != -1) sz(parent(v)) += sz(v)\n }\n debug(sz)\n\n def heavyPath(rt: Int): ArrayBuffer[Int] = {\n val res = ArrayBuffer[Int](rt)\n var it = rt\n while(it != -1) {\n var next = -1\n REP(g(it).length) { i =>\n val u = g(it)(i)\n if (parent(it) != u && (next == -1 || sz(u) > sz(next))) {\n next = u\n }\n }\n if (next != -1) res += next\n it = next\n }\n res\n }\n\n def step(rt: Int, d1: Int): Int = {\n val path = heavyPath(rt)\n debug(path.mkString(\" \"))\n val w = path.last\n if (rt == w) rt\n else {\n val d2 = query(w, 'd')\n val dist = depth(w) - depth(rt)\n\n debug(s\"rt:$rt w:$w d1:$d1 d2:$d2 dist:$dist\")\n\n if (dist == d1 + d2) {\n path(d1)\n } else {\n val d = (d1 + d2 - dist) / 2\n val joint = path(d1 - d)\n val next = query(joint, 's') - 1\n step(next, d - 1)\n }\n }\n }\n\n val ans = step(0, query(0, 'd'))\n out.println(s\"! ${ans+1}\")\n out.flush()\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": [{"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n var queryCnt = 36\n\n def query1(v: Int): Int = {\n queryCnt -= 1\n out.println(s\"d ${v+1}\")\n out.flush()\n ni()\n }\n\n def query2(v: Int): Int = {\n queryCnt -= 1\n out.println(s\"s ${v+1}\")\n out.flush()\n ni() - 1\n }\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (depth, parent, _) = traceBfs(g)\n debug(depth)\n debug(parent)\n\n def farthest(rt: Int): Int = {\n val n = g.length\n val q = Array.ofDim[Int](n)\n q(0) = rt\n var cur = 0\n var last = 1\n\n var farthest = rt\n\n while (cur < last) {\n val v = q(cur)\n if (depth(v) > depth(farthest)) farthest = v\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (u != parent(v)) {\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n\n farthest\n }\n\n def up(s: Int, cnt: Int): Int = {\n var it = s\n REP(cnt) { _ =>\n it = parent(it)\n }\n it\n }\n\n def step(rt: Int, d1: Int): Int = {\n if (queryCnt >= d1) {\n var it = rt\n REP(d1) { _ =>\n it = query2(it)\n }\n return it\n }\n\n val u = farthest(rt)\n if (u == rt) return rt\n\n val d = depth(u) - depth(rt)\n debug(s\"rt:$rt u:$u d:$d\")\n val d2 = query1(u)\n debug(s\"d1:$d1 d2:$d2\")\n if (d1 + d2 == d) {\n up(u, d2)\n } else {\n val dd = (d1 + d2 - d) / 2\n val dd2 = d2 - dd\n val joint = up(u, dd2)\n step(query2(joint), dd - 1)\n }\n }\n\n val ans = step(0, query1(0))\n out.println(s\"! ${ans+1}\")\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n var queryCnt = 36\n\n def query1(v: Int): Int = {\n queryCnt -= 1\n out.println(s\"d ${v+1}\")\n out.flush()\n ni()\n }\n\n def query2(v: Int): Int = {\n queryCnt -= 1\n out.println(s\"s ${v+1}\")\n out.flush()\n ni() - 1\n }\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (depth, parent, _) = traceBfs(g)\n debug(depth)\n debug(parent)\n\n def farthest(rt: Int): Int = {\n val n = g.length\n val q = Array.ofDim[Int](n)\n q(0) = rt\n var cur = 0\n var last = 1\n\n var farthest = rt\n\n while (cur < last) {\n val v = q(cur)\n if (depth(v) > depth(farthest)) farthest = v\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (u != parent(v)) {\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n\n farthest\n }\n\n def downUntilJoint(rt: Int): (Int, Int) = {\n var cur = rt\n var cnt = 0\n\n while (g(cur).length == 2) {\n REP(g(rt).length) { i =>\n if (g(rt)(i) != parent(cur)) {\n cur = g(rt)(i)\n }\n }\n cnt += 1\n }\n (cur, cnt)\n }\n\n def up(s: Int, cnt: Int): Int = {\n var it = s\n REP(cnt) { _ =>\n it = parent(it)\n }\n it\n }\n\n def step(rt: Int, d1: Int): Int = {\n if (queryCnt >= d1) {\n var it = rt\n REP(d1) { _ =>\n it = query2(it)\n }\n return it\n }\n\n val u = farthest(rt)\n if (u == rt) return rt\n\n val d = depth(u) - depth(rt)\n debug(s\"rt:$rt u:$u d:$d\")\n val d2 = query1(u)\n debug(s\"d1:$d1 d2:$d2\")\n if (d1 + d2 == d) {\n up(u, d2)\n } else {\n val dd = (d1 + d2 - d) / 2\n val dd2 = d2 - dd\n val joint = up(u, dd2)\n val (nextRt, move) = downUntilJoint(joint)\n step(query2(nextRt), dd - move - 1)\n }\n }\n\n val ans = step(0, query1(0))\n out.println(s\"! ${ans+1}\")\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def query1(v: Int): Int = {\n out.println(s\"d ${v+1}\")\n out.flush()\n ni()\n }\n\n def query2(v: Int): Int = {\n out.println(s\"s ${v+1}\")\n out.flush()\n ni() - 1\n }\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (depth, parent, _) = traceBfs(g)\n debug(depth)\n debug(parent)\n\n def farthest(rt: Int): Int = {\n val n = g.length\n val q = Array.ofDim[Int](n)\n q(0) = rt\n var cur = 0\n var last = 1\n\n var farthest = rt\n\n while (cur < last) {\n val v = q(cur)\n if (depth(v) > depth(farthest)) farthest = v\n REP(g(v).length) { i =>\n val u = g(v)(i)\n if (u != parent(v)) {\n q(last) = u\n last += 1\n }\n }\n cur += 1\n }\n\n farthest\n }\n\n def up(s: Int, cnt: Int): Int = {\n var it = s\n REP(cnt) { _ =>\n it = parent(it)\n }\n it\n }\n\n def step(rt: Int, d1: Int): Int = {\n val u = farthest(rt)\n if (u == rt) return rt\n\n val d = depth(u) - depth(rt)\n debug(s\"rt:$rt u:$u d:$d\")\n val d2 = query1(u)\n debug(s\"d1:$d1 d2:$d2\")\n if (d1 + d2 == d) {\n up(u, d2)\n } else {\n val dd = (d1 + d2 - d) / 2\n val dd2 = d2 - dd\n val joint = up(u, dd2)\n step(query2(joint), dd - 1)\n }\n }\n\n val ans = step(0, query1(0))\n out.println(s\"! ${ans+1}\")\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}"}], "src_uid": "5e34b8ed812d392799f45c3c3fa1c979"} {"nl": {"description": "Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace \"Zmey-Gorynych\", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$. Using each of them exactly at once, you're to make such sequence $$$b_1, b_2, \\dots, b_n$$$ that sequence $$$c_1, c_2, \\dots, c_n$$$ is lexicographically maximal, where $$$c_i=GCD(b_1,\\dots,b_i)$$$ - the greatest common divisor of the first $$$i$$$ elements of $$$b$$$. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$) \u00a0\u2014 the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\\dots,a_n$$$ ($$$1 \\le a_i \\le 10^3$$$) \u00a0\u2014 the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.", "output_spec": "For each test case output the answer in a single line \u00a0\u2014 the desired sequence $$$b$$$. If there are multiple answers, print any.", "sample_inputs": ["7\n2\n2 5\n4\n1 8 2 3\n3\n3 8 9\n5\n64 25 75 100 50\n1\n42\n6\n96 128 88 80 52 7\n5\n2 4 8 16 17"], "sample_outputs": ["5 2 \n8 2 1 3 \n9 3 8 \n100 50 25 75 64 \n42 \n128 96 80 88 52 7 \n17 2 4 8 16"], "notes": "NoteIn the first test case of the example, there are only two possible permutations $$$b$$$ \u00a0\u2014 $$$[2, 5]$$$ and $$$[5, 2]$$$: for the first one $$$c=[2, 1]$$$, for the second one $$$c=[5, 1]$$$.In the third test case of the example, number $$$9$$$ should be the first in $$$b$$$, and $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, so the second number of $$$b$$$ should be $$$3$$$.In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation $$$b$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a sequence of n integers a1,\u2009a2,\u2009...,\u2009an. Determine a real number x such that the weakness of the sequence a1\u2009-\u2009x,\u2009a2\u2009-\u2009x,\u2009...,\u2009an\u2009-\u2009x is as small as possible.The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.The poorness of a segment is defined as the absolute value of sum of the elements of segment.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000), the length of a sequence. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u200910\u2009000).", "output_spec": "Output a real number denoting the minimum possible weakness of a1\u2009-\u2009x,\u2009a2\u2009-\u2009x,\u2009...,\u2009an\u2009-\u2009x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["3\n1 2 3", "4\n1 2 3 4", "10\n1 10 2 9 3 8 4 7 5 6"], "sample_outputs": ["1.000000000000000", "2.000000000000000", "4.500000000000000"], "notes": "NoteFor the first case, the optimal value of x is 2 so the sequence becomes \u2009-\u20091, 0, 1 and the max poorness occurs at the segment \"-1\" or segment \"1\". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes \u2009-\u20091.5,\u2009\u2009-\u20090.5,\u20090.5,\u20091.5 and the max poorness occurs on segment \"-1.5 -0.5\" or \"0.5 1.5\". The poorness value (answer) equals to 2 in this case."}, "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 as = readInts(n)\n\n def calc(x: Double): Double = {\n\n var negSum, posSum = 0\n var negLen, posLen = 0\n var max = 0d\n\n for (a <- as) {\n\n negSum += a\n negLen += 1\n\n posSum += a\n posLen += 1\n\n val pos = posSum - x * posLen\n val neg = x * negLen - negSum\n \n if (pos < 0) {\n posSum = 0\n posLen = 0\n }\n if (neg < 0) {\n negSum = 0\n negLen = 0\n }\n \n if (neg > max) max = neg\n if (pos > max) max = pos\n }\n max\n }\n\n var done = false\n var left = as.min.toDouble\n var right = as.max.toDouble\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.00000000001d) {\n min = Math.min(min, calc((right + left) / 2d))\n done = true\n } else {\n val leftThird = left + (right - left) / 3d\n val rightThird = right - (right - left) / 3d\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\n\n println(min)\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 as = readInts(n)\n\n def calc(x: Double): Double = {\n\n var negSum, posSum = 0L\n var negLen, posLen = 0L\n var max = 0d\n\n for (a <- as) {\n\n negSum += a\n negLen += 1\n\n posSum += a\n posLen += 1\n\n val pos = posSum - x * posLen\n val neg = x * negLen - negSum\n \n if (pos < 0) {\n posSum = 0\n posLen = 0\n }\n if (neg < 0) {\n negSum = 0\n negLen = 0\n }\n \n if (neg > max) max = neg\n if (pos > max) max = pos\n }\n max\n }\n\n var done = false\n var left = -10000d\n var right = 10000d\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.0000000001d) {\n min = Math.min(min, calc((right + left) / 2d))\n done = true\n } else {\n val leftThird = left + (right - left) / 3d\n val rightThird = right - (right - left) / 3d\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\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) = readInts(1)\n val as = readInts(n)\n //val x = (as.min + as.max) * 0.5d\n\n def calc(x: Double): Double = {\n var negSum, posSum = 0d\n var max = 0d\n for (a <- as) {\n negSum += (x - a)\n if (negSum < 0d) negSum = 0d\n posSum += (a - x)\n if (posSum < 0d) posSum = 0d\n if (negSum > max) max = negSum\n if (posSum > max) max = posSum\n }\n max\n }\n\n var done = false\n var left = -10000d\n var right = 10000d\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.0000000001) {\n min = Math.min(min, calc((right + left) / 2))\n done = true\n } else {\n val leftThird = left + (right - left) / 3\n val rightThird = right - (right - left) / 3\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\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) = readInts(1)\n val as = readInts(n)\n //val x = (as.min + as.max) * 0.5d\n\n def calc(x: Double): Double = {\n var negSum, posSum = 0L\n var negLen, posLen = 0L\n var max = 0d\n for (a <- as) {\n if (a < x) {\n negSum += a\n negLen += 1\n posSum = 0\n posLen = 0\n } else if (a > x) {\n posSum += a\n posLen += 1\n negSum = 0\n negLen = 0\n }\n val pos = posSum - x * posLen\n val neg = x * negLen - negSum\n if (neg > max) max = neg\n if (pos > max) max = pos\n }\n max\n }\n\n var done = false\n var left = -10000d\n var right = 10000d\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.00000000001d) {\n min = Math.min(min, calc((right + left) / 2))\n done = true\n } else {\n val leftThird = left + (right - left) / 3\n val rightThird = right - (right - left) / 3\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\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) = readInts(1)\n val as = readInts(n)\n\n def calc(x: Double): Double = {\n\n var negSum, posSum = 0L\n var negLen, posLen = 0L\n var max = 0d\n\n for (a <- as) {\n\n negSum += a\n negLen += 1\n\n posSum += a\n posLen += 1\n\n val pos = posSum - x * posLen\n val neg = x * negLen - negSum\n \n if (pos < 0) {\n posSum = 0\n posLen = 0\n }\n if (neg < 0) {\n negSum = 0\n negLen = 0\n }\n \n if (neg > max) max = neg\n if (pos > max) max = pos\n }\n max\n }\n\n var done = false\n var left = -10000d\n var right = 10000d\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.0000000001) {\n min = Math.min(min, calc((right + left) / 2))\n done = true\n } else {\n val leftThird = left + (right - left) / 3\n val rightThird = right - (right - left) / 3\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\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) = readInts(1)\n val as = readInts(n)\n //val x = (as.min + as.max) * 0.5d\n\n def calc(x: Double): Double = {\n var negSum, posSum = 0d\n var max = 0d\n for (a <- as) {\n if (a < x) {\n negSum += (x - a)\n posSum = 0\n } else if (a > x) {\n posSum += (a - x)\n negSum = 0\n }\n if (negSum > max) max = negSum\n if (posSum > max) max = posSum\n }\n max\n }\n\n var done = false\n var left = -10000d\n var right = 10000d\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.0000000001) {\n min = Math.min(min, calc((right + left) / 2))\n done = true\n } else {\n val leftThird = left + (right - left) / 3\n val rightThird = right - (right - left) / 3\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\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) = readInts(1)\n val as = readInts(n)\n //val x = (as.min + as.max) * 0.5d\n\n def calc(x: Double): Double = {\n var negSum, posSum = 0L\n var negLen, posLen = 0L\n var max = 0d\n for (a <- as) {\n if (a <= x) {\n negSum += a\n negLen += 1\n } else {\n negSum = 0\n negLen = 0\n }\n if (a >= x) {\n posSum += a\n posLen += 1\n } else {\n posSum = 0\n posLen = 0\n }\n val pos = posSum - x * posLen\n val neg = x * negLen - negSum\n if (neg > max) max = neg\n if (pos > max) max = pos\n }\n max\n }\n\n var done = false\n var left = -10000d\n var right = 10000d\n var min = Double.PositiveInfinity\n\n while (!done) {\n\n if (Math.abs(right - left) < 0.00000000001d) {\n min = Math.min(min, calc((right + left) / 2))\n done = true\n } else {\n val leftThird = left + (right - left) / 3\n val rightThird = right - (right - left) / 3\n val l = calc(leftThird)\n val r = calc(rightThird)\n if (l < min) min = l\n if (r < min) min = r\n if (l > r) left = leftThird\n else right = rightThird\n }\n }\n\n println(min)\n}\n"}], "src_uid": "14950fe682a063b1ae96332e273dea01"} {"nl": {"description": "One day n friends gathered together to play \"Mafia\". During each round of the game some player must be the supervisor and other n\u2009-\u20091 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the \"Mafia\" game they need to play to let each person play at least as many rounds as they want?", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the i-th number in the list is the number of rounds the i-th person wants to play.", "output_spec": "In a single line print a single integer \u2014 the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3\n3 2 2", "4\n2 2 2 2"], "sample_outputs": ["4", "3"], "notes": "NoteYou don't need to know the rules of \"Mafia\" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game)."}, "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 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"}, {"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"} {"nl": {"description": "It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on n main squares of the capital of Berland. Each of the n squares certainly can have demonstrations of only one party, otherwise it could lead to riots. On the other hand, both parties have applied to host a huge number of demonstrations, so that on all squares demonstrations must be held. Now the capital management will distribute the area between the two parties.Some pairs of squares are connected by (n\u2009-\u20091) bidirectional roads such that between any pair of squares there is a unique way to get from one square to another. Some squares are on the outskirts of the capital meaning that they are connected by a road with only one other square, such squares are called dead end squares.The mayor of the capital instructed to distribute all the squares between the parties so that the dead end squares had the same number of demonstrations of the first and the second party. It is guaranteed that the number of dead end squares of the city is even.To prevent possible conflicts between the zublicanes and the mumocrates it was decided to minimize the number of roads connecting the squares with the distinct parties. You, as a developer of the department of distributing squares, should determine this smallest number.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of squares in the capital of Berland. Next n\u2009-\u20091 lines contain the pairs of integers x,\u2009y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n,\u2009x\u2009\u2260\u2009y) \u2014 the numbers of the squares connected by the road. All squares are numbered with integers from 1 to n. It is guaranteed that the number of dead end squares of the city is even.", "output_spec": "Print a single number \u2014 the minimum number of roads connecting the squares with demonstrations of different parties.", "sample_inputs": ["8\n1 4\n2 4\n3 4\n6 5\n7 5\n8 5\n4 5", "5\n1 2\n1 3\n1 4\n1 5"], "sample_outputs": ["1", "2"], "notes": null}, "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 WHITE = 0\n val BLACK = 1\n \n class DP {\n var dp = ofDim[Short](2, 0)\n def addUpEdge = {\n val res = initDP(dp(0).length, 0)\n for (cnt <- 0 until dp(0).length) {\n res.dp(0)(cnt) = math.min(dp(0)(cnt), dp(1)(cnt) + 1).toShort\n res.dp(1)(cnt) = math.min(dp(0)(cnt) + 1, dp(1)(cnt)).toShort\n }\n res\n }\n }\n \n def initDP(n: Int, value: Short): DP = {\n val res = new DP\n res.dp = Array.fill[Short](2, n)(value)\n res\n }\n \n def combineArrays(a: Array[Short], b: Array[Short]): Array[Short] = {\n if (a.length == 0) return b\n if (b.length == 0) return a\n val c = Array.fill[Short](a.length + b.length - 1)((Short.MaxValue / 2).toShort)\n for (i <- 0 until a.length) {\n for (j <- 0 until b.length) {\n if (a(i) + b(j) < c(i + j)) c(i + j) = (a(i) + b(j)).toShort\n }\n }\n c\n }\n \n def combineDP(a: DP, b: DP): DP = {\n val res = new DP\n res.dp(0) = combineArrays(a.dp(0), b.dp(0))\n res.dp(1) = combineArrays(a.dp(1), b.dp(1))\n res\n }\n \n var n = 0\n var g: Array[ArrayBuffer[Int]] = null\n \n def dfs(v: Int, p: Int): DP = {\n if (g(v).length == 1) {\n val res = initDP(2, 0)\n res.dp(0)(0) = Short.MaxValue / 2\n res.dp(1)(1) = Short.MaxValue / 2\n return res\n } \n var res = new DP\n for (to <- g(v)) {\n if (to != p) {\n res = combineDP(res, dfs(to, v).addUpEdge)\n }\n }\n return res\n }\n \n def main(args: Array[String]): Unit = { \n n = in.nextInt\n \n g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])\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 var root = 1\n var cntLeafs = 0\n \n for (i <- 1 to n) {\n if (g(i).length != 1) root = i\n else cntLeafs += 1\n }\n \n val z = dfs(root, -1)\n \n val res = math.min(z.dp(0)(cntLeafs / 2).toInt, z.dp(1)(cntLeafs / 2).toInt)\n \n out.println(res)\n \n out.close\n }\n}"}], "negative_code": [], "src_uid": "3d1ace687b28bec9bd365757f311987c"} {"nl": {"description": "Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.", "input_spec": "The only line contains three integers b, d and s (0\u2009\u2264\u2009b,\u2009d,\u2009s\u2009\u2264\u20091018,\u2009\u2009b\u2009+\u2009d\u2009+\u2009s\u2009\u2265\u20091)\u00a0\u2014 the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium. ", "output_spec": "Print single integer\u00a0\u2014 the minimum possible number of meals which Vasiliy could have missed during his vacation. ", "sample_inputs": ["3 2 1", "1 0 0", "1 1 1", "1000000000000000000 0 1000000000000000000"], "sample_outputs": ["1", "0", "0", "999999999999999999"], "notes": "NoteIn the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day. In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal. "}, "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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.Today he wrote string $$$s$$$ of length $$$n$$$ consisting only of uppercase or lowercase Latin letters. He asks you to check if $$$s$$$ is the correct spelling of his name.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ $$$(1 \\leq n \\leq 10)$$$\u00a0\u2014 the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of only uppercase or lowercase Latin characters.", "output_spec": "For each test case, output \"YES\" (without quotes) if $$$s$$$ satisfies the condition, and \"NO\" (without quotes) otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["10\n\n5\n\nTimur\n\n5\n\nmiurT\n\n5\n\nTrumi\n\n5\n\nmriTu\n\n5\n\ntimur\n\n4\n\nTimr\n\n6\n\nTimuur\n\n10\n\ncodeforces\n\n10\n\nTimurTimur\n\n5\n\nTIMUR"], "sample_outputs": ["YES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO\nNO"], "notes": null}, "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 (_, 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"}, {"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"} {"nl": {"description": "You are given a convex polygon P with n distinct vertices p1,\u2009p2,\u2009...,\u2009pn. Vertex pi has coordinates (xi,\u2009yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.", "input_spec": "The first line has one integer n (4\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000)\u00a0\u2014 the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109)\u00a0\u2014 the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).", "output_spec": "Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .", "sample_inputs": ["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"], "sample_outputs": ["0.3535533906", "1.0000000000"], "notes": "NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is \u2009\u2248\u20090.4242640687, whereas we can make it non-convex by only moving each point a distance of at most \u2009\u2248\u20090.3535533906."}, "positive_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 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"}, {"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"} {"nl": {"description": "A championship is held in Berland, in which $$$n$$$ players participate. The player with the number $$$i$$$ has $$$a_i$$$ ($$$a_i \\ge 1$$$) tokens.The championship consists of $$$n-1$$$ games, which are played according to the following rules: in each game, two random players with non-zero tokens are selected; the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly); the winning player takes all of the loser's tokens; The last player with non-zero tokens is the winner of the championship.All random decisions that are made during the championship are made equally probable and independently.For example, if $$$n=4$$$, $$$a = [1, 2, 4, 3]$$$, then one of the options for the game (there could be other options) is: during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now $$$a = [0, 2, 4, 4]$$$; during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now $$$a = [0, 2, 8, 0]$$$; during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now $$$a = [0, 0, 10, 0]$$$; the third player is declared the winner of the championship. Championship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case consists of one positive integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of players in the championship. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the number of tokens the players have. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$. ", "output_spec": "For each test case, print the number of players who have a nonzero probability of winning the championship. On the next line print the numbers of these players in increasing order. Players are numbered starting from one in the order in which they appear in the input. ", "sample_inputs": ["2\n4\n1 2 4 3\n5\n1 1 1 1 1"], "sample_outputs": ["3\n2 3 4 \n5\n1 2 3 4 5"], "notes": null}, "positive_code": [{"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory extends App {\r\n val t = readLine.toInt\r\n for (_ <- 1 to t) {\r\n val n = readLine.toInt\r\n val tokens = readLine.split(' ').toList.map(x => BigInt(x))\r\n val as = tokens.zip((1 to tokens.length).toList).sortBy(x => x._1)\r\n lazy val index = recursion(as, 0, 0, -1)\r\n lazy val non_zero_players = as.slice(Math.max(0, index), as.length).sortBy(x => x._2)\r\n println(non_zero_players.length)\r\n println(non_zero_players.map(x => x._2.toString()).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[(BigInt, Int)], sum : BigInt, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x._1 > sum) {\r\n recursion(xs, sum + x._1, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x._1, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory extends App {\r\n val t = readLine.toInt\r\n for (_ <- 1 to t) {\r\n val n = readLine.toInt\r\n val tokens = readLine.split(' ').toList.map(x => x.toInt)\r\n val as = tokens.zip((1 to tokens.length).toList).sortBy(x => x._1)\r\n lazy val index = recursion(as, 0, 0, -1)\r\n lazy val non_zero_players = as.slice(Math.max(0, index), as.length).sortBy(x => x._2)\r\n println(non_zero_players.length)\r\n println(non_zero_players.map(x => x._2.toString()).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[(Int, Int)], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x._1 > sum) {\r\n recursion(xs, sum + x._1, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x._1, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory 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).sorted\r\n lazy val index = recursion(as, 0, 0, -1)\r\n println(as.length - Math.max(index, 0))\r\n println((Math.max(index, 0) + 1 to as.length).toList.map(x => x.toString).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x > sum) {\r\n recursion(xs, sum + x, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory 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).sorted\r\n lazy val index = recursion(as, 0, 0, -1)\r\n println(as.length - index)\r\n println((Math.max(index, 0) + 1 to as.length).toList.map(x => x.toString).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x > sum) {\r\n recursion(xs, sum + x, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory 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).sorted\r\n lazy val index = recursion(as, 0, 0, -1)\r\n println(as.length - index)\r\n println(as.slice(index, as.length).map(x => x.toString).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x > sum) {\r\n recursion(xs, sum + x, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory 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).sorted\r\n lazy val index = recursion(as, 0, 0, -1)\r\n println(as.slice(index, as.length).map(x => x.toString).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x > sum) {\r\n recursion(xs, sum + x, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}, {"source_code": "import scala.annotation.tailrec\r\nimport scala.io.StdIn.readLine\r\n\r\nobject AccidentalVictory 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 lazy val index = recursion(as, 0, 0, -1)\r\n println(as.slice(index, as.length).map(x => x.toString).mkString(\" \"))\r\n\r\n @tailrec\r\n def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {\r\n case x :: xs =>\r\n if(x > sum) {\r\n recursion(xs, sum + x, current_index + 1, current_index)\r\n } else {\r\n recursion(xs, sum + x, current_index + 1, last_zero_index)\r\n }\r\n case _ => last_zero_index\r\n }\r\n }\r\n}\r\n\r\n"}], "src_uid": "debce043777e7e575f77a94edf89c7f1"} {"nl": {"description": "Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $$$1$$$ meter movement in the south, north, west or east direction respectively).It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is $$$5$$$ seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes $$$1$$$ second.Find the skier's time to roll all the path.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed $$$10^5$$$ characters. The sum of the lengths of $$$t$$$ given lines over all test cases in the input does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the desired path time in seconds.", "sample_inputs": ["5\nNNN\nNS\nWWEN\nWWEE\nNWNWS"], "sample_outputs": ["15\n6\n16\n12\n25"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn.readLine\n\nobject C {\n\n def solution(moves: String): Int = {\n val isRightTaken = mutable.Set.empty[(Int, Int)]\n val isTopTaken = mutable.Set.empty[(Int, Int)]\n def add[T](set: mutable.Set[T], value: T) = if (set.add(value)) 5 else 1\n\n var (time, i, j) = (0, 0, 0)\n for (dir <- moves) {\n dir match {\n case 'E' => // Right\n time += add(isRightTaken, (i, j))\n i += 1\n case 'W' => // Left\n time += add(isRightTaken, (i - 1, j))\n i -= 1\n case 'N' => // Top\n time += add(isTopTaken, (i, j))\n j += 1\n case 'S' => // Bottom\n time += add(isTopTaken, (i, j - 1))\n j -= 1\n }\n }\n time\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val moves = readLine\n println(solution(moves))\n }\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn.readLine\n\nobject C {\n\n def solution(moves: String): Int = {\n val isRightTaken = mutable.Set.empty[(Int, Int)]\n val isTopTaken = mutable.Set.empty[(Int, Int)]\n def add[T](set: mutable.Set[T], value: T) = if (set.add(value)) 5 else 1\n\n var (time, i, j) = (0, 0, 0)\n for (dir <- moves) {\n dir match {\n case 'E' => // Right\n time += add(isRightTaken, (i, j))\n i += 1\n case 'W' => // Left\n time += add(isRightTaken, (i - 1, j))\n i -= 1\n case 'N' => // Top\n time += add(isTopTaken, (i, j))\n j += 1\n case 'S' => // Bottom\n time += add(isTopTaken, (i, j - 1))\n i -= 1\n }\n }\n time\n }\n\n def main(args: Array[String]): Unit = {\n for {_ <- 0 until readLine.toInt} {\n val moves = readLine\n println(solution(moves))\n }\n }\n}"}], "src_uid": "8190d3bc81a4d76f8256f31f07441a36"} {"nl": {"description": "As usual, Sereja has array a, its elements are integers: a[1],\u2009a[2],\u2009...,\u2009a[n]. Let's introduce notation:A swap operation is the following sequence of actions: choose two indexes i,\u2009j (i\u2009\u2260\u2009j); perform assignments tmp\u2009=\u2009a[i],\u2009a[i]\u2009=\u2009a[j],\u2009a[j]\u2009=\u2009tmp. What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009200;\u00a01\u2009\u2264\u2009k\u2009\u2264\u200910). The next line contains n integers a[1], a[2], ..., a[n] (\u2009-\u20091000\u2009\u2264\u2009a[i]\u2009\u2264\u20091000).", "output_spec": "In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.", "sample_inputs": ["10 2\n10 -1 2 2 2 2 2 2 -1 10", "5 10\n-1 -1 -1 -1 -1"], "sample_outputs": ["32", "-1"], "notes": null}, "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.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 P425A extends App {\n val sc = new Scanner(System.in)\n val out = new PrintWriter(System.out)\n\n def solve(): Int = {\n val N, K = sc.nextInt\n val A = Array.fill(N)(sc.nextInt)\n \n @tailrec\n def loop(acc: Int, i: Int, j: Int): Int = {\n if (i == N) acc\n else if (j == N + 1) loop(acc, i + 1, i + 2)\n else {\n val lr = A.slice(i, j)\n val kmax = (A.slice(0, i) ++ A.slice(j, N)).sorted(Ordering.Int.reverse).take(K)\n val sum = (lr ++ kmax).sorted(Ordering.Int.reverse).take(j - i).sum\n loop(acc max sum, i, j + 1)\n }\n }\n\n loop(Int.MinValue, 0, 1)\n }\n \n out.println(solve)\n out.close\n}\n"}], "negative_code": [], "src_uid": "ff69d22bc683e5d1d83438585224c774"} {"nl": {"description": "You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: Operation AND ('&', ASCII code 38) Operation OR ('|', ASCII code 124) Operation NOT ('!', ASCII code 33) Variables x, y and z (ASCII codes 120-122) Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one.Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:E ::= E '|' T | TT ::= T '&' F | FF ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'", "input_spec": "The first line contains one integer n\u00a0\u2014 the number of functions in the input (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1\u00a0\u2014 the truth table of the i-th function. The digit on position j (0\u2009\u2264\u2009j\u2009<\u20098) equals to the value of the function in case of , and .", "output_spec": "You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.", "sample_inputs": ["4\n00110011\n00000111\n11110000\n00011111"], "sample_outputs": ["y\n(y|z)&x\n!x\nx|y&z"], "notes": "NoteThe truth table for the second function:"}, "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject E {\n def fromBinary(s: String): Int = s.zipWithIndex.map(p => if (p._1 == '1') 1 << p._2 else 0).sum\n\n def compare(l: String, r: String): Int = {\n if (l == r) 0 else if (l == null) 1 else if (r == null) -1 else if (l.length != r.length) {\n l.length - r.length\n } else l.compareTo(r)\n }\n\n def generate(): Array[String] = {\n val shortestE, shortestF, shortestT = Array.ofDim[String](256)\n shortestF(fromBinary(\"00001111\")) = \"x\"\n shortestF(fromBinary(\"00110011\")) = \"y\"\n shortestF(fromBinary(\"01010101\")) = \"z\"\n var changed = false\n do {\n changed = false\n for (i <- 0 until 256) {\n if (shortestE(i) != null) {\n val br = \"(\" + shortestE(i) + \")\"\n if (compare(shortestF(i), br) > 0) {\n shortestF(i) = br\n changed = true\n }\n }\n if (compare(shortestT(i), shortestF(i)) > 0) {\n shortestT(i) = shortestF(i)\n changed = true\n }\n if (compare(shortestE(i), shortestT(i)) > 0) {\n shortestE(i) = shortestT(i)\n changed = true\n }\n if (shortestF(i) != null) {\n val neg = \"!\" + shortestF(i)\n if (compare(shortestF(~i & 255), neg) > 0) {\n shortestF(~i & 255) = neg\n changed = true\n }\n }\n for (j <- 0 until 256) {\n if (shortestE(i) != null && shortestT(j) != null) {\n val or = shortestE(i) + \"|\" + shortestT(j)\n if (compare(shortestE(i | j), or) > 0) {\n shortestE(i | j) = or\n changed = true\n }\n }\n if (shortestT(i) != null && shortestF(j) != null) {\n val and = shortestT(i) + \"&\" + shortestF(j)\n if (compare(shortestT(i & j), and) > 0) {\n shortestT(i & j) = and\n changed = true\n }\n }\n }\n }\n } while (changed)\n shortestE\n }\n\n def solve(in: Input, out: Output): Unit = {\n val answers = generate()\n val n = in.nextInt()\n for (_ <- 0 until n) {\n val line = in.next()\n val tableKey = (0 until 8).map(i => if (line(i) == '1') 1 << i else 0).sum\n out.println(answers(tableKey))\n }\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": [], "src_uid": "e840b008dfd50a9be7061b6788160568"} {"nl": {"description": "Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1\u2009\u00d7\u20091. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x\u2009+\u20091. In case of x\u2009=\u2009n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.", "output_spec": "The only line of the output should contain a single integer\u00a0\u2014 the maximum number of squares that Vika can paint if she follows the rules described above.", "sample_inputs": ["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"], "sample_outputs": ["12", "15", "11"], "notes": "NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5."}, "positive_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.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": "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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?", "input_spec": "The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.", "output_spec": "Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.", "sample_inputs": ["3121", "6", "1000000000000000000000000000000000", "201920181"], "sample_outputs": ["2", "1", "33", "4"], "notes": "NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$."}, "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 // \u307e\u3048\u306e\u72b6\u614b\u304b\u3089\u9077\u79fb\n REP(3) { j =>\n last(x^1)((j + m) % 3) = last(x)(j)\n }\n // m\u306e\u72b6\u614b\u306e\u6700\u77ed\u3092\u66f4\u65b0\n last(x^1)(m) = i // \u53c2\u7167\u3059\u308b\u306e\u306f\uff11\u6b69\u624b\u524d\u306eDP\u306e\u72b6\u614b\n\n if (m == 0) {\n dp(i + 1) = dp(i) + 1\n } else {\n // 3\u3092\u3064\u304f\u3089\u306a\u3044\u5834\u5408\u306e\u500b\u6570\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}"}, {"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}"}], "negative_code": [], "src_uid": "3b2d0d396649a200a73faf1b930ef611"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$, where $$$n$$$ is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: At least $$$\\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \\dots, n - 1$$$ are greater than or equal to $$$0$$$. At least $$$\\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \\dots, n - 1$$$ are less than or equal to $$$0$$$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \\le n \\le 99$$$, $$$n$$$ is odd) \u00a0\u2014 the number of integers given to you. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$) \u00a0\u2014 the numbers themselves. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10000$$$.", "output_spec": "For each test case, print $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$, corresponding to the integers after flipping signs. $$$b_i$$$ has to be equal to either $$$a_i$$$ or $$$-a_i$$$, and of the adjacent differences $$$b_{i + 1} - b_i$$$ for $$$i = 1, \\dots, n - 1$$$, at least $$$\\frac{n - 1}{2}$$$ should be non-negative and at least $$$\\frac{n - 1}{2}$$$ should be non-positive. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.", "sample_inputs": ["5\n3\n-2 4 3\n5\n1 1 1 1 1\n5\n-2 4 7 -6 4\n9\n9 7 -4 -2 1 -3 9 -4 -5\n9\n-4 1 9 4 8 9 5 1 -9"], "sample_outputs": ["-2 -4 3\n1 1 1 1 1\n-2 -4 7 -6 4\n-9 -7 -4 2 1 -3 -9 -4 -5\n4 -1 -9 -4 -8 -9 -5 -1 9"], "notes": "NoteIn the first test case, the difference $$$(-4) - (-2) = -2$$$ is non-positive, while the difference $$$3 - (-4) = 7$$$ is non-negative.In the second test case, we don't have to flip any signs. All $$$4$$$ differences are equal to $$$0$$$, which is both non-positive and non-negative.In the third test case, $$$7 - (-4)$$$ and $$$4 - (-6)$$$ are non-negative, while $$$(-4) - (-2)$$$ and $$$(-6) - 7$$$ are non-positive."}, "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\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"}, {"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"} {"nl": {"description": "Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $$$x$$$ with $$$p$$$ zeros appended to its end.Now Monocarp asks you to compare these two numbers. Can you help him?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains two integers $$$x_1$$$ and $$$p_1$$$ ($$$1 \\le x_1 \\le 10^6; 0 \\le p_1 \\le 10^6$$$)\u00a0\u2014 the description of the first number. The second line of each testcase contains two integers $$$x_2$$$ and $$$p_2$$$ ($$$1 \\le x_2 \\le 10^6; 0 \\le p_2 \\le 10^6$$$)\u00a0\u2014 the description of the second number.", "output_spec": "For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.", "sample_inputs": ["5\n2 1\n19 0\n10 2\n100 1\n1999 0\n2 3\n1 0\n1 0\n99 0\n1 2"], "sample_outputs": [">\n=\n<\n=\n<"], "notes": "NoteThe comparisons in the example are: $$$20 > 19$$$, $$$1000 = 1000$$$, $$$1999 < 2000$$$, $$$1 = 1$$$, $$$99 < 100$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob\u00a0\u2014 then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy\u00a0\u2014 and after that, she has $$$55$$$ candies too.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 1000$$$)\u00a0\u2014 the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \\le a, b, c \\le 10^{16}$$$)\u00a0\u2014 the number of candies in the first, second and third piles correspondingly.", "output_spec": "Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th query\u00a0\u2014 the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).", "sample_inputs": ["4\n1 3 4\n1 10 100\n10000000000000000 10000000000000000 10000000000000000\n23 34 45"], "sample_outputs": ["4\n55\n15000000000000000\n51"], "notes": null}, "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}\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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "d9e4a9a32d60e75f3cf959ef7f894fc6"} {"nl": {"description": "Shubham has a binary string $$$s$$$. A binary string is a string containing only characters \"0\" and \"1\".He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was \"0\", it becomes \"1\", and vice versa. A string is called good if it does not contain \"010\" or \"101\" as a subsequence \u00a0\u2014 for instance, \"1001\" contains \"101\" as a subsequence, hence it is not a good string, while \"1000\" doesn't contain neither \"010\" nor \"101\" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1\\le t \\le 100)$$$\u00a0\u2014 the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \\le |s| \\le 1000)$$$.", "output_spec": "For every string, output the minimum number of operations required to make it good.", "sample_inputs": ["7\n001\n100\n101\n010\n0\n1\n001100"], "sample_outputs": ["0\n0\n1\n1\n0\n0\n2"], "notes": "NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: \"001\" can be achieved by flipping the first character \u00a0\u2014 and is one of the possible ways to get a good string.For the $$$4$$$th test case: \"000\" can be achieved by flipping the second character \u00a0\u2014 and is one of the possible ways to get a good string.For the $$$7$$$th test case: \"000000\" can be achieved by flipping the third and fourth characters \u00a0\u2014 and is one of the possible ways to get a good string."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Qpwoeirut has taken up architecture and ambitiously decided to remodel his city.Qpwoeirut's city can be described as a row of $$$n$$$ buildings, the $$$i$$$-th ($$$1 \\le i \\le n$$$) of which is $$$h_i$$$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $$$i$$$ is taller than the building $$$j$$$ if and only if the number of floors $$$h_i$$$ in building $$$i$$$ is larger than the number of floors $$$h_j$$$ in building $$$j$$$.Building $$$i$$$ is cool if it is taller than both building $$$i-1$$$ and building $$$i+1$$$ (and both of them exist). Note that neither the $$$1$$$-st nor the $$$n$$$-th building can be cool.To remodel the city, Qpwoeirut needs to maximize the number of cool buildings. To do this, Qpwoeirut can build additional floors on top of any of the buildings to make them taller. Note that he cannot remove already existing floors.Since building new floors is expensive, Qpwoeirut wants to minimize the number of floors he builds. Find the minimum number of floors Qpwoeirut needs to build in order to maximize the number of cool buildings.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$3 \\le n \\le 10^5$$$)\u00a0\u2014 the number of buildings in Qpwoeirut's city. The second line of each test case contains $$$n$$$ integers $$$h_1, h_2, \\ldots, h_n$$$ ($$$1 \\le h_i \\le 10^9$$$)\u00a0\u2014 the number of floors in each of the buildings of the city. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the minimum number of additional floors Qpwoeirut needs to build in order to maximize the number of cool buildings.", "sample_inputs": ["6\n\n3\n\n2 1 2\n\n5\n\n1 2 1 4 3\n\n6\n\n3 1 4 5 5 2\n\n8\n\n4 2 1 3 5 3 6 1\n\n6\n\n1 10 1 1 10 1\n\n8\n\n1 10 11 1 10 11 10 1"], "sample_outputs": ["2\n0\n3\n3\n0\n4"], "notes": "NoteIn the first test case, it is optimal for Qpwoeirut to make the second building cool by building $$$2$$$ additional floors on top of it, making it taller than both of its adjacent buildings. The final heights of buildings will be $$$[2, \\underline{3}, 2]$$$. In the second test case, the number of cool buildings is already maximized, so Qpwoeirut does not need to do anything.In the third test case, it is optimal for Qpwoeirut to make the third and fifth buildings cool by building $$$2$$$ additional floors onto the third building and $$$1$$$ additional floor onto the fifth building. The final heights of buildings will be $$$[3, 1, \\underline{6}, 5, \\underline{6}, 2]$$$. It can be shown that it is impossible to make more than $$$2$$$ of the buildings cool, or to make $$$2$$$ buildings cool using fewer than $$$3$$$ additional floors.In the fourth test case, Qpwoeirut can either make the second building cool, or he can make the third building cool. Either way, he will be building $$$3$$$ additional floors and maximizing the number of cool buildings. The final heights of buildings will be $$$[4, 2, \\underline{4}, 3, 5, 3, 6, 1]$$$ or $$$[4, \\underline{5}, 1, 3, 5, 3, 6, 1]$$$. "}, "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 tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until n) {\r\n A(i) = tokenizer.nextToken().toInt\r\n }\r\n var count: Long = 0\r\n var count2: Long = 0\r\n if ((n % 2) == 1) {\r\n for {i <- A.indices\r\n if ((i %2) == 1)} {\r\n count+= max(0, max(A(i-1) - A(i) + 1, A(i+1) - A(i) + 1))\r\n }\r\n println(count)\r\n }\r\n else {\r\n val L = new Array[Long](n/2)\r\n val R = new Array[Long](n/2)\r\n val S = new Array[Long](n/2)\r\n L(0) = 0\r\n R((n/2) - 1) = 0\r\n for {i <- A.indices\r\n if (((i %2) == 1) && (i < (n-1)))} {\r\n count+= max(0, max(A(i-1) - A(i) + 1, A(i+1) - A(i) + 1))\r\n L(1+((i-1) / 2)) = count\r\n }\r\n for {i <- A.indices\r\n if (((i %2) == 1) && (i < (n-1)))} {\r\n count2+= max(0, max(A(n-1-i+1) - A(n-1-i) + 1, A(n-1-i-1) - A(n-1-i) + 1))\r\n R(n/2 - 2 - ((i-1) / 2)) = count2\r\n }\r\n for (i <- S.indices) {\r\n S(i) = L(i) + R(i)\r\n }\r\n println(S.min)\r\n }\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "ba52f4eaf05c0f154c40cec46c861c13"} {"nl": {"description": "One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.", "input_spec": "The first input line contains a single even integer n (4\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of students in the class. The second line contains exactly n capital English letters \"L\" and \"R\". If the i-th letter at the second line equals \"L\", then the student number i is a lefthander, otherwise he is a righthander.", "output_spec": "Print integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.", "sample_inputs": ["6\nLLRLLL", "4\nRRLL"], "sample_outputs": ["1 4\n2 5\n6 3", "3 1\n4 2"], "notes": null}, "positive_code": [{"source_code": "import scala.io.Source\nimport java.io.PrintWriter\nimport java.io.File\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 orientation = it.next.trim()\n \n def PRINT(a: Int, b: Int) = if (orientation.charAt(a) == 'R' && orientation.charAt(b) == 'L') writer.println((b+1)+\" \"+(a+1))\n else writer.println((a+1)+\" \"+(b+1))\n \n def solve(xs: List[Int]):Unit = xs match {\n case List(a, b) => PRINT(a, b)\n case a :: b :: c :: tail => PRINT(a, c); solve(b :: tail)\n }\n\n solve(0 to n-1 toList) \n writer.close()\n }\n}"}], "negative_code": [], "src_uid": "564664d9cd2ccbccb42574b3881ec5fe"} {"nl": {"description": "Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible: delete $$$s_1$$$ and $$$s_2$$$: $$$\\textbf{10}11001 \\rightarrow 11001$$$; delete $$$s_2$$$ and $$$s_3$$$: $$$1\\textbf{01}1001 \\rightarrow 11001$$$; delete $$$s_4$$$ and $$$s_5$$$: $$$101\\textbf{10}01 \\rightarrow 10101$$$; delete $$$s_6$$$ and $$$s_7$$$: $$$10110\\textbf{01} \\rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.", "input_spec": "First line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \\le |s| \\le 100$$$), consisting of only characters 0 and 1.", "output_spec": "For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.", "sample_inputs": ["3\n01\n1111\n0011"], "sample_outputs": ["DA\nNET\nNET"], "notes": "NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move."}, "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 s = readLine()\n\n val t1 = s.count(_ == '1')\n val t2 = s.length - t1\n\n if ((t1 min t2) % 2 == 0) println(\"NET\")\n else println(\"DA\")\n }\n}\n"}], "negative_code": [], "src_uid": "046900001c7326fc8d890a22fa7267c9"} {"nl": {"description": " You are given an array $$$a_1, a_2, \\dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \\le a_2 \\le \\ldots \\le a_n$$$.", "input_spec": " The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \\ldots a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the array itself. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": " For each test case, output \"YES\" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or \"NO\" if it is impossible to do so.", "sample_inputs": ["4\n1\n8\n6\n4 3 6 6 2 9\n4\n4 5 6 7\n5\n7 5 2 2 4"], "sample_outputs": ["YES\nYES\nYES\nNO"], "notes": "Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation."}, "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"}, {"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"}], "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"} {"nl": {"description": "According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of buttons on the jacket. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091). The number ai\u2009=\u20090 if the i-th button is not fastened. Otherwise ai\u2009=\u20091.", "output_spec": "In the only line print the word \"YES\" if the jacket is fastened in a right way. Otherwise print the word \"NO\".", "sample_inputs": ["3\n1 0 1", "3\n1 0 0"], "sample_outputs": ["YES", "NO"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n\u2009\u00d7\u2009n is called k-special if the following three conditions are satisfied: every integer from 1 to n2 appears in the table exactly once; in each row numbers are situated in increasing order; the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n\u2009\u00d7\u2009n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009500,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the size of the table Alice is looking for and the column that should have maximum possible sum.", "output_spec": "First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any.", "sample_inputs": ["4 1", "5 3"], "sample_outputs": ["28\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16", "85\n5 6 17 18 19\n9 10 23 24 25\n7 8 20 21 22\n3 4 14 15 16\n1 2 11 12 13"], "notes": null}, "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": "\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"}, {"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"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$, and $$$q$$$ queries. The $$$i$$$-th query consists of two numbers $$$l_i$$$ and $$$r_i$$$, and the answer to it is the number of integers $$$x$$$ such that $$$l_i \\le x \\le r_i$$$, and $$$((x \\bmod a) \\bmod b) \\ne ((x \\bmod b) \\bmod a)$$$. Calculate the answer for each query.Recall that $$$y \\bmod z$$$ is the remainder of the division of $$$y$$$ by $$$z$$$. For example, $$$5 \\bmod 3 = 2$$$, $$$7 \\bmod 8 = 7$$$, $$$9 \\bmod 4 = 1$$$, $$$9 \\bmod 9 = 0$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Then the test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$q$$$ ($$$1 \\le a, b \\le 200$$$; $$$1 \\le q \\le 500$$$). Then $$$q$$$ lines follow, each containing two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^{18}$$$) for the corresponding query.", "output_spec": "For each test case, print $$$q$$$ integers\u00a0\u2014 the answers to the queries of this test case in the order they appear.", "sample_inputs": ["2\n4 6 5\n1 1\n1 3\n1 5\n1 7\n1 9\n7 10 2\n7 8\n100 200"], "sample_outputs": ["0 0 0 2 4 \n0 91"], "notes": null}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.Note that in this problem you do not have to minimize the number of swaps \u2014 your task is to find any sequence that is no longer than n.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the number of array elements. The second line contains elements of array: a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the i-th element of the array. The elements are numerated from 0 to n\u2009-\u20091 from left to right. Some integers may appear in the array more than once.", "output_spec": "In the first line print k (0\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n\u2009-\u20091), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i\u2009=\u2009j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.", "sample_inputs": ["5\n5 2 5 1 4", "6\n10 20 20 40 60 60", "2\n101 100"], "sample_outputs": ["2\n0 3\n4 2", "0", "1\n0 1"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are, The chosen c prisoners has to form a contiguous segment of prisoners. Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.", "input_spec": "The first line of input will contain three space separated integers n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105), t\u00a0(0\u2009\u2264\u2009t\u2009\u2264\u2009109) and c\u00a0(1\u2009\u2264\u2009c\u2009\u2264\u2009n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109. ", "output_spec": "Print a single integer \u2014 the number of ways you can choose the c prisoners.", "sample_inputs": ["4 3 3\n2 3 1 1", "1 1 1\n2", "11 4 2\n2 2 0 7 3 2 2 4 9 1 4"], "sample_outputs": ["2", "0", "6"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "7d1e8769a6b1d5c6680ab530d19e7fa4"} {"nl": {"description": "Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.", "input_spec": "The first line of the input contains two positive integers, n and m \u2014 the number of the cities and the number of roads in Berland (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000). Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi,\u2009yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi), where xi and yi are the numbers of the cities connected by the i-th road. It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of separated cities after the reform.", "sample_inputs": ["4 3\n2 1\n1 3\n4 3", "5 5\n2 1\n1 3\n2 3\n2 5\n4 3", "6 5\n1 2\n2 3\n4 5\n4 6\n5 6"], "sample_outputs": ["1", "0", "1"], "notes": "NoteIn the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , ."}, "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._\n\nobject _659E extends CodeForcesApp {\n override def apply(io: IO) = {\n val n, m = io[Int]\n val edgeCount = map[Int] to 0\n\n val ds = new UnionFind[Int]\n (1 to n) foreach ds.+=\n\n repeat(m) {\n val u, v = io[Int]\n ds.union(u, v)\n edgeCount(u) += 1\n }\n\n val components = (1 to n).groupBy(ds)\n\n val ans = components.values count {comp =>\n val subEdges = comp.sumWith(edgeCount)\n comp.size == subEdges + 1\n }\n\n io += ans\n }\n\n class UnionFind[A] extends (A => Option[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 apply(x: A) = when(contains(x))(find(x))\n\n def union(x: A, y: A) = parent(find(x)) = find(y)\n\n def +=(x: A) = parent(x) = x\n\n def contains(x: A) = parent contains x\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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[K2, V] = 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": "1817fbdc61541c09fb8f48df31f5049a"} {"nl": {"description": "Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n\u2009+\u20092n\u2009+\u20093n\u2009+\u20094n)\u00a0mod\u00a05for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).", "input_spec": "The single line contains a single integer n (0\u2009\u2264\u2009n\u2009\u2264\u200910105). The number doesn't contain any leading zeroes.", "output_spec": "Print the value of the expression without leading zeros.", "sample_inputs": ["4", "124356983594583453458888889"], "sample_outputs": ["4", "0"], "notes": "NoteOperation x\u00a0mod\u00a0y means taking remainder after division x by y.Note to the first sample:"}, "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}"}, {"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"}], "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"} {"nl": {"description": "Polycarp has $$$26$$$ tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: \"DDBBCCCBBEZ\", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: \"BAB\", \"AABBCCDDEEBZZ\" and \"AAAAZAAAAA\".If Polycarp solved the tasks as follows: \"FFGZZZY\", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: \"BA\", \"AFFFCC\" and \"YYYYY\".Help Polycarp find out if his teacher might be suspicious.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the number of days during which Polycarp solved tasks. The second line contains a string of length $$$n$$$, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.", "output_spec": "For each test case output: \"YES\", if the teacher cannot be suspicious; \"NO\", otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["5\n3\nABA\n11\nDDBBCCCBBEZ\n7\nFFGZZZY\n1\nZ\n2\nAB"], "sample_outputs": ["NO\nNO\nYES\nYES\nYES"], "notes": null}, "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"}, {"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}"}], "negative_code": [], "src_uid": "3851854541b4bd168f5cb1e8492ed8ef"} {"nl": {"description": "Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $$$n$$$, he encrypts it in the following way: he picks three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$l \\leq a,b,c \\leq r$$$, and then he computes the encrypted value $$$m = n \\cdot a + b - c$$$.Unfortunately, an adversary intercepted the values $$$l$$$, $$$r$$$ and $$$m$$$. Is it possible to recover the original values of $$$a$$$, $$$b$$$ and $$$c$$$ from this information? More formally, you are asked to find any values of $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$a$$$, $$$b$$$ and $$$c$$$ are integers, $$$l \\leq a, b, c \\leq r$$$, there exists a strictly positive integer $$$n$$$, such that $$$n \\cdot a + b - c = m$$$. ", "input_spec": "The first line contains the only integer $$$t$$$ ($$$1 \\leq t \\leq 20$$$)\u00a0\u2014 the number of test cases. The following $$$t$$$ lines describe one test case each. Each test case consists of three integers $$$l$$$, $$$r$$$ and $$$m$$$ ($$$1 \\leq l \\leq r \\leq 500\\,000$$$, $$$1 \\leq m \\leq 10^{10}$$$). The numbers are such that the answer to the problem exists.", "output_spec": "For each test case output three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that, $$$l \\leq a, b, c \\leq r$$$ and there exists a strictly positive integer $$$n$$$ such that $$$n \\cdot a + b - c = m$$$. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions.", "sample_inputs": ["2\n4 6 13\n2 3 1"], "sample_outputs": ["4 6 5\n2 2 3"], "notes": "NoteIn the first example $$$n = 3$$$ is possible, then $$$n \\cdot 4 + 6 - 5 = 13 = m$$$. Other possible solutions include: $$$a = 4$$$, $$$b = 5$$$, $$$c = 4$$$ (when $$$n = 3$$$); $$$a = 5$$$, $$$b = 4$$$, $$$c = 6$$$ (when $$$n = 3$$$); $$$a = 6$$$, $$$b = 6$$$, $$$c = 5$$$ (when $$$n = 2$$$); $$$a = 6$$$, $$$b = 5$$$, $$$c = 4$$$ (when $$$n = 2$$$).In the second example the only possible case is $$$n = 1$$$: in this case $$$n \\cdot 2 + 2 - 3 = 1 = m$$$. Note that, $$$n = 0$$$ is not possible, since in that case $$$n$$$ is not a strictly positive integer."}, "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"}, {"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"}], "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"} {"nl": {"description": "Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.", "output_spec": "Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.", "sample_inputs": ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"], "sample_outputs": ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"], "notes": "NoteIn the first test case Polycarpus first writes to friend by name \"alex\", and the list looks as follows: alex Then Polycarpus writes to friend by name \"ivan\" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name \"roman\" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name \"ivan\", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex "}, "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 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"}, {"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"} {"nl": {"description": "Nikolay lives in a two-storied house. There are $$$n$$$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $$$1$$$ and $$$n$$$). If Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers $$$i$$$ and $$$i+1$$$ on each floor are neighbouring, for all $$$1 \\leq i \\leq n - 1$$$. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room $$$x$$$ on the first floor and the room $$$x$$$ on the second floor, then Nikolay can use it to move from one room to another. The picture illustrates a house with $$$n = 4$$$. There is a staircase between the room $$$2$$$ on the first floor and the room $$$2$$$ on the second floor, and another staircase between the room $$$4$$$ on the first floor and the room $$$4$$$ on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string \"0101\" in the input. Nikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been). Calculate the maximum number of rooms Nikolay can visit during his tour, if: he can start in any room on any floor of his choice, and he won't visit the same room twice. ", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then test cases follow. Each test case consists of two lines. The first line contains one integer $$$n$$$ $$$(1 \\le n \\le 1\\,000)$$$ \u2014 the number of rooms on each floor. The second line contains one string consisting of $$$n$$$ characters, each character is either a '0' or a '1'. If the $$$i$$$-th character is a '1', then there is a staircase between the room $$$i$$$ on the first floor and the room $$$i$$$ on the second floor. If the $$$i$$$-th character is a '0', then there is no staircase between the room $$$i$$$ on the first floor and the room $$$i$$$ on the second floor. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.", "output_spec": "For each test case print one integer \u2014 the maximum number of rooms Nikolay can visit during his tour, if he can start in any room on any floor, and he won't visit the same room twice.", "sample_inputs": ["4\n5\n00100\n8\n00000000\n5\n11111\n3\n110"], "sample_outputs": ["6\n8\n10\n6"], "notes": "NoteIn the first test case Nikolay may start in the first room of the first floor. Then he moves to the second room on the first floor, and then \u2014 to the third room on the first floor. Then he uses a staircase to get to the third room on the second floor. Then he goes to the fourth room on the second floor, and then \u2014 to the fifth room on the second floor. So, Nikolay visits $$$6$$$ rooms.There are no staircases in the second test case, so Nikolay can only visit all rooms on the same floor (if he starts in the leftmost or in the rightmost room).In the third test case it is possible to visit all rooms: first floor, first room $$$\\rightarrow$$$ second floor, first room $$$\\rightarrow$$$ second floor, second room $$$\\rightarrow$$$ first floor, second room $$$\\rightarrow$$$ first floor, third room $$$\\rightarrow$$$ second floor, third room $$$\\rightarrow$$$ second floor, fourth room $$$\\rightarrow$$$ first floor, fourth room $$$\\rightarrow$$$ first floor, fifth room $$$\\rightarrow$$$ second floor, fifth room.In the fourth test case it is also possible to visit all rooms: second floor, third room $$$\\rightarrow$$$ second floor, second room $$$\\rightarrow$$$ second floor, first room $$$\\rightarrow$$$ first floor, first room $$$\\rightarrow$$$ first floor, second room $$$\\rightarrow$$$ first floor, third room."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Alice and Bob play a game. Alice has $$$n$$$ cards, the $$$i$$$-th of them has the integer $$$a_i$$$ written on it. Bob has $$$m$$$ cards, the $$$j$$$-th of them has the integer $$$b_j$$$ written on it.On the first turn of the game, the first player chooses one of his/her cards and puts it on the table (plays it). On the second turn, the second player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the first turn, and plays it. On the third turn, the first player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the second turn, and plays it, and so on \u2014 the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.If some player cannot make a turn, he/she loses.For example, if Alice has $$$4$$$ cards with numbers $$$[10, 5, 3, 8]$$$, and Bob has $$$3$$$ cards with numbers $$$[6, 11, 6]$$$, the game may go as follows: Alice can choose any of her cards. She chooses the card with integer $$$5$$$ and plays it. Bob can choose any of his cards with number greater than $$$5$$$. He chooses a card with integer $$$6$$$ and plays it. Alice can choose any of her cards with number greater than $$$6$$$. She chooses the card with integer $$$10$$$ and plays it. Bob can choose any of his cards with number greater than $$$10$$$. He chooses a card with integer $$$11$$$ and plays it. Alice can choose any of her cards with number greater than $$$11$$$, but she has no such cards, so she loses. Both Alice and Bob play optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game).You have to answer two questions: who wins if Alice is the first player? who wins if Bob is the first player? ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Each test case consists of four lines. The first line of a test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of cards Alice has. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 50$$$) \u2014 the numbers written on the cards that Alice has. The third line contains one integer $$$m$$$ ($$$1 \\le m \\le 50$$$) \u2014 the number of Bob's cards. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \\dots, b_m$$$ ($$$1 \\le b_i \\le 50$$$) \u2014 the numbers on Bob's cards.", "output_spec": "For each test case, print two lines. The first line should be Alice if Alice wins when she is the first player; otherwise, the first line should be Bob. The second line should contain the name of the winner if Bob is the first player, in the same format.", "sample_inputs": ["4\n\n1\n\n6\n\n2\n\n6 8\n\n4\n\n1 3 3 7\n\n2\n\n4 2\n\n1\n\n50\n\n2\n\n25 50\n\n10\n\n1 2 3 4 5 6 7 8 9 10\n\n2\n\n5 15"], "sample_outputs": ["Bob\nBob\nAlice\nAlice\nAlice\nBob\nBob\nBob"], "notes": "NoteLet's consider the first test case of the example.Alice has one card with integer $$$6$$$, Bob has two cards with numbers $$$[6, 8]$$$.If Alice is the first player, she has to play the card with number $$$6$$$. Bob then has to play the card with number $$$8$$$. Alice has no cards left, so she loses.If Bob is the first player, then no matter which of his cards he chooses on the first turn, Alice won't be able to play her card on the second turn, so she will lose."}, "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"}, {"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"}], "negative_code": [], "src_uid": "581c89736e549300c566e4700b741906"} {"nl": {"description": "Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters \"a\", \"b\" and \"c\". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.", "input_spec": "The input consists of a single string $$$s$$$\u00a0($$$2 \\leq |s| \\leq 10^6$$$). The string $$$s$$$ consists only of characters \"a\", \"b\", \"c\". It is guaranteed that no two consecutive characters are equal.", "output_spec": "Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \\geq \\lfloor \\frac{|s|}{2} \\rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string \"IMPOSSIBLE\" (quotes for clarity).", "sample_inputs": ["cacbac", "abc", "cbacacacbcbababacbcb"], "sample_outputs": ["aba", "a", "cbaaacbcaaabc"], "notes": "NoteIn the first example, other valid answers include \"cacac\", \"caac\", \"aca\" and \"ccc\". "}, "positive_code": [{"source_code": "object E extends App {\n\n val s = readLine\n\n var l = 0\n var r = s.length - 1\n val prefix = new StringBuilder\n var res = \"\"\n\n while (res == \"\") {\n if (l == r) {\n val half = prefix.result()\n res = half + s(l) + half.reverse\n } else if (l > r) {\n val half = prefix.result()\n res = half + half.reverse\n } else if (s(l) == s(r)) {\n prefix += s(l)\n l += 1\n r -= 1\n } else if (s(l) == s(r - 1)) {\n r -= 1\n } else {\n l += 1\n }\n }\n\n println(if (res.length < s.length / 2) \"IMPOSSIBLE\" else res)\n}\n"}], "negative_code": [], "src_uid": "3bebb50d1c2ef9f80e78715614f039d7"} {"nl": {"description": "Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n\u2009+\u20091 points with coordinates (1,\u2009y1), (2,\u2009y2), ..., (2n\u2009+\u20091,\u2009y2n\u2009+\u20091), with the i-th segment connecting the point (i,\u2009yi) and the point (i\u2009+\u20091,\u2009yi\u2009+\u20091). For any even i (2\u2009\u2264\u2009i\u2009\u2264\u20092n) the following condition holds: yi\u2009-\u20091\u2009<\u2009yi and yi\u2009>\u2009yi\u2009+\u20091. We shall call a vertex of a polyline with an even x coordinate a mountain peak. The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2. Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1,\u2009r1), (2,\u2009r2), ..., (2n\u2009+\u20091,\u2009r2n\u2009+\u20091).Given Bolek's final picture, restore the initial one.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100). The next line contains 2n\u2009+\u20091 space-separated integers r1,\u2009r2,\u2009...,\u2009r2n\u2009+\u20091 (0\u2009\u2264\u2009ri\u2009\u2264\u2009100) \u2014 the y coordinates of the polyline vertices on Bolek's picture. It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.", "output_spec": "Print 2n\u2009+\u20091 integers y1,\u2009y2,\u2009...,\u2009y2n\u2009+\u20091 \u2014 the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.", "sample_inputs": ["3 2\n0 5 3 5 1 5 2", "1 1\n0 2 0"], "sample_outputs": ["0 5 3 4 1 4 2", "0 1 0"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "The only difference between easy and hard versions is constraints.Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.There are $$$n$$$ voters, and two ways to convince each of them to vote for you. The first way to convince the $$$i$$$-th voter is to pay him $$$p_i$$$ coins. The second way is to make $$$m_i$$$ other voters vote for you, and the $$$i$$$-th voter will vote for free.Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $$$m_1 = 1$$$, $$$m_2 = 2$$$, $$$m_3 = 2$$$, $$$m_4 = 4$$$, $$$m_5 = 5$$$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: $$${5} \\rightarrow {1, 5} \\rightarrow {1, 2, 3, 5} \\rightarrow {1, 2, 3, 4, 5}$$$.Calculate the minimum number of coins you have to spend so that everyone votes for you.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 5000$$$) \u2014 the number of voters. The next $$$n$$$ lines contains the description of voters. $$$i$$$-th line contains two integers $$$m_i$$$ and $$$p_i$$$ ($$$1 \\le p_i \\le 10^9, 0 \\le m_i < n$$$). It is guaranteed that the sum of all $$$n$$$ over all test cases does not exceed $$$5000$$$.", "output_spec": "For each test case print one integer \u2014 the minimum number of coins you have to spend so that everyone votes for you.", "sample_inputs": ["3\n3\n1 5\n2 10\n2 8\n7\n0 1\n3 1\n1 1\n6 1\n1 1\n4 1\n4 1\n6\n2 6\n2 3\n2 8\n2 7\n4 4\n5 5"], "sample_outputs": ["8\n0\n7"], "notes": "NoteIn the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: $$${3} \\rightarrow {1, 3} \\rightarrow {1, 2, 3}$$$.In the second example you don't need to buy votes. The set of people voting for you will change as follows: $$${1} \\rightarrow {1, 3, 5} \\rightarrow {1, 2, 3, 5} \\rightarrow {1, 2, 3, 5, 6, 7} \\rightarrow {1, 2, 3, 4, 5, 6, 7}$$$.In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: $$${2, 5} \\rightarrow {1, 2, 3, 4, 5} \\rightarrow {1, 2, 3, 4, 5, 6}$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "negative_code": [], "src_uid": "cc64dfbaadc7f9deae23c71df52d7326"} {"nl": {"description": "You are given $$$n$$$ points with integer coordinates on a coordinate axis $$$OX$$$. The coordinate of the $$$i$$$-th point is $$$x_i$$$. All points' coordinates are distinct and given in strictly increasing order.For each point $$$i$$$, you can do the following operation no more than once: take this point and move it by $$$1$$$ to the left or to the right (i..e., you can change its coordinate $$$x_i$$$ to $$$x_i - 1$$$ or to $$$x_i + 1$$$). In other words, for each point, you choose (separately) its new coordinate. For the $$$i$$$-th point, it can be either $$$x_i - 1$$$, $$$x_i$$$ or $$$x_i + 1$$$.Your task is to determine if you can move some points as described above in such a way that the new set of points forms a consecutive segment of integers, i.\u2009e. for some integer $$$l$$$ the coordinates of points should be equal to $$$l, l + 1, \\ldots, l + n - 1$$$.Note that the resulting points should have distinct coordinates.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of points in the set $$$x$$$. The second line of the test case contains $$$n$$$ integers $$$x_1 < x_2 < \\ldots < x_n$$$ ($$$1 \\le x_i \\le 10^6$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th point. It is guaranteed that the points are given in strictly increasing order (this also means that all coordinates are distinct). It is also guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 if the set of points from the test case can be moved to form a consecutive segment of integers, print YES, otherwise print NO.", "sample_inputs": ["5\n\n2\n\n1 4\n\n3\n\n1 2 3\n\n4\n\n1 2 3 7\n\n1\n\n1000000\n\n3\n\n2 5 6"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Task2 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 getNextNum\r\n\r\n val points = StdIn.readLine().split(\" \").map(_.toInt)\r\n\r\n var bigDistancesSum: Long = 0l\r\n var prevPoint = points(0)\r\n\r\n for (i <- points.tail) {\r\n bigDistancesSum += i - prevPoint - 1\r\n prevPoint = i\r\n }\r\n\r\n if (bigDistancesSum > 2) println(\"NO\")\r\n else println(\"YES\")\r\n }\r\n\r\n}"}], "negative_code": [], "src_uid": "f4267120fce9304fc4c45142b60fb867"} {"nl": {"description": "Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n\u2009=\u20095 the handkerchief pattern should look like that: \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a03\u00a02\u00a01\u00a00\u00a0\u00a00\u00a01\u00a02\u00a03\u00a04\u00a03\u00a02\u00a01\u00a000\u00a01\u00a02\u00a03\u00a04\u00a05\u00a04\u00a03\u00a02\u00a01\u00a00\u00a0\u00a00\u00a01\u00a02\u00a03\u00a04\u00a03\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a03\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00Your task is to determine the way the handkerchief will look like by the given n.", "input_spec": "The first line contains the single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20099).", "output_spec": "Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.", "sample_inputs": ["2", "3"], "sample_outputs": ["0\n 0 1 0\n0 1 2 1 0\n 0 1 0\n 0", "0\n 0 1 0\n 0 1 2 1 0\n0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0"], "notes": null}, "positive_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 + 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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "You are given $$$n$$$ strings $$$s_1, s_2, \\ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \\le \\lvert s_i \\rvert \\le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.", "output_spec": "If it is possible to make the strings equal, print \"YES\" (without quotes). Otherwise, print \"NO\" (without quotes). You can output each character in either lowercase or uppercase.", "sample_inputs": ["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings \"ca\" and \"cbab\" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to \"cab\". In the second test case, it is impossible to make all $$$n$$$ strings equal."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "You're given an integer $$$n$$$. For every integer $$$i$$$ from $$$2$$$ to $$$n$$$, assign a positive integer $$$a_i$$$ such that the following conditions hold: For any pair of integers $$$(i,j)$$$, if $$$i$$$ and $$$j$$$ are coprime, $$$a_i \\neq a_j$$$. The maximal value of all $$$a_i$$$ should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is $$$1$$$.", "input_spec": "The only line contains the integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$).", "output_spec": "Print $$$n-1$$$ integers, $$$a_2$$$, $$$a_3$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$1 \\leq a_i \\leq n$$$). If there are multiple solutions, print any of them.", "sample_inputs": ["4", "3"], "sample_outputs": ["1 2 1", "2 1"], "notes": "NoteIn the first example, notice that $$$3$$$ and $$$4$$$ are coprime, so $$$a_3 \\neq a_4$$$. Also, notice that $$$a=[1,2,3]$$$ satisfies the first condition, but it's not a correct answer because its maximal value is $$$3$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "There is a matrix A of size x\u2009\u00d7\u2009y filled with integers. For every , Ai,\u2009j\u2009=\u2009y(i\u2009-\u20091)\u2009+\u2009j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i,\u2009j)) you can move into one of the following cells: (i\u2009+\u20091,\u2009j) \u2014 only if i\u2009<\u2009x; (i,\u2009j\u2009+\u20091) \u2014 only if j\u2009<\u2009y; (i\u2009-\u20091,\u2009j) \u2014 only if i\u2009>\u20091; (i,\u2009j\u2009-\u20091) \u2014 only if j\u2009>\u20091.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?", "input_spec": "The first line contains one integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009200000) \u2014 the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the integers in the cells on your path.", "output_spec": "If all possible values of x and y such that 1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.", "sample_inputs": ["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"], "sample_outputs": ["YES\n3 3", "NO", "YES\n4 9"], "notes": "NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples."}, "positive_code": [{"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport java.util.TreeSet\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main2 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\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n\n var mx = -1\n var ok = true\n\n for (i <- 1 to n-1) mx = mx.max((a(i) - a(i-1)).abs)\n for (i <- 1 to n-1) {\n val diff = a(i) - a(i-1)\n diff match {\n case 0 => ok = false\n case -1 => ok &= a(i) % mx != 0 || mx == 1\n case 1 => ok &= a(i - 1) % mx != 0 || mx == 1\n case _ => ok &= diff.abs == mx\n }\n }\n\n if (mx == -1 || mx == 0) mx = a(0)\n\n out.println(if (ok) \"YES\\n\" + 1000000000 + \" \" + mx else \"NO\")\n out.flush()\n out.close()\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": [{"source_code": "import java.io._\nimport java.util\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport java.util.TreeSet\nimport scala.collection.mutable.ListBuffer\nimport scala.io.StdIn\n\nobject Main2 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\n val n = in.nextInt\n val a = in.nextLine.split(' ').map(_.toInt)\n\n var mx = -1\n var ok = true\n\n for (i <- 1 to n-1) mx = mx.max((a(i) - a(i-1)).abs)\n for (i <- 1 to n-1) {\n val diff = a(i) - a(i-1)\n diff match {\n case 0 => {}\n case -1 => ok &= a(i) % mx != 0 || mx == 1\n case 1 => ok &= a(i - 1) % mx != 0 || mx == 1\n case _ => ok &= diff.abs == mx\n }\n }\n\n if (mx == -1 || mx == 0) mx = a(0)\n\n out.println(if (ok) \"YES\\n\" + 1000000000 + \" \" + mx else \"NO\")\n out.flush()\n out.close()\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}"}], "src_uid": "3b725f11009768904514d87e2c7714ee"} {"nl": {"description": "The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i\u2009+\u20091. Reaching a certain rank i having not reached all the previous i\u2009-\u20091 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.", "input_spec": "The first input line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains n\u2009-\u20091 integers di (1\u2009\u2264\u2009di\u2009\u2264\u2009100). The third input line contains two integers a and b (1\u2009\u2264\u2009a\u2009<\u2009b\u2009\u2264\u2009n). The numbers on the lines are space-separated.", "output_spec": "Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.", "sample_inputs": ["3\n5 6\n1 2", "3\n5 6\n1 3"], "sample_outputs": ["5", "11"], "notes": null}, "positive_code": [{"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"}, {"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": "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"}, {"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}"}], "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"} {"nl": {"description": "Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 amount of squares in the stripe. The second line contains n space-separated numbers \u2014 they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.", "output_spec": "Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.", "sample_inputs": ["9\n1 5 -6 7 9 -16 0 -2 2", "3\n1 1 1", "2\n0 0"], "sample_outputs": ["3", "0", "1"], "notes": null}, "positive_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 n = nextInt\n val a = new Array[Int](n)\n var sum2 = 0\n for (i <- 0 until n) {\n a(i) = nextInt\n sum2 += a(i)\n }\n var sum1 = 0\n var ans = 0\n for (i <- 1 until n) {\n sum1 += a(i - 1)\n sum2 -= a(i - 1)\n if (sum1 == sum2) {\n ans += 1\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}"}], "negative_code": [], "src_uid": "5358fff5b798ac5e500d0f5deef765c7"} {"nl": {"description": "Bajtek, known for his unusual gifts, recently got an integer array $$$x_0, x_1, \\ldots, x_{k-1}$$$.Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $$$a$$$ of length $$$n + 1$$$. As a formal description of $$$a$$$ says, $$$a_0 = 0$$$ and for all other $$$i$$$\u00a0($$$1 \\le i \\le n$$$) $$$a_i = x_{(i-1)\\bmod k} + a_{i-1}$$$, where $$$p \\bmod q$$$ denotes the remainder of division $$$p$$$ by $$$q$$$.For example, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then: $$$a_0 = 0$$$, $$$a_1 = x_{0\\bmod 3}+a_0=x_0+0=1$$$, $$$a_2 = x_{1\\bmod 3}+a_1=x_1+1=3$$$, $$$a_3 = x_{2\\bmod 3}+a_2=x_2+3=6$$$, $$$a_4 = x_{3\\bmod 3}+a_3=x_0+6=7$$$, $$$a_5 = x_{4\\bmod 3}+a_4=x_1+7=9$$$. So, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then $$$a = [0, 1, 3, 6, 7, 9]$$$.Now the boy hopes that he will be able to restore $$$x$$$ from $$$a$$$! Knowing that $$$1 \\le k \\le n$$$, help him and find all possible values of $$$k$$$\u00a0\u2014 possible lengths of the lost array.", "input_spec": "The first line contains exactly one integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the length of the array $$$a$$$, excluding the element $$$a_0$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$). Note that $$$a_0$$$ is always $$$0$$$ and is not given in the input.", "output_spec": "The first line of the output should contain one integer $$$l$$$ denoting the number of correct lengths of the lost array. The second line of the output should contain $$$l$$$ integers\u00a0\u2014 possible lengths of the lost array in increasing order.", "sample_inputs": ["5\n1 2 3 4 5", "5\n1 3 5 6 8", "3\n1 5 3"], "sample_outputs": ["5\n1 2 3 4 5", "2\n3 5", "1\n3"], "notes": "NoteIn the first example, any $$$k$$$ is suitable, since $$$a$$$ is an arithmetic progression.Possible arrays $$$x$$$: $$$[1]$$$ $$$[1, 1]$$$ $$$[1, 1, 1]$$$ $$$[1, 1, 1, 1]$$$ $$$[1, 1, 1, 1, 1]$$$In the second example, Bajtek's array can have three or five elements.Possible arrays $$$x$$$: $$$[1, 2, 2]$$$ $$$[1, 2, 2, 1, 2]$$$For example, $$$k = 4$$$ is bad, since it leads to $$$6 + x_0 = 8$$$ and $$$0 + x_0 = 1$$$, which is an obvious contradiction.In the third example, only $$$k = n$$$ is good.Array $$$[1, 4, -2]$$$ satisfies the requirements.Note that $$$x_i$$$ may be negative."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Polycarp is practicing his problem solving skill. He has a list of $$$n$$$ problems with difficulties $$$a_1, a_2, \\dots, a_n$$$, respectively. His plan is to practice for exactly $$$k$$$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $$$n$$$ problems in exactly $$$k$$$ days.Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $$$k$$$ days he will solve all the $$$n$$$ problems.The profit of the $$$j$$$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $$$j$$$-th day (i.e. if he solves problems with indices from $$$l$$$ to $$$r$$$ during a day, then the profit of the day is $$$\\max\\limits_{l \\le i \\le r}a_i$$$). The total profit of his practice is the sum of the profits over all $$$k$$$ days of his practice.You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $$$n$$$ problems between $$$k$$$ days satisfying the conditions above in such a way, that the total profit is maximum.For example, if $$$n = 8, k = 3$$$ and $$$a = [5, 4, 2, 6, 5, 1, 9, 2]$$$, one of the possible distributions with maximum total profit is: $$$[5, 4, 2], [6, 5], [1, 9, 2]$$$. Here the total profit equals $$$5 + 6 + 9 = 20$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2000$$$) \u2014 the number of problems and the number of days, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 2000$$$) \u2014 difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).", "output_spec": "In the first line of the output print the maximum possible total profit. In the second line print exactly $$$k$$$ positive integers $$$t_1, t_2, \\dots, t_k$$$ ($$$t_1 + t_2 + \\dots + t_k$$$ must equal $$$n$$$), where $$$t_j$$$ means the number of problems Polycarp will solve during the $$$j$$$-th day in order to achieve the maximum possible total profit of his practice. If there are many possible answers, you may print any of them.", "sample_inputs": ["8 3\n5 4 2 6 5 1 9 2", "5 1\n1 1 1 1 1", "4 2\n1 2000 2000 2"], "sample_outputs": ["20\n3 2 3", "1\n5", "4000\n2 2"], "notes": "NoteThe first example is described in the problem statement.In the second example there is only one possible distribution.In the third example the best answer is to distribute problems in the following way: $$$[1, 2000], [2000, 2]$$$. The total profit of this distribution is $$$2000 + 2000 = 4000$$$."}, "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 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}"}, {"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": "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"}], "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"} {"nl": {"description": "Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of segments drawn by Vika. Each of the next n lines contains four integers x1, y1, x2 and y2 (\u2009-\u2009109\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009109)\u00a0\u2014 the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.", "output_spec": "Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.", "sample_inputs": ["3\n0 1 2 1\n1 4 1 2\n0 3 2 3", "4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2"], "sample_outputs": ["8", "16"], "notes": "NoteIn the first sample Vika will paint squares (0,\u20091), (1,\u20091), (2,\u20091), (1,\u20092), (1,\u20093), (1,\u20094), (0,\u20093) and (2,\u20093)."}, "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 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"}, {"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"} {"nl": {"description": "We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $$$s$$$ can transform to another superhero with name $$$t$$$ if $$$s$$$ can be made equal to $$$t$$$ by changing any vowel in $$$s$$$ to any other vowel and any consonant in $$$s$$$ to any other consonant. Multiple changes can be made.In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.Given the names of two superheroes, determine if the superhero with name $$$s$$$ can be transformed to the Superhero with name $$$t$$$.", "input_spec": "The first line contains the string $$$s$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. The second line contains the string $$$t$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. Both strings $$$s$$$ and $$$t$$$ are guaranteed to be different and consist of lowercase English letters only.", "output_spec": "Output \"Yes\" (without quotes) if the superhero with name $$$s$$$ can be transformed to the superhero with name $$$t$$$ and \"No\" (without quotes) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["a\nu", "abc\nukm", "akm\nua"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteIn the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $$$s$$$ to $$$t$$$.In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $$$s$$$ to $$$t$$$."}, "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 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}"}, {"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"} {"nl": {"description": "There is a bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct).We shall assume that the stop is located on the coordinate axis Ox, at point x\u2009=\u20090, and the bus goes along the ray Ox, that is, towards the positive direction of the coordinate axis, and back. The i-th student needs to get to the point with coordinate xi (xi\u2009>\u20090).The bus moves by the following algorithm. Initially it is at point 0. The students consistently come to the stop and get on it. The bus has a seating capacity which is equal to m passengers. At the moment when m students get on the bus, it starts moving in the positive direction of the coordinate axis. Also it starts moving when the last (n-th) student gets on the bus. The bus is moving at a speed of 1 unit of distance per 1 unit of time, i.e. it covers distance y in time y.Every time the bus passes the point at which at least one student needs to get off, it stops and these students get off the bus. The students need 1\u2009+\u2009[k\u2009/\u20092] units of time to get off the bus, where k is the number of students who leave at this point. Expression [k\u2009/\u20092] denotes rounded down k\u2009/\u20092. As soon as the last student leaves the bus, the bus turns around and goes back to the point x\u2009=\u20090. It doesn't make any stops until it reaches the point. At the given point the bus fills with students once more, and everything is repeated.If students come to the stop when there's no bus, they form a line (queue) and get on the bus in the order in which they came. Any number of students get on the bus in negligible time, you should assume that it doesn't take any time. Any other actions also take no time. The bus has no other passengers apart from the students.Write a program that will determine for each student the time when he got off the bus. The moment a student got off the bus is the moment the bus stopped at the student's destination stop (despite the fact that the group of students need some time to get off).", "input_spec": "The first line contains two space-separated integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of students and the number of passengers the bus can transport, correspondingly. Next n lines contain descriptions of the students, one per line. Each line contains a pair of integers ti,\u2009xi (1\u2009\u2264\u2009ti\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009104). The lines are given in the order of strict increasing of ti. Values of xi can coincide.", "output_spec": "Print n numbers w1,\u2009w2,\u2009...,\u2009wn, wi \u2014 the moment of time when the i-th student got off the bus. Print the numbers on one line and separate them with single spaces.", "sample_inputs": ["1 10\n3 5", "2 1\n3 5\n4 5", "5 4\n3 5\n4 5\n5 5\n6 5\n7 1", "20 4\n28 13\n31 13\n35 6\n36 4\n52 6\n53 4\n83 2\n84 4\n87 1\n93 6\n108 4\n113 6\n116 1\n125 2\n130 2\n136 13\n162 2\n166 4\n184 1\n192 2"], "sample_outputs": ["8", "8 19", "11 11 11 11 20", "51 51 43 40 93 89 86 89 114 121 118 121 137 139 139 152 195 199 193 195"], "notes": "NoteIn the first sample the bus waits for the first student for 3 units of time and drives him to his destination in additional 5 units of time. So the student leaves the bus at the moment of time 3\u2009+\u20095\u2009=\u20098.In the second sample the capacity of the bus equals 1, that's why it will drive the first student alone. This student is the same as the student from the first sample. So the bus arrives to his destination at the moment of time 8, spends 1\u2009+\u2009[1\u2009/\u20092]\u2009=\u20091 units of time on getting him off, and returns back to 0 in additional 5 units of time. That is, the bus returns to the bus stop at the moment of time 14. By this moment the second student has already came to the bus stop. So he immediately gets in the bus, and is driven to his destination in additional 5 units of time. He gets there at the moment 14\u2009+\u20095\u2009=\u200919. In the third sample the bus waits for the fourth student for 6 units of time, then drives for 5 units of time, then gets the passengers off for 1\u2009+\u2009[4\u2009/\u20092]\u2009=\u20093 units of time, then returns for 5 units of time, and then drives the fifth student for 1 unit of time."}, "positive_code": [{"source_code": "import java.io._\n\nobject Solution {\n def main(args: Array[String]) {\n val in = new BufferedReader(new InputStreamReader(System.in))\n def readInts = in.readLine.split(\" \").map(_.toInt).toList\n val n :: m :: _ = readInts\n val students = for(i <- 0 until n) yield {\n val t :: x :: _ = readInts\n (t, x, i)\n }\n var time = 0\n val ans = new Array[Int](n)\n for(chunk <- students grouped m) {\n time = (time /: chunk)(_ max _._1)\n val grouped = chunk.groupBy(_._2).toList\n val sorted = grouped.sortWith(_._1 < _._1)\n var biggestTime = 0\n for(l <- sorted) {\n for(s <- l._2) ans(s._3) = time + s._2\n time += 1 + l._2.length / 2\n biggestTime = l._1\n }\n time += biggestTime * 2\n }\n println(ans.mkString(\" \"))\n }\n}"}], "negative_code": [], "src_uid": "bb2ee9d4f718116ec391c93af58ec012"} {"nl": {"description": "This is an interactive problem. Refer to the Interaction section below for better understanding.Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.", "input_spec": "The first line contains 3 integers n,\u2009m and c (, means rounded up)\u00a0\u2014 the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.", "output_spec": null, "sample_inputs": ["2 4 4\n2\n1\n3"], "sample_outputs": ["1\n2\n2"], "notes": "NoteIn the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.The input format for hacking: The first line contains 3 integers n,\u2009m and c; The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round. "}, "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, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n\n val pos = if (p > c / 2) {\n var j = n - 1\n while (xs(j) > 0 && p <= xs(j)) j -= 1\n j\n } else {\n var j = 0\n while (xs(j) > 0 && p >= xs(j)) j += 1\n j\n }\n\n xs(pos) = p\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\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\n val Array(n, m, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n val cand = if (p == c) n - 1 else (p - 1) * n / c\n\n val pos = if (xs(cand) < 0) {\n cand\n } else if (p == xs(cand)) {\n var l = cand\n while (l > 0 && xs(l) == p) l -= 1\n var r = cand\n while (r < n - 1 && xs(r) == p) r += 1\n if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r\n } else if (p < xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1\n j\n } else if (p > xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1\n j\n } else -100\n\n xs(pos) = p\n //println(cand, xs.mkString(\" \"))\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\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(n, m, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n val cand = (p - 1) * n / c\n\n val pos = if (xs(cand) < 0) {\n cand\n } else if (xs(cand) == p) {\n var l = cand\n while (l > 0 && xs(l) == p) l -= 1\n var r = 0\n while (r < n - 1 && xs(r) == p) r += 1\n if (cand - l < r - cand && xs(l) != p) l else r\n } else if (p < xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1\n j\n } else if (p > xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1\n j\n } else -100\n\n\n xs(pos) = p\n //println(cand, xs.mkString(\" \"))\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\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, m, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n val cand = p * n / c - 1\n\n val pos = if (xs(cand) < 0) {\n cand\n } else if (p == xs(cand)) {\n var l = cand\n while (l > 0 && xs(l) == p) l -= 1\n var r = cand\n while (r < n - 1 && xs(r) == p) r += 1\n if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r\n } else if (p < xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1\n j\n } else if (p > xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1\n j\n } else -100\n\n xs(pos) = p\n //println(cand, xs.mkString(\" \"))\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\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, m, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n val cand = (p * n / c - 1) max 0\n\n val pos = if (xs(cand) < 0) {\n cand\n } else if (p == xs(cand)) {\n var l = cand\n while (l > 0 && xs(l) == p) l -= 1\n var r = cand\n while (r < n - 1 && xs(r) == p) r += 1\n if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r\n } else if (p < xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1\n j\n } else if (p > xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1\n j\n } else -100\n\n xs(pos) = p\n //println(cand, xs.mkString(\" \"))\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\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(n, m, c) = readInts(3)\n val xs = Array.fill(n)(c + 100)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n val cand = (p - 1) * n / c\n\n val pos = if (xs(cand) > c) {\n cand\n } else if (xs(cand) == p) {\n var l = cand\n while (l > 0 && xs(l) == p) l -= 1\n var r = 0\n while (r < n - 1 && xs(r) == p) r += 1\n if (cand - l < r - cand && xs(l) != p) l else r\n } else if (p < xs(cand)) {\n var j = cand\n while (xs(j) <= c && j > 0 && p < xs(j)) j -= 1\n j\n } else if (p > xs(cand)) {\n var j = cand\n while (xs(j) <= c && j < n - 1 && p > xs(j)) j += 1\n j\n } else -100\n\n\n xs(pos) = p\n //println(cand, xs.mkString(\" \"))\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = true\n while (i < n && solved) {\n if (xs(i) > c || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\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, m, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n\n val pos = if (p > c / 2) {\n var j = n - 1\n while (xs(j) > 0 && p < xs(j)) j -= 1\n j\n } else {\n var j = 0\n while (xs(j) > 0 && p > xs(j)) j += 1\n j\n }\n\n xs(pos) = p\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\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, m, c) = readInts(3)\n val xs = Array.fill(n)(-1)\n\n var solved = false\n while (!solved) {\n\n val p = readLine.toInt\n val cand = (p - 1) * n / c\n\n val pos = if (xs(cand) < 0) {\n cand\n } else if (p == xs(cand)) {\n var l = cand\n while (l > 0 && xs(l) == p) l -= 1\n var r = cand\n while (r < n - 1 && xs(r) == p) r += 1\n if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r\n } else if (p < xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1\n j\n } else if (p > xs(cand)) {\n var j = cand\n while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1\n j\n } else -100\n\n xs(pos) = p\n //println(cand, xs.mkString(\" \"))\n\n println(pos + 1)\n Console.flush\n\n var i = 1\n solved = xs(0) > 0\n while (i < n && solved) {\n if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false\n i += 1\n }\n }\n}\n"}], "src_uid": "305159945f077d5fff514bfd398eb10e"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $$$1$$$. You can't choose a string if it is empty.For example: by applying a move to the string \"where\", the result is the string \"here\", by applying a move to the string \"a\", the result is an empty string \"\". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.Write a program that finds the minimum number of moves to make two given strings $$$s$$$ and $$$t$$$ equal.", "input_spec": "The first line of the input contains $$$s$$$. In the second line of the input contains $$$t$$$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $$$2\\cdot10^5$$$, inclusive.", "output_spec": "Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.", "sample_inputs": ["test\nwest", "codeforces\nyes", "test\nyes", "b\nab"], "sample_outputs": ["2", "9", "7", "1"], "notes": "NoteIn the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to \"est\".In the second example, the move should be applied to the string \"codeforces\" $$$8$$$ times. As a result, the string becomes \"codeforces\" $$$\\to$$$ \"es\". The move should be applied to the string \"yes\" once. The result is the same string \"yes\" $$$\\to$$$ \"es\".In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.In the fourth example, the first character of the second string should be deleted."}, "positive_code": [{"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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \\ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.", "input_spec": "First line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\leq x_i,y_i \\leq 10^9$$$).", "output_spec": "Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.", "sample_inputs": ["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"], "sample_outputs": ["3", "4"], "notes": "NoteIllustration for the first example: Illustration for the second example: "}, "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": "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"}, {"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"} {"nl": {"description": "There is a forest that we model as a plane and live $$$n$$$ rare animals. Animal number $$$i$$$ has its lair in the point $$$(x_{i}, y_{i})$$$. In order to protect them, a decision to build a nature reserve has been made.The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.For convenience, scientists have made a transformation of coordinates so that the river is defined by $$$y = 0$$$. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of animals. Each of the next $$$n$$$ lines contains two integers $$$x_{i}$$$, $$$y_{i}$$$ ($$$-10^7 \\le x_{i}, y_{i} \\le 10^7$$$) \u2014 the coordinates of the $$$i$$$-th animal's lair. It is guaranteed that $$$y_{i} \\neq 0$$$. No two lairs coincide.", "output_spec": "If the reserve cannot be built, print $$$-1$$$. Otherwise print the minimum radius. Your answer will be accepted if absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["1\n0 1", "3\n0 1\n0 2\n0 -3", "2\n0 1\n1 1"], "sample_outputs": ["0.5", "-1", "0.625"], "notes": "NoteIn the first sample it is optimal to build the reserve with the radius equal to $$$0.5$$$ and the center in $$$(0,\\ 0.5)$$$.In the second sample it is impossible to build a reserve.In the third sample it is optimal to build the reserve with the radius equal to $$$\\frac{5}{8}$$$ and the center in $$$(\\frac{1}{2},\\ \\frac{5}{8})$$$."}, "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 X, Y = Array.ofDim[Int](N)\n rep(N) { i =>\n X(i) = ni()\n Y(i) = ni()\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 binSearch(l: Double, h: Double)(f: Double => Boolean): Double = {\n // lt\u3092\u3053\u3053\u3067\u3064\u304b\u3046\u3068EPS\u304c\u3089\u307f\u3067\u304a\u304b\u3057\u3044\u3053\u3068\u306b\u306a\u3063\u3066\u7d42\u4e86\u3057\u306a\u3044\n if (h - l < EPS * max(1, min(abs(l), abs(h)))) h\n else {\n val mid = (h + l) / 2.0\n if (f(mid)) binSearch(l, mid)(f)\n else binSearch(mid, h)(f)\n }\n }\n\n if (Y.exists(_ > 0) && Y.exists(_ < 0)) {\n out.println(-1)\n } else {\n rep(N) { i =>\n Y(i) = abs(Y(i))\n }\n\n val ans = binSearch(0.0, 1e16) { y =>\n var ms = -1e16\n var mx = 1e16\n 0 until N forall { i =>\n if (lt(2 * y, Y(i))) false\n else {\n val h = abs(Y(i) - y)\n val w = Math.sqrt(y + h) * Math.sqrt(y - h)\n ms = max(ms, X(i) - w)\n mx = min(mx, X(i) + w)\n lt(ms, mx)\n }\n }\n }\n out.println(f\"$ans%.6f\")\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 = ni()\n val X, Y = Array.ofDim[Int](N)\n rep(N) { i =>\n X(i) = ni()\n Y(i) = ni()\n }\n\n if (Y.exists(_ > 0) && Y.exists(_ < 0)) {\n out.println(-1)\n } else {\n rep(N) { i =>\n Y(i) = abs(Y(i))\n }\n\n val E = 0.0000000001\n\n def test(y: Double): Boolean = {\n var ms = -1e7\n var mx = 1e7\n 0 until N forall { i =>\n val h = abs(Y(i) - y)\n if (abs(h) < E) true\n else if (h > y - E) false\n else {\n val t = Math.asin(h / y)\n val w = Math.cos(t) * y\n ms = max(ms, X(i) - w)\n mx = min(mx, X(i) + w)\n ms < mx + E\n }\n }\n }\n\n var l = 0.0\n var h = 2e7\n\n rep(100) { _ =>\n val mid = (h + l) / 2\n if (test(mid)) h = mid\n else l = mid\n }\n\n out.println(f\"$l%.6f\")\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}"}], "src_uid": "d01f153d0049c22a21e321d5c4fbece9"} {"nl": {"description": "There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical \u2014 formally, for every $$$i \\in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold: segments $$$h_1$$$ and $$$h_2$$$ are horizontal; segments $$$v_1$$$ and $$$v_2$$$ are vertical; segment $$$h_1$$$ intersects with segment $$$v_1$$$; segment $$$h_2$$$ intersects with segment $$$v_1$$$; segment $$$h_1$$$ intersects with segment $$$v_2$$$; segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 5000$$$) \u2014 the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.", "output_spec": "Print one integer \u2014 the number of ways to choose four segments so they form a rectangle.", "sample_inputs": ["7\n-1 4 -1 -2\n6 -1 -2 -1\n-2 3 6 3\n2 -2 2 4\n4 -1 4 3\n5 3 5 1\n5 2 1 2", "5\n1 5 1 0\n0 1 5 1\n5 4 0 4\n4 2 4 0\n4 3 4 5"], "sample_outputs": ["7", "0"], "notes": "NoteThe following pictures represent sample cases: "}, "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[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 case class Seg(v: Int, from: Int, to: Int)\n case class Event(y: Int, tpe: Int, seg: Seg)\n\nclass 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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\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 \u304cLong\u3068\u304b\u3058\u3083\u306a\u3044\u5834\u5408\u306f\u3053\u308c\u3089\u3092\u5b9f\u88c5\u3057\u306a\u3044\u3068\u4e0b\u306e\u5974\u3089\u304c\u4f7f\u3048\u306a\u3044\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val E_buf = ArrayBuffer[Event]()\n var zipX_buf = ArrayBuffer[Int]()\n REP(n) { _ =>\n val x1, y1, x2, y2 = ni()\n if (x1 == x2) {\n val v = Seg(x1, min(y1, y2), max(y1, y2))\n E_buf += Event(min(y1, y2), 1, v)\n E_buf += Event(max(y1, y2), 3, v)\n } else {\n val h = Seg(y1, min(x1, x2), max(x1, x2))\n E_buf += Event(y1, 2, h)\n }\n zipX_buf += x1\n zipX_buf += x2\n }\n\n // n\u304c\u5c11\u306a\u3044\u304b\u3089\u3053\u308c\u3067ok\n val E = E_buf.sortBy(e => (e.y, e.tpe)).toArray\n\n val MAX = isDebug(20, 10000)\n val OFF = isDebug(10, 5000)\n\n val zipX = zipX_buf.distinct.sorted.toArray\n val zipX_rev = Array.fill[Int](MAX + 1)(-1)\n REP(zipX.length) { i =>\n zipX_rev(zipX(i) + OFF) = i\n }\n\n debug(zipX)\n debug(zipX_rev)\n\n val vlines, flg = Array.ofDim[Boolean](zipX.length)\n var ans = 0L\n REP(E.length) { i =>\n if (E(i).tpe == 2) {\n val s = E(i).y\n val bit = new BIT(vlines.length)\n var id = 0\n while(id < vlines.length) {\n if (vlines(id) && E(i).seg.from <= zipX(id) && zipX(id) <= E(i).seg.to) {\n flg(id) = true\n } else {\n flg(id) = false\n }\n id += 1\n }\n REP(vlines.length) { id =>\n if (flg(id)) bit.add(id, 1)\n }\n var j = i + 1\n while(j < E.length) {\n if (E(j).tpe == 3) {\n val x = E(j).seg.v\n val xid = zipX_rev(x+OFF)\n if (flg(xid)) {\n bit.add(xid, -1)\n flg(xid) = false\n }\n } else if(E(j).tpe == 2) {\n val x1 = E(j).seg.from\n val x2 = E(j).seg.to\n val cnt = bit.query(zipX_rev(x1+OFF), zipX_rev(x2+OFF) + 1)\n debug(s\"$s ${E(j).y} $x1 $x2 $cnt\")\n ans += max(0, cnt * (cnt - 1) / 2)\n }\n j += 1\n }\n\n } else if (E(i).tpe == 1) {\n val x = E(i).seg.v\n vlines(zipX_rev(x+OFF)) = true\n } else {\n val x = E(i).seg.v\n vlines(zipX_rev(x+OFF)) = false\n }\n }\n\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "09890f75bdcfff81f67eb915379b325e"} {"nl": {"description": "You are given a set of all integers from $$$l$$$ to $$$r$$$ inclusive, $$$l < r$$$, $$$(r - l + 1) \\le 3 \\cdot 10^5$$$ and $$$(r - l)$$$ is always odd.You want to split these numbers into exactly $$$\\frac{r - l + 1}{2}$$$ pairs in such a way that for each pair $$$(i, j)$$$ the greatest common divisor of $$$i$$$ and $$$j$$$ is equal to $$$1$$$. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.", "input_spec": "The only line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le 10^{18}$$$, $$$r - l + 1 \\le 3 \\cdot 10^5$$$, $$$(r - l)$$$ is odd).", "output_spec": "If any solution exists, print \"YES\" in the first line. Each of the next $$$\\frac{r - l + 1}{2}$$$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $$$1$$$. All $$$(r - l + 1)$$$ numbers should be pairwise distinct and should have values from $$$l$$$ to $$$r$$$ inclusive. If there are multiple solutions, print any of them. If there exists no solution, print \"NO\".", "sample_inputs": ["1 8"], "sample_outputs": ["YES\n2 7\n4 1\n3 8\n6 5"], "notes": null}, "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 L, R = nl()\n val N = (R - L + 1).toInt\n out.println(\"YES\")\n rep(N / 2) { k =>\n val i = L + 2 * k\n val j = i + 1\n 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): 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": "6432a543eeee9833c6d849222ad6b93d"} {"nl": {"description": "Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.", "input_spec": "The first line contains four integers c1,\u2009c2,\u2009c3,\u2009c4 (1\u2009\u2264\u2009c1,\u2009c2,\u2009c3,\u2009c4\u2009\u2264\u20091000) \u2014 the costs of the tickets. The second line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000) \u2014 the number of buses and trolleys Vasya is going to use. The third line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 the number of times Vasya is going to use the bus number i. The fourth line contains m integers bi (0\u2009\u2264\u2009bi\u2009\u2264\u20091000) \u2014 the number of times Vasya is going to use the trolley number i.", "output_spec": "Print a single number \u2014 the minimum sum of burles Vasya will have to spend on the tickets.", "sample_inputs": ["1 3 7 19\n2 3\n2 5\n4 4 4", "4 3 2 1\n1 3\n798\n1 2 3", "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42"], "sample_outputs": ["12", "1", "16"], "notes": "NoteIn the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2\u00b71)\u2009+\u20093\u2009+\u20097\u2009=\u200912 burles.In the second sample the profitable strategy is to buy one ticket of the fourth type.In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: \"Many are my names in many countries. Mithrandir among the Elves, Thark\u00fbn to the Dwarves, Ol\u00f3rin I was in my youth in the West that is forgotten, in the South Inc\u00e1nus, in the North Gandalf; to the East I go not.\"And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as \"kazak\", \"oo\" and \"r\" are palindromes, but strings \"abb\" and \"ij\" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print \"Impossible\" (without quotes).", "input_spec": "The first line contains one string $$$s$$$ ($$$1 \\le |s| \\le 5\\,000$$$)\u00a0\u2014 the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.", "output_spec": "Print one integer $$$k$$$\u00a0\u2014 the minimum number of cuts needed to get a new name, or \"Impossible\" (without quotes).", "sample_inputs": ["nolon", "otto", "qqqq", "kinnikkinnik"], "sample_outputs": ["2", "1", "Impossible", "1"], "notes": "NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin."}, "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 C = Array.ofDim[Int](26)\n REP(N) { i =>\n C(S(i) - 'a') += 1\n }\n\n /**\n * s\u6587\u5b57\u76ee\u304b\u3089\u59cb\u3081\u3066\u8db3\u308a\u306a\u3044\u5206\u306f\u30b9\u30e9\u30a4\u30c9\u3057\u3066N\u6587\u5b57\u5217\u4f5c\u3063\u305f\u5834\u5408\u3001\u56de\u6587\u306b\u306a\u3063\u3066\u3044\u308b\u304b\n */\n def testPali(s: Int): Boolean = {\n var ok = true\n REP(N / 2) { i =>\n ok &&= S((s + i) % N) == S((s + N - 1 - i) % N)\n }\n ok\n }\n\n def testNotSame(s: Int): Boolean = {\n var ok = false\n REP(N) { i =>\n ok ||= S((s + i) % N) != S(i)\n }\n ok\n }\n\n val mxUsed = C.max\n if (mxUsed == N || mxUsed == N - 1) {\n out.println(\"Impossible\")\n } else {\n var ans = 2\n REP(N - 1, 1) { i =>\n if (testPali(i) && testNotSame(i)) {\n// debug(s\"find cut1 $i\")\n ans = min(ans, 1)\n }\n }\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 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 S = ns()\n val N = S.length\n\n val memo = Array.fill[Int](N + 1)(-1)\n /**\n * \u56de\u6587\u30c1\u30a7\u30c3\u30af\n * @param i 1-indexed\n */\n def test(i: Int): Boolean = {\n// debug(s\"test($i)\")\n if (memo(i) == -1) {\n var ok = true\n REP(i / 2) { j =>\n val oppo = i - 1 - j\n ok &&= S(oppo) == S(j)\n }\n memo(i) = if (ok) 1 else 0\n }\n memo(i) == 1\n }\n\n /**\n * \u5076\u306e\u56de\u6587\u3092\u3092\u534a\u5206\u306b\u5206\u5272\u3057\u3066\u3044\u3063\u3066\u3001\u6700\u5f8c\u306b\u56de\u6587\u3058\u3083\u306a\u3044\u3082\u306e\u306b\u306a\u308b\u304b\u3069\u3046\u304b\n * 12211221 => 1221 => 12 => ok\n * 1232112321 => 12321 => no\n * @param i 1-indexed\n */\n def check(i: Int): Boolean = {\n i % 2 == 0 && {\n !test(i / 2) || check(i / 2)\n }\n }\n\n val INF = 100\n var ans = INF\n\n // \u5de6\u304b\u3089\u771f\u3093\u4e2d\u307e\u3067\u3067\u56de\u6587\u304c\u306a\u3051\u308c\u3070\u9006\u5074\u3068\u5165\u308c\u66ff\u3048\u3066\u5225\u306e\u540d\u524d\u306b\u3067\u304d\u308b\n REP(N / 2, 1) { i =>\n if (!test(i)) {\n // \u3061\u3087\u3046\u3069\u771f\u3093\u4e2d\u306e\u5834\u5408\u306f\u5206\u5272\u306f\uff11\u56de\u3067\u3044\u3044\n if (N % 2 == 0 && i == N / 2) {\n// debug(s\"HOGE $i\")\n ans = min(1, ans)\n }\n else ans = min(2, ans)\n }\n else {\n // \u56de\u6587\u3060\u3063\u305f\u5834\u5408\u306f\u3001\u5076\u306e\u5834\u5408\u306a\u3089\u5de6\u534a\u5206\u3092\u4e00\u756a\u53f3\u306b\u3082\u3063\u3066\u3044\u304f\u3053\u3068\u3067\u56de\u6587\u3092\u3064\u304f\u308c\u308b\n // \u305f\u3060\u3057\u3053\u308c\u3082\u56de\u6587\u3060\u3063\u305f\u5834\u5408\u3001\u3082\u3068\u306e\u6587\u5b57\u3068\u3044\u3063\u3057\u3087\u306b\u306a\u308b\u306e\u3067\u3001\u3055\u3089\u306b\u540c\u3058\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u3066\u56de\u6587\u3067\u306a\u3044\u3082\u306e\u304c\u306a\u3044\u304b\u63a2\u3059\n if (check(i)) {\n// debug(s\"FUGA $i\")\n ans = min(1, ans)\n }\n }\n }\n\n// debug(memo)\n\n if (ans == INF) out.println(\"Impossible\")\n else 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 Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 C = Array.ofDim[Int](26)\n REP(N) { i =>\n C(S(i) - 'a') += 1\n }\n\n /**\n * s\u6587\u5b57\u76ee\u304b\u3089\u59cb\u3081\u3066\u8db3\u308a\u306a\u3044\u5206\u306f\u30b9\u30e9\u30a4\u30c9\u3057\u3066N\u6587\u5b57\u5217\u4f5c\u3063\u305f\u5834\u5408\u3001\u56de\u6587\u306b\u306a\u3063\u3066\u3044\u308b\u304b\n */\n def testPali(s: Int): Boolean = {\n var ok = true\n REP(N / 2) { i =>\n ok &&= S((s + i) % N) == S((s + N - 1 - i) % N)\n }\n ok\n }\n\n val mxUsed = C.max\n if (mxUsed == N || mxUsed == N - 1) {\n out.println(\"Impossible\")\n } else {\n var ans = 2\n REP(N - 1, 1) { i =>\n if (testPali(i)) ans = min(ans, 1)\n }\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 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}"}], "src_uid": "ffdef277d0ff8e8579b113f5bd30f52a"} {"nl": {"description": "You are given a tree consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is equal to $$$a_i$$$.Let's denote the function $$$g(x, y)$$$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $$$x$$$ to vertex $$$y$$$ (including these two vertices). Also let's denote $$$dist(x, y)$$$ as the number of vertices on the simple path between vertices $$$x$$$ and $$$y$$$, including the endpoints. $$$dist(x, x) = 1$$$ for every vertex $$$x$$$.Your task is calculate the maximum value of $$$dist(x, y)$$$ among such pairs of vertices that $$$g(x, y) > 1$$$.", "input_spec": "The first line contains one integer $$$n$$$ \u2014 the number of vertices $$$(1 \\le n \\le 2 \\cdot 10^5)$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \\le a_i \\le 2 \\cdot 10^5)$$$ \u2014 the numbers written on vertices. Then $$$n - 1$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ $$$(1 \\le x, y \\le n, x \\ne y)$$$ denoting an edge connecting vertex $$$x$$$ with vertex $$$y$$$. It is guaranteed that these edges form a tree.", "output_spec": "If there is no pair of vertices $$$x, y$$$ such that $$$g(x, y) > 1$$$, print $$$0$$$. Otherwise print the maximum value of $$$dist(x, y)$$$ among such pairs.", "sample_inputs": ["3\n2 3 4\n1 2\n2 3", "3\n2 3 4\n1 3\n2 3", "3\n1 1 1\n1 2\n2 3"], "sample_outputs": ["1", "2", "0"], "notes": null}, "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 val P = Array(\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,\n 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,\n 73, 79, 83, 89, 97,101,103,107,109,113,\n 127,131,137,139,149,151,157,163,167,173,\n 179,181,191,193,197,199,211,223,227,229,\n 233,239,241,251,257,263,269,271,277,281,\n 283,293,307,311,313,317,331,337,347,349,\n 353,359,367,373,379,383,389,397,401,409,\n 419,421,431,433,439,443,449\n )\n\n val NN = 2e5.toInt\n val prime = Array.ofDim[Int](2e4.toInt)\n val factor = Array.ofDim[Int](NN + 1)\n var pp = 0\n\n 2 to NN foreach { i =>\n if (factor(i) == 0) {\n factor(i) = i\n prime(pp) = i\n pp += 1\n }\n\n def fill(p: Int): Unit = {\n if (p < pp && prime(p) * i <= NN) {\n factor(prime(p) * i) = prime(p)\n if (prime(p) != i)\n fill(p + 1)\n }\n }\n\n fill(0)\n }\n\n def factorize(x: Int)(fn: Int => Unit): Unit = {\n if (x > 1) {\n val f = factor(x)\n fn(f)\n factorize(x / f)(fn)\n }\n }\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (_, parent, queue) = traceBfs(g)\n\n val flg = Array.ofDim[Boolean](N)\n val dp = Array.ofDim[Int](N)\n\n var ans = 0\n\n // \u221aN\u307e\u3067\n REP(P.length) { i =>\n val p = P(i)\n REP(N) { j =>\n flg(j) = A(j) % p == 0\n }\n\n REP_r(N) { j =>\n val v = queue(j)\n if (!flg(v)) {\n dp(v) = 0\n } else {\n var c1, c2 = 0\n REP(g(v).length) { k =>\n val u = g(v)(k)\n if (u != parent(v)) {\n c2 = max(c2, dp(u))\n if (c2 > c1) {\n val tmp = c1\n c1 = c2\n c2 = tmp\n }\n }\n }\n dp(v) = c1 + 1\n ans = max(ans, c1 + c2 + 1)\n }\n }\n }\n\n def findBigPrime(x: Int): Int = {\n factorize(x) { p =>\n if (p.toLong * p > NN) return p\n }\n 0\n }\n\n // \u221aN\u4ee5\u964d\u306f\u30ce\u30fc\u30c9\u3092\u5404\u3005\uff11\u56de\u3060\u3051\u5272\u308a\u5f53\u3066\u308b\u3068\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\n\n // \u221aN\u4ee5\u964d\u306e\u7d20\u6570\u304c\u56e0\u6570\u306a\u3089\u305d\u306e\u5024\u304c\u5165\u3063\u3066\u3044\u308b\n val B = Array.ofDim[Int](N)\n REP(N) { i =>\n B(i) = findBigPrime(A(i))\n }\n\n REP_r(N) { i =>\n val v = queue(i)\n if (B(v) == 0) {\n dp(v) = 0\n } else {\n var c1, c2 = 0\n REP(g(v).length) { k =>\n val u = g(v)(k)\n if (u != parent(v) && B(u) == B(v)) { // \u7d20\u6570\u304c\u4e00\u7dd2\u306e\u3082\u306e\u3060\u3051\n c2 = max(c2, dp(u))\n if (c2 > c1) {\n val tmp = c1\n c1 = c2\n c2 = tmp\n }\n }\n }\n dp(v) = c1 + 1\n ans = max(ans, c1 + c2 + 1)\n }\n }\n\n out.println(ans)\n }\n\n /**\n * @param n \u30ce\u30fc\u30c9\u6570\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 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 val P = Array(\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,\n 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,\n 73, 79, 83, 89, 97,101,103,107,109,113,\n 127,131,137,139,149,151,157,163,167,173,\n 179,181,191,193,197,199,211,223,227,229,\n 233,239,241,251,257,263,269,271,277,281,\n 283,293,307,311,313,317,331,337,347,349,\n 353,359,367,373,379,383,389,397,401,409,\n 419,421,431,433,439,443,449\n )\n\n def solve(): Unit = {\n val N = ni()\n val A = na(N)\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (_, parent, queue) = traceBfs(g)\n\n val flg = Array.ofDim[Boolean](N)\n val dp = Array.ofDim[Int](N)\n\n var ans = 0\n REP(P.length) { i =>\n val p = P(i)\n REP(N) { j =>\n flg(j) = A(j) % p == 0\n }\n\n REP_r(N) { j =>\n val v = queue(j)\n if (!flg(v)) {\n dp(v) = 0\n } else {\n var mxChild = 0\n REP(g(v).length) { k =>\n val u = g(v)(k)\n if (u != parent(v)) mxChild = max(mxChild, dp(u))\n }\n dp(v) = mxChild + 1\n }\n ans = max(ans, dp(v))\n }\n }\n\n out.println(ans)\n }\n\n /**\n * @param n \u30ce\u30fc\u30c9\u6570\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 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": "ba82353e9bc1ee36ed068547d2f4043d"} {"nl": {"description": "Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time \"glued to the screen\", your vision is impaired. So you have to write a program that will pass the check for you.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of mannequins. Next n lines contain two space-separated integers each: xi,\u2009yi (|xi|,\u2009|yi|\u2009\u2264\u20091000) \u2014 the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.", "output_spec": "Print a single real number \u2014 the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10\u2009-\u20096. ", "sample_inputs": ["2\n2 0\n0 2", "3\n2 0\n0 2\n-2 2", "4\n2 0\n0 2\n-2 0\n0 -2", "2\n2 1\n1 2"], "sample_outputs": ["90.0000000000", "135.0000000000", "270.0000000000", "36.8698976458"], "notes": "NoteSolution for the first sample test is shown below: Solution for the second sample test is shown below: Solution for the third sample test is shown below: Solution for the fourth sample test is shown below: "}, "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"}, {"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"}], "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"} {"nl": {"description": "As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.", "input_spec": "The first line contains two space-separated positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u20091000) \u2014 the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) \u2014 the towers' initial heights.", "output_spec": "In the first line print two space-separated non-negative integers s and m (m\u2009\u2264\u2009k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i\u2009\u2260\u2009j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.", "sample_inputs": ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"], "sample_outputs": ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"], "notes": "NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6."}, "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 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"}, {"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"} {"nl": {"description": "Little X used to play a card game called \"24 Game\", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1,\u20092,\u2009...,\u2009n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a\u2009+\u2009b, or a\u2009-\u2009b, or a\u2009\u00d7\u2009b.After n\u2009-\u20091 steps there is only one number left. Can you make this number equal to 24?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "If it's possible, print \"YES\" in the first line. Otherwise, print \"NO\" (without the quotes). If there is a way to obtain 24 as the result number, in the following n\u2009-\u20091 lines print the required operations an operation per line. Each operation should be in form: \"a op b = c\". Where a and b are the numbers you've picked at this operation; op is either \"+\", or \"-\", or \"*\"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.", "sample_inputs": ["1", "8"], "sample_outputs": ["NO", "YES\n8 * 7 = 56\n6 * 5 = 30\n3 - 4 = -1\n1 - 2 = -1\n30 - -1 = 31\n56 - 31 = 25\n25 + -1 = 24"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $$$a_1, a_2, \\dots, a_n$$$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \\dots a_{p - 1} a_p, b_1 b_2 \\dots b_{q - 1} b_q)$$$, where $$$a_1 \\dots a_p$$$ and $$$b_1 \\dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally, if $$$p \\ge q$$$ then $$$f(a_1 \\dots a_p, b_1 \\dots b_q) = a_1 a_2 \\dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$$$; if $$$p < q$$$ then $$$f(a_1 \\dots a_p, b_1 \\dots b_q) = b_1 b_2 \\dots b_{q - p} a_1 b_{q - p + 1} a_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $$$\\sum_{i = 1}^{n}\\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\\,244\\,353$$$.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$) \u2014 the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the elements of the array. All numbers $$$a_1, a_2, \\dots, a_n$$$ are of equal length (that is, they consist of the same number of digits).", "output_spec": "Print the answer modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["3\n12 33 45", "2\n123 456", "1\n1", "5\n1000000000 1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["26730", "1115598", "11", "265359409"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 998244353\n\n /*\n * 10^18\u307e\u3067\u306epow\u3092\u914d\u5217\u3067\u7528\u610f\u3057\u3066\u304a\u304f\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\u306e\u6574\u6570\u5024\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}"}, {"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"} {"nl": {"description": "There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m \u2014 the smallest number of points you should add on the line to make the distances between all neighboring points equal. ", "input_spec": "The first line contains a single integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the number of points. The second line contains a sequence of integers x1,\u2009x2,\u2009...,\u2009xn (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109) \u2014 the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.", "output_spec": "Print a single integer m \u2014 the smallest number of points you should add on the line to make the distances between all neighboring points equal. ", "sample_inputs": ["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"], "sample_outputs": ["1", "0", "8"], "notes": "NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything."}, "positive_code": [{"source_code": "object B {\n def gcd(a:Int, b:Int) : Int = {\n if (b == 0) {\n return a\n }\n return gcd(b, a%b)\n }\n def main(args: Array[String]) {\n val N = scala.io.StdIn.readLine().toInt\n val A = scala.io.StdIn.readLine().split(' ').map(_.toInt).sorted\n var divisor = 0\n for (i <- 1 to A.length-1) {\n val gap = Math.abs(A(i) - A(i-1))\n divisor = gcd(divisor, gap)\n }\n var res = 0\n for (i <- 1 to A.length-1) {\n val gap = Math.abs(A(i) - A(i-1))\n res += gap / divisor - 1\n }\n println(res)\n }\n}\n\n\n\n\n"}], "negative_code": [], "src_uid": "805d82c407c1b34f217f8836454f7e09"} {"nl": {"description": "There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id\u00a0\u2014 integer from 1 to n.It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti\u00a0\u2014 the moment in seconds in which the task will come, ki\u00a0\u2014 the number of servers needed to perform it, and di\u00a0\u2014 the time needed to perform this task in seconds. All ti are distinct.To perform the i-th task you need ki servers which are unoccupied in the second ti. After the servers begin to perform the task, each of them will be busy over the next di seconds. Thus, they will be busy in seconds ti,\u2009ti\u2009+\u20091,\u2009...,\u2009ti\u2009+\u2009di\u2009-\u20091. For performing the task, ki servers with the smallest ids will be chosen from all the unoccupied servers. If in the second ti there are not enough unoccupied servers, the task is ignored.Write the program that determines which tasks will be performed and which will be ignored.", "input_spec": "The first line contains two positive integers n and q (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009q\u2009\u2264\u2009105) \u2014 the number of servers and the number of tasks. Next q lines contains three integers each, the i-th line contains integers ti, ki and di (1\u2009\u2264\u2009ti\u2009\u2264\u2009106, 1\u2009\u2264\u2009ki\u2009\u2264\u2009n, 1\u2009\u2264\u2009di\u2009\u2264\u20091000)\u00a0\u2014 the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds. ", "output_spec": "Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.", "sample_inputs": ["4 3\n1 3 2\n2 2 1\n3 4 3", "3 2\n3 2 3\n5 1 2", "8 6\n1 3 20\n4 2 1\n6 5 5\n10 1 1\n15 3 6\n21 8 8"], "sample_outputs": ["6\n-1\n10", "3\n3", "6\n9\n30\n-1\n15\n36"], "notes": "NoteIn the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task."}, "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _747C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, q = read[Int]\n val expiry = Array.ofDim[Int](n)\n\n repeat(q) {\n val t, k, d = read[Int]\n\n val available = expiry.indices.filter(i => expiry(i) < t)\n\n val ans = if (available.length < k) {\n -1\n } else {\n var acc = 0\n available.take(k) foreach {i =>\n acc += i + 1\n expiry(i) = t + d - 1\n }\n acc\n }\n writeLine(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 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": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _747C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n, q = read[Int]\n val expiry = Array.ofDim[Int](n)\n\n repeat(q) {\n val t, k, d = read[Int]\n val available = expiry.zipWithIndex.collect {\n case (e, i) if e < t => (e, i)\n }\n val ans = if (available.length < k) {\n -1\n } else {\n var acc = 0\n available.sorted.take(k) foreach {\n case (_, i) =>\n acc += i + 1\n expiry(i) = t + d - 1\n }\n acc\n }\n writeLine(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 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 = \" \"): 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": "9f46205d62ba05d8bcc2c56f84b2d2b2"} {"nl": {"description": "In this problem you will have to deal with a real algorithm that is used in the VK social network.As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of T seconds (for example, T\u2009=\u200960\u00a0seconds\u2009=\u20091\u00a0min and T\u2009=\u200986400\u00a0seconds\u2009=\u20091\u00a0day). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.Let's consider the following formal model. We have a service that works for n seconds. We know the number of queries to this resource at at each moment of time t (1\u2009\u2264\u2009t\u2009\u2264\u2009n). Let's formulate the following algorithm of calculating the mean with exponential decay. Let c be some real number, strictly larger than one.// setting this constant value correctly can adjust // the time range for which statistics will be calculateddouble c = some constant value; // as the result of the algorithm's performance this variable will contain // the mean number of queries for the last // T seconds by the current moment of timedouble mean = 0.0; for t = 1..n: // at each second, we do the following: // at is the number of queries that came at the last second; mean = (mean + at / T) / c;Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant c correctly will make the value of mean not very different from the real mean value ax at t\u2009-\u2009T\u2009+\u20091\u2009\u2264\u2009x\u2009\u2264\u2009t. The advantage of such approach is that it only uses the number of requests at the current moment of time and doesn't require storing the history of requests for a large time range. Also, it considers the recent values with the weight larger than the weight of the old ones, which helps to react to dramatic change in values quicker.However before using the new theoretical approach in industrial programming, there is an obligatory step to make, that is, to test its credibility practically on given test data sets. Your task is to compare the data obtained as a result of the work of an approximate algorithm to the real data. You are given n values at, integer T and real number c. Also, you are given m moments pj (1\u2009\u2264\u2009j\u2009\u2264\u2009m), where we are interested in the mean value of the number of queries for the last T seconds. Implement two algorithms. The first one should calculate the required value by definition, i.e. by the formula . The second algorithm should calculate the mean value as is described above. Print both values and calculate the relative error of the second algorithm by the formula , where approx is the approximate value, obtained by the second algorithm, and real is the exact value obtained by the first algorithm.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105), integer T (1\u2009\u2264\u2009T\u2009\u2264\u2009n) and real number c (1\u2009<\u2009c\u2009\u2264\u2009100) \u2014 the time range when the resource should work, the length of the time range during which we need the mean number of requests and the coefficient c of the work of approximate algorithm. Number c is given with exactly six digits after the decimal point. The next line contains n integers at (1\u2009\u2264\u2009at\u2009\u2264\u2009106) \u2014 the number of queries to the service at each moment of time. The next line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the number of moments of time when we are interested in the mean number of queries for the last T seconds. The next line contains m integers pj (T\u2009\u2264\u2009pj\u2009\u2264\u2009n), representing another moment of time for which we need statistics. Moments pj are strictly increasing.", "output_spec": "Print m lines. The j-th line must contain three numbers real, approx and error, where: is the real mean number of queries for the last T seconds; approx is calculated by the given algorithm and equals mean at the moment of time t\u2009=\u2009pj (that is, after implementing the pj-th iteration of the cycle); is the relative error of the approximate algorithm. The numbers you printed will be compared to the correct numbers with the relative or absolute error 10\u2009-\u20094. It is recommended to print the numbers with at least five digits after the decimal point.", "sample_inputs": ["1 1 2.000000\n1\n1\n1", "11 4 1.250000\n9 11 7 5 15 6 6 6 6 6 6\n8\n4 5 6 7 8 9 10 11", "13 4 1.250000\n3 3 3 3 3 20 3 3 3 3 3 3 3\n10\n4 5 6 7 8 9 10 11 12 13"], "sample_outputs": ["1.000000 0.500000 0.500000", "8.000000 4.449600 0.443800\n9.500000 6.559680 0.309507\n8.250000 6.447744 0.218455\n8.000000 6.358195 0.205226\n8.250000 6.286556 0.237993\n6.000000 6.229245 0.038207\n6.000000 6.183396 0.030566\n6.000000 6.146717 0.024453", "3.000000 1.771200 0.409600\n3.000000 2.016960 0.327680\n7.250000 5.613568 0.225715\n7.250000 5.090854 0.297813\n7.250000 4.672684 0.355492\n7.250000 4.338147 0.401635\n3.000000 4.070517 0.356839\n3.000000 3.856414 0.285471\n3.000000 3.685131 0.228377\n3.000000 3.548105 0.182702"], "notes": null}, "positive_code": [{"source_code": "object Main extends App {\nimport java.awt.Point\nimport java.io._\nimport java.math.BigInteger\nimport java.util._\nimport java.lang.Math._\nimport scala.collection.JavaConversions._\n\n\nnew Thread(null, new B(), \"\", 256 * (1L << 20)).start()\n \n\n\nclass B extends Runnable {\n\n var in: BufferedReader = _\n\n var out: PrintWriter = _\n\n var tok: StringTokenizer = new StringTokenizer(\"\")\n\n def run() {\n try {\n val t1 = System.currentTimeMillis()\n in = new BufferedReader(new InputStreamReader(System.in))\n out = new PrintWriter(System.out)\n Locale.setDefault(Locale.US)\n solve()\n in.close()\n out.close()\n } catch {\n case t: Throwable => {\n t.printStackTrace(System.err)\n System.exit(-1)\n }\n }\n }\n\n private def readString(): String = {\n while (!tok.hasMoreTokens()) {\n tok = new StringTokenizer(in.readLine())\n }\n tok.nextToken()\n }\n\n private def readInt(): Int = {\n java.lang.Integer.parseInt(readString())\n }\n\n private def readLong(): Long = java.lang.Long.parseLong(readString())\n\n private def readDouble(): Double = {\n java.lang.Double.parseDouble(readString())\n }\n\n private def solve() {\n val n = readInt()\n val T = readInt()\n val c = readDouble()\n val a = Array.ofDim[Long](n)\n val sum = Array.ofDim[Long](n)\n val true_average = Array.ofDim[Double](n)\n val approximate_average = Array.ofDim[Double](n)\n for (i <- 0 until n) {\n a(i) = readLong()\n sum(i) = a(i) + (if (i > 0) sum(i - 1) else 0)\n approximate_average(i) = ((if (i > 0) approximate_average(i - 1) else 0) + a(i).toDouble / T) / \n c\n true_average(i) = ((sum(i) - (if (i - T >= 0) sum(i - T) else 0)).toDouble / \n T)\n }\n val m = readInt()\n for (i <- 0 until m) {\n val q = readInt() - 1\n out.println(true_average(q) + \" \" + approximate_average(q) + \" \" + \n Math.abs(approximate_average(q) - true_average(q)) / true_average(q))\n }\n }\n\n\n \n \n}\n}\n\n\n"}], "negative_code": [], "src_uid": "be8d2eff2f34e72625566680ae188c49"} {"nl": {"description": "Petya has n positive integers a1,\u2009a2,\u2009...,\u2009an. His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'.Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000) \u2014 the number of Petya's numbers. Each of the following lines contains non-empty string si consisting of lowercase Latin letters from 'a' to 'j' \u2014 the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters.", "output_spec": "Determine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests.", "sample_inputs": ["3\nab\nde\naj", "5\nabcdef\nghij\nbdef\naccbd\ng", "3\naa\njj\naa"], "sample_outputs": ["47", "136542", "44"], "notes": "NoteIn the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10,\u200923,\u200914]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration.In the second example the numbers after the restoration can look like: [120468,\u20093579,\u20092468,\u200910024,\u20093]. In the second example the numbers after the restoration can look like: [11,\u200922,\u200911]. "}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.", "input_spec": "The first line of the input contains the public key of the messenger \u2014 an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009108).", "output_spec": "In the first line print \"YES\" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines \u2014 the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them. If there is no answer, print in a single line \"NO\" (without the quotes).", "sample_inputs": ["116401024\n97 1024", "284254589153928171911281811000\n1009 1000", "120\n12 1"], "sample_outputs": ["YES\n11640\n1024", "YES\n2842545891539\n28171911281811000", "NO"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next().map(_.asDigit)\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n val first = Array.ofDim[Boolean](line.length)\n line.indices.foldLeft(0) {\n case (current, index) =>\n val nCurrent = (current * 10 + line(index)) % a\n if (nCurrent == 0)\n first(index) = true\n nCurrent\n }\n val resIndex = line.indices.tail.reverse.foldLeft(-1, 0, 1) {\n case ((-1, current, l), index) =>\n val nL = (l * 10) % b\n val nCurrent = (line(index) * l + current) % b\n if (nCurrent == 0 && line(index) != 0 && first(index - 1))\n (index - 1, nCurrent, nL)\n else\n (-1, nCurrent, nL)\n case (acc, index) => acc\n }._1\n\n resIndex match {\n case -1 => println(\"NO\")\n case index =>\n println(\"YES\")\n println(line.take(index + 1).mkString)\n println(line.drop(index + 1).mkString)\n }\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val line = in.next().map(_.asDigit)\n val Array(a, b) = in.next().split(' ').map(_.toInt)\n val firstindices = line.indices.foldLeft(List.empty[Int], 0) {\n case ((result, current), index) =>\n val nCurrent = (current * 10 + line(index)) % a\n if (nCurrent == 0)\n (index :: result, nCurrent)\n else\n (result, nCurrent)\n }._1.toSet\n val lastindices = line.indices.reverse.foldLeft(List.empty[Int], 0, 1) {\n case ((result, current, l), index) =>\n val nL = (l * 10) % b\n val nCurrent = (line(index) * l + current) % b\n if (nCurrent == 0 && line(index) != 0)\n (index :: result, nCurrent, nL)\n else\n (result, nCurrent, nL)\n }._1.toSet\n\n firstindices.intersect(lastindices).headOption match {\n case None => println(\"NO\")\n case Some(index) =>\n println(\"YES\")\n println(line.take(index + 1).mkString)\n println(line.drop(index + 1).mkString)\n }\n}"}], "src_uid": "695418026140545863313f5f3cc1bf00"} {"nl": {"description": "Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor \u00abTextpad\u00bb decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!", "input_spec": "The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. ", "output_spec": "Format the given text, aligning it center. Frame the whole text with characters \u00ab*\u00bb of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.", "sample_inputs": ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"], "sample_outputs": ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"], "notes": null}, "positive_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 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"}, {"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 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}"}, {"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"}], "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"} {"nl": {"description": "Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change. ", "input_spec": "The first line contains two space-separated integers n,\u2009s (1\u2009\u2264\u2009n,\u2009s\u2009\u2264\u2009100). The i-th of the next n lines contains two integers xi, yi (1\u2009\u2264\u2009xi\u2009\u2264\u2009100;\u00a00\u2009\u2264\u2009yi\u2009<\u2009100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.", "output_spec": "Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.", "sample_inputs": ["5 10\n3 90\n12 0\n9 70\n5 50\n7 0", "5 5\n10 10\n20 20\n30 30\n40 40\n50 50"], "sample_outputs": ["50", "-1"], "notes": "NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change."}, "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.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}"}, {"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"} {"nl": {"description": "First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the \"root\" of the word \u2014 some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction \u2014 it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word \"suffix\" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by \"corners\". Thus, the set of possible suffixes for this word is {aca,\u2009ba,\u2009ca}. ", "input_spec": "The only line contains a string s (5\u2009\u2264\u2009|s|\u2009\u2264\u2009104) consisting of lowercase English letters.", "output_spec": "On the first line print integer k \u2014 a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. ", "sample_inputs": ["abacabaca", "abaca"], "sample_outputs": ["3\naca\nba\nca", "0"], "notes": "NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix."}, "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._\n\nobject _667C extends CodeForcesApp {\n override def apply(io: IO) = {\n val s = io[String]\n val ans = mutable.Set.empty[String]\n val seen = mutable.Set.empty[(Int, String)]\n\n def solve(l: Int, last: String): Unit = {\n val key = l -> last\n if (!(seen contains key)){\n def check(length: Int) = {\n val w = s.substring(l - length, l)\n if (last != w) {\n ans += w\n solve(l - length, w)\n }\n }\n if(l >= 7) check(2)\n if(l >= 8) check(3)\n val _ = seen += key\n }\n }\n solve(s.length, null)\n (io += ans.size).appendNewLine(ans.toSeq.sorted mkString \"\\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 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[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}\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": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._\n\nobject _667C extends CodeForcesApp {\n override def apply(io: IO) = {\n val s = io[String]\n val ans = mutable.Set.empty[String]\n val seen = mutable.Set.empty[Int]\n\n def solve(l: Int, last: String): Unit = if (!(seen contains l)){\n def check(length: Int) = {\n val w = s.substring(l - length, l)\n if (last != w) {\n ans += w\n solve(l - length, w)\n }\n }\n if(l >= 7) check(2)\n if(l >= 8) check(3)\n val _ = seen += l\n }\n solve(s.length, null)\n (io += ans.size).appendNewLine(ans.toSeq.sorted mkString \"\\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 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[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}\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"}], "src_uid": "dd7ccfee8c2a19bf47d65d5a62ac0071"} {"nl": {"description": "Polycarp wrote on the board a string $$$s$$$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string $$$s$$$, and he rewrote the remaining letters in any order. As a result, he got some new string $$$t$$$. You have to find it with some additional information.Suppose that the string $$$t$$$ has length $$$m$$$ and the characters are numbered from left to right from $$$1$$$ to $$$m$$$. You are given a sequence of $$$m$$$ integers: $$$b_1, b_2, \\ldots, b_m$$$, where $$$b_i$$$ is the sum of the distances $$$|i-j|$$$ from the index $$$i$$$ to all such indices $$$j$$$ that $$$t_j > t_i$$$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $$$b_i$$$, Polycarp finds all such indices $$$j$$$ that the index $$$j$$$ contains a letter that is later in the alphabet than $$$t_i$$$ and sums all the values $$$|i-j|$$$.For example, if $$$t$$$ = \"abzb\", then: since $$$t_1$$$='a', all other indices contain letters which are later in the alphabet, that is: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$; since $$$t_2$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_2=|2-3|=1$$$; since $$$t_3$$$='z', then there are no indexes $$$j$$$ such that $$$t_j>t_i$$$, thus $$$b_3=0$$$; since $$$t_4$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_4=|4-3|=1$$$. Thus, if $$$t$$$ = \"abzb\", then $$$b=[6,1,0,1]$$$.Given the string $$$s$$$ and the array $$$b$$$, find any possible string $$$t$$$ for which the following two requirements are fulfilled simultaneously: $$$t$$$ is obtained from $$$s$$$ by erasing some letters (possibly zero) and then writing the rest in any order; the array, constructed from the string $$$t$$$ according to the rules above, equals to the array $$$b$$$ specified in the input data. ", "input_spec": "The first line contains an integer $$$q$$$ ($$$1 \\le q \\le 100$$$)\u00a0\u2014 the number of test cases in the test. Then $$$q$$$ test cases follow. Each test case consists of three lines: the first line contains string $$$s$$$, which has a length from $$$1$$$ to $$$50$$$ and consists of lowercase English letters; the second line contains positive integer $$$m$$$ ($$$1 \\le m \\le |s|$$$), where $$$|s|$$$ is the length of the string $$$s$$$, and $$$m$$$ is the length of the array $$$b$$$; the third line contains the integers $$$b_1, b_2, \\dots, b_m$$$ ($$$0 \\le b_i \\le 1225$$$). It is guaranteed that in each test case an answer exists.", "output_spec": "Output $$$q$$$ lines: the $$$k$$$-th of them should contain the answer (string $$$t$$$) to the $$$k$$$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.", "sample_inputs": ["4\nabac\n3\n2 1 0\nabc\n1\n0\nabba\n3\n1 0 1\necoosdcefr\n10\n38 13 24 14 11 5 3 24 17 0"], "sample_outputs": ["aac\nb\naba\ncodeforces"], "notes": "NoteIn the first test case, such strings $$$t$$$ are suitable: \"aac', \"aab\".In the second test case, such trings $$$t$$$ are suitable: \"a\", \"b\", \"c\".In the third test case, only the string $$$t$$$ equals to \"aba\" is suitable, but the character 'b' can be from the second or third position."}, "positive_code": [{"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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite \u2014 cookies. Ichihime decides to attend the contest. Now she is solving the following problem.\u00a0You are given four positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, such that $$$a \\leq b \\leq c \\leq d$$$. Your task is to find three integers $$$x$$$, $$$y$$$, $$$z$$$, satisfying the following conditions: $$$a \\leq x \\leq b$$$. $$$b \\leq y \\leq c$$$. $$$c \\leq z \\leq d$$$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $$$x$$$, $$$y$$$, and $$$z$$$.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u00a0\u2014 the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given as four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \\leq a \\leq b \\leq c \\leq d \\leq 10^9$$$).", "output_spec": "For each test case, print three integers $$$x$$$, $$$y$$$, $$$z$$$ \u00a0\u2014 the integers you found satisfying the conditions given in the statement. It is guaranteed that the answer always exists. If there are multiple answers, print any.", "sample_inputs": ["4\n1 3 5 7\n1 5 5 7\n100000 200000 300000 400000\n1 1 977539810 977539810"], "sample_outputs": ["3 4 5\n5 5 5\n182690 214748 300999\n1 977539810 977539810"], "notes": "NoteOne of the possible solutions to the first test case:One of the possible solutions to the second test case:"}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Solution_A extends App {\n val T = StdIn.readInt()\n for (t <- 1 to T) {\n val input = StdIn.readLine().split(' ').map{_.toInt}\n println(s\"${input(1)} ${input(2)} ${input(2)}\")\n }\n}\n"}], "negative_code": [], "src_uid": "821d48c9a67d37ad7acc50d4d0d0d723"} {"nl": {"description": "A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.", "input_spec": "The first line of the input data contains numbers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950), n \u2014 amount of lines, and m \u2014 amount of columns on Bob's sheet. The following n lines contain m characters each. Character \u00ab.\u00bb stands for a non-shaded square on the sheet, and \u00ab*\u00bb \u2014 for a shaded square. It is guaranteed that Bob has shaded at least one square.", "output_spec": "Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.", "sample_inputs": ["6 7\n.......\n..***..\n..*....\n..***..\n..*....\n..***..", "3 3\n***\n*.*\n***"], "sample_outputs": ["***\n*..\n***\n*..\n***", "***\n*.*\n***"], "notes": null}, "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 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}"}, {"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 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"}], "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"} {"nl": {"description": "You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding. On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$)\u00a0\u2014 the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^{9}$$$).", "output_spec": "For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.", "sample_inputs": ["2\n2\n1"], "sample_outputs": ["2\n1"], "notes": "NoteIn the first test case, there are the following $$$2$$$ ways to fill the area: In the second test case, there is a unique way to fill the area: "}, "positive_code": [{"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": "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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$, and an integer $$$x$$$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $$$[3, 6, 9]$$$, in a single operation one can replace the last two elements by their sum, yielding an array $$$[3, 15]$$$, or replace the first two elements to get an array $$$[9, 9]$$$. Note that the size of the array decreases after each operation.The beauty of an array $$$b=[b_1, \\ldots, b_k]$$$ is defined as $$$\\sum_{i=1}^k \\left\\lceil \\frac{b_i}{x} \\right\\rceil$$$, which means that we divide each element by $$$x$$$, round it up to the nearest integer, and sum up the resulting values. For example, if $$$x = 3$$$, and the array is $$$[4, 11, 6]$$$, the beauty of the array is equal to $$$\\left\\lceil \\frac{4}{3} \\right\\rceil + \\left\\lceil \\frac{11}{3} \\right\\rceil + \\left\\lceil \\frac{6}{3} \\right\\rceil = 2 + 4 + 2 = 8$$$.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.", "input_spec": "The first input line contains a single integer $$$t$$$\u00a0\u2014 the number of test cases ($$$1 \\le t \\le 1000$$$). The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$1 \\leq x \\leq 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$), the elements of the array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case output two integers\u00a0\u2014 the minimal and the maximal possible beauty.", "sample_inputs": ["2\n3 3\n3 6 9\n3 3\n6 4 11"], "sample_outputs": ["6 6\n7 8"], "notes": "NoteIn the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements $$$4$$$ and $$$11$$$ with their sum, yielding an array $$$[6, 15]$$$, which has its beauty equal to $$$7$$$."}, "positive_code": [{"source_code": "//package bScalaAdvanced.exercises.codeForces.contest694\n\nimport scala.io.StdIn._\nimport math.ceil\n\nobject taskA extends App{\n\nval sets = readInt()\n (1 to sets).foreach(set =>{\n val x = readLine().split(\" \")(1).toDouble\n val arr = readLine.split(\" \").map(_.toDouble)\n val sumMax:Long = {\n var subSum:Long = 0\n arr.foreach(n => subSum+= ceil(n / x).toLong)\n subSum\n }\n\n val sumMin:Long = {\n var subSum:Double = 0\n arr.foreach(n => subSum += n)\n ceil(subSum/x).toLong\n }\n\n println(sumMin + \" \" + sumMax)\n })\n}\n"}], "negative_code": [{"source_code": "//package bScalaAdvanced.exercises.codeForces.contest694\n\nimport scala.io.StdIn._\nimport math.ceil\n\nobject taskA extends App{\n\nval sets = readInt()\n (1 to sets).foreach(set =>{\n val x = readLine().split(\" \")(1).toDouble\n val arr = readLine.split(\" \").map(_.toDouble)\n val sumMax:Long = {\n var subSum:Long = 0\n arr.foreach(n => subSum+= ceil(n / x).toInt)\n subSum\n }\n\n val sumMin:Long = {\n var subSum:Double = 0\n arr.foreach(n => subSum += n)\n ceil(subSum/x).toInt\n }\n\n println(sumMin + \" \" + sumMax)\n })\n}\n"}, {"source_code": "//package bScalaAdvanced.exercises.codeForces.contest694\n\nimport scala.io.StdIn._\nimport math.ceil\n\nobject taskA extends App{\n\nval sets = readInt()\n (1 to sets).foreach(set =>{\n val x = readLine().split(\" \")(1).toDouble\n val arr = readLine.split(\" \").map(_.toDouble)\n val sumMax = {\n var subSum = 0\n arr.foreach(n => subSum+= ceil(n / x).toInt)\n subSum\n }\n\n val sumMin = {\n var subSum:Double = 0\n arr.foreach(n => subSum += n)\n ceil(subSum/x).toInt\n }\n\n println(sumMin + \" \" + sumMax)\n })\n}\n"}], "src_uid": "b36d7f840abe998185a988fe8dd2ec75"} {"nl": {"description": "Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.", "input_spec": "The single line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009104).", "output_spec": "If the answer exists, print 3 distinct numbers x, y and z (1\u2009\u2264\u2009x,\u2009y,\u2009z\u2009\u2264\u2009109, x\u2009\u2260\u2009y, x\u2009\u2260\u2009z, y\u2009\u2260\u2009z). Otherwise print -1. If there are multiple answers, print any of them.", "sample_inputs": ["3", "7"], "sample_outputs": ["2 7 42", "7 8 56"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "f60ea0f2caaec16894e84ba87f90c061"} {"nl": {"description": "Let there be an array $$$b_1, b_2, \\ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \\ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \\leq i \\leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \\sum_{i = 1}^{c} \\operatorname{mex}(\\{b_{l_i}, b_{l_i + 1}, \\ldots, b_{r_i}\\}),$$$$$$ where $$$\\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \\ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.", "input_spec": "The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 30$$$)\u00a0\u2014 the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["4\n2\n1 2\n3\n2 0 1\n4\n2 0 5 1\n5\n0 1 1 0 1"], "sample_outputs": ["4\n14\n26\n48"], "notes": "NoteIn the second test case: The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \\operatorname{mex}(\\{2\\}) + \\operatorname{mex}(\\{0, 1\\}) = 2 + 0 + 2 = 4$$$. The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \\operatorname{mex}(\\{2\\}) + \\operatorname{mex}(\\{0\\}) = 2 + 0 + 1 = 3$$$ The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \\operatorname{mex}(\\{2\\}) = 1 + 0 = 1$$$. The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \\operatorname{mex}(\\{0, 1\\}) = 1 + 2 = 3$$$. The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \\operatorname{mex}(\\{0\\}) = 1 + 1 = 2$$$. The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \\operatorname{mex}(\\{1\\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \\times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times: take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$. Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \\dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \\dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \\leq n, m \\leq 500$$$)\u00a0\u2014 the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \\leq A_{ij} \\leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \\leq B_{ij} \\leq 10^{9}$$$).", "output_spec": "Print \"YES\" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and \"NO\" (without quotes) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["2 2\n1 1\n6 1\n1 6\n1 1", "2 2\n4 4\n4 5\n5 4\n4 4", "3 3\n1 2 3\n4 5 6\n7 8 9\n1 4 7\n2 5 6\n3 8 9"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \\begin{bmatrix} 1 & 2 & 3\\\\ 4 & 5 & 6\\\\ 7 & 8 & 9 \\end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \\begin{bmatrix} 1 & 4 & 7\\\\ 2 & 5 & 8\\\\ 3 & 6 & 9 \\end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \\begin{bmatrix} 1 & 4 & 7\\\\ 2 & \\textbf{5} & \\textbf{8}\\\\ 3 & \\textbf{6} & \\textbf{9} \\end{bmatrix} $$$$$$So matrix becomes$$$$$$ \\begin{bmatrix} 1 & 4 & 7\\\\ 2 & 5 & 6\\\\ 3 & 8 & 9 \\end{bmatrix} $$$$$$and it is $$$B$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "77e2ddc4684fccd1856c93c2fc6e1ce2"} {"nl": {"description": "There is a chess board of size $$$n \\times m$$$. The rows are numbered from $$$1$$$ to $$$n$$$, the columns are numbered from $$$1$$$ to $$$m$$$.Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction: Find any isolated cell on the board. If there are no such cells, print any cell on the board.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 64$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 8$$$)\u00a0\u2014 the number of rows and columns of the board.", "output_spec": "For each testcase, print two integers\u00a0\u2014 the row and the column of any isolated cell on the board. If there are no such cells, print any cell on the board.", "sample_inputs": ["3\n\n1 7\n\n8 8\n\n3 3"], "sample_outputs": ["1 7\n7 2\n2 2"], "notes": "NoteIn the first testcase, all cells are isolated. A knight can't move from any cell of the board to any other one. Thus, any cell on board is a correct answer.In the second testcase, there are no isolated cells. On a normal chess board, a knight has at least two moves from any cell. Thus, again, any cell is a correct answer.In the third testcase, only the middle cell of the board is isolated. The knight can move freely around the border of the board, but can't escape the middle."}, "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){\r\n if ( ts < t ){\r\n def solve() = {\r\n var Array(n, m) = io.StdIn.readLine().split(\" \").map(_.toInt);\r\n if ( n < 2 || m < 2 )\r\n Array(1, 1)\r\n else\r\n if ( n <= 3 && m <= 3 )\r\n Array(2, 2)\r\n else\r\n Array(1, 1)\r\n }\r\n var ans = solve()\r\n println( ans(0)+\" \"+ans(1) )\r\n loopts(ts+1)\r\n }\r\n }\r\n loopts(0)\r\n }\r\n \r\n}"}], "negative_code": [], "src_uid": "e6753e3f71ff13cebc1aaf04d3d2106b"} {"nl": {"description": "You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \\leq i < n$$$) such that $$$h_i \\leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.", "input_spec": "The first line will contain a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 2 \\cdot 10^5$$$) \u2014 the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\\ldots,h_n$$$ ($$$1 \\leq h_i \\leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output $$$n$$$ integers \u2014 the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.", "sample_inputs": ["2\n4\n4 2 1 2\n2\n3 1"], "sample_outputs": ["2 4 1 2 \n1 3"], "notes": "NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal."}, "positive_code": [{"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"}, {"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": "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"}], "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"} {"nl": {"description": "$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$, $$$a_i \\neq a_j$$$ for $$$i \\neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\leq b_i \\leq 10^9$$$, $$$b_i \\neq b_j$$$ for $$$i \\neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print a string of length $$$n$$$. $$$i$$$-th character should be \"1\" if the $$$i$$$-th player can win the tournament, or \"0\" otherwise.", "sample_inputs": ["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"], "sample_outputs": ["0001\n1111\n1"], "notes": "NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament."}, "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, val p: 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 val arr = new Array[pair](n)\n val a = new Array[Int](n)\n val mx = new Array[Int](n+1)\n val ans = new Array[Boolean](n+1)\n for (i <- 0 until n)\n a(i) = readInt()\n for (i <- 0 until n)\n arr(i) = pair(readInt(), a(i), i+1)\n quickSort(arr)\n for (i <- (0 until n).reverse) {\n mx(i) = max(mx(i+1), arr(i).b)\n }\n var po = 0\n var best = 0\n while (po < n && po <= best) {\n ans(arr(po).p) = true\n best = max(best, bs(po, n, arr(po).b).toInt)\n po += 1\n }\n for (i <- 1 to n) {\n if(ans(i))\n writer.print(\"1\")\n else\n writer.print(\"0\")\n }\n writer.println()\n def check(kk: Long, num: Long): Boolean = {\n if (num < mx(kk.toInt))\n return true\n return false\n }\n def bs(st:Long, en:Long, num:Long): Long = {\n if (en - st <= 1L) {\n if (check(en, num))\n return en\n else\n return st\n }\n val mid = (st + en) / 2L\n if (check(mid, num))\n return bs(mid, en, num)\n else\n return bs(st, mid, num)\n }\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "f9cf1a6971a7003078b63195198e5a51"} {"nl": {"description": "Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.", "input_spec": "The first line contains two integers n and d (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009109) \u2014 the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u2009104) \u2014 the size of one low quality photo and of one high quality photo, correspondingly. Next n lines describe the clients. The i-th line contains two integers xi and yi (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009105) \u2014 the number of low quality photos and high quality photos the i-th client wants, correspondingly. All numbers on all lines are separated by single spaces. ", "output_spec": "On the first line print the answer to the problem \u2014 the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.", "sample_inputs": ["3 10\n2 3\n1 4\n2 1\n1 0", "3 6\n6 6\n1 1\n1 0\n1 0"], "sample_outputs": ["2\n3 2", "1\n2"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "The length of the longest common prefix of two strings $$$s = s_1 s_2 \\ldots s_n$$$ and $$$t = t_1 t_2 \\ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \\le k \\le min(n,m)$$$) such that $$$s_1 s_2 \\ldots s_k$$$ equals $$$t_1 t_2 \\ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \\dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \\le i \\le n$$$) she calculated $$$a_i$$$\u00a0\u2014 the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \\dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \\dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. ", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 50$$$)\u00a0\u2014 the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.", "output_spec": "For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \\le |s_i| \\le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints.", "sample_inputs": ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"], "sample_outputs": ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"], "notes": "NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\\color{red}{a}eren$$$ and $$$\\color{red}{a}ri$$$ $$$\\rightarrow 1$$$ Between $$$\\color{red}{ar}i$$$ and $$$\\color{red}{ar}ousal$$$ $$$\\rightarrow 2$$$ Between $$$\\color{red}{arou}sal$$$ and $$$\\color{red}{arou}nd$$$ $$$\\rightarrow 4$$$ Between $$$\\color{red}{ar}ound$$$ and $$$\\color{red}{ar}i$$$ $$$\\rightarrow 2$$$ "}, "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 val intInputs = in.line().split(\" \").map(_.toInt).toList\n val temN = intInputs.head :: intInputs\n\n var lastString = \"\"\n temN.indices\n .foreach(f = index => {\n if (index == 0) {\n lastString = lastString + \"m\" * 100\n } else {\n val copy = temN(index)\n val fromLast = if (copy == 0) \"\" else lastString.substring(0, copy)\n\n val char = if (fromLast.isEmpty) {\n if (lastString(0) == 'm') \"n\" else \"m\"\n } else {\n val in = fromLast.length\n if (lastString(in) == 'm') \"n\" else \"m\"\n }\n\n lastString = fromLast + char * (100 - copy)\n }\n println(lastString)\n })\n\n /*\n var lastChar1 = true\n var char = \"a\"\n temN.indices\n .foreach(f = index => {\n val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)\n if (temN(index) == 0) {\n if (lastChar1) {\n lastChar1 = false\n char = \"c\"\n } else {\n lastChar1 = true\n char = \"a\"\n }\n }\n println(if (t == 0) char else char * t)\n })*/\n// println(\"-----------\")\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": "\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 intInputs = in.line().split(\" \").map(_.toInt).toList\n val temN = intInputs.head :: intInputs\n\n val string1 = \"c\"\n (0.until(temN.length))\n .foreach(f = index => {\n val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)\n val s = if (t == 0 && index % 2 == 0) \"c\" else if (t == 0 && index % 2 == 1) \"b\" else \"a\" * t\n println(s)\n })\n// println(\"-----------\")\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": "\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 intInputs = in.line().split(\" \").map(_.toInt).toList\n val temN = intInputs.head :: intInputs\n\n val string1 = \"c\"\n (0.until(temN.length))\n .foreach(f = index => {\n val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)\n val s = if (t == 0 && index % 2 == 0) \"c\" else if (t == 0 && index % 2 == 1) \"a\" else \"a\" * t\n println(s)\n })\n// println(\"-----------\")\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": "\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 intInputs = in.line().split(\" \").map(_.toInt).toList\n val temN = intInputs.head :: intInputs\n\n var lastString = \"\"\n temN.indices\n .foreach(f = index => {\n if (index == 0) {\n lastString = lastString + \"m\" * 100\n } else {\n val copy = temN(index)\n val fromLast = if (copy == 0) \"\" else lastString.substring(0, copy)\n\n val char = if (fromLast.isEmpty) {\n if (lastString(0) == 'm') \"n\" else \"m\"\n } else {\n val in = math.max(fromLast.length - 1, 0)\n if (fromLast(in) == 'm') \"n\" else \"m\"\n }\n\n lastString = fromLast + char * (100 - copy)\n }\n println(lastString)\n })\n\n /*\n var lastChar1 = true\n var char = \"a\"\n temN.indices\n .foreach(f = index => {\n val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)\n if (temN(index) == 0) {\n if (lastChar1) {\n lastChar1 = false\n char = \"c\"\n } else {\n lastChar1 = true\n char = \"a\"\n }\n }\n println(if (t == 0) char else char * t)\n })*/\n// println(\"-----------\")\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": "\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 intInputs = in.line().split(\" \").map(_.toInt).toList\n val temN = intInputs.head :: intInputs\n\n var lastChar1 = true\n var char = \"a\"\n temN.indices\n .foreach(f = index => {\n val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)\n if (temN(index) == 0) {\n if (lastChar1) {\n lastChar1 = false\n char = \"c\"\n } else {\n lastChar1 = true\n char = \"a\"\n }\n }\n println(if (t == 0) char else char * t)\n })\n// println(\"-----------\")\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": "6983823efdc512f8759203460cd6bb4c"} {"nl": {"description": "A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, \"abcba\", \"a\", and \"abba\" are palindromes, while \"abab\" and \"xy\" are not.A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, \"abc\", \"ab\", and \"c\" are substrings of the string \"abc\", while \"ac\" and \"d\" are not.Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string \"aaa\" is $$$6$$$ because all its substrings are palindromes, and the palindromic count of the string \"abc\" is $$$3$$$ because only its substrings of length $$$1$$$ are palindromes.You are given a string $$$s$$$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$)\u00a0\u2014 the length of string $$$s$$$. The second line contains string $$$s$$$ that consists of exactly $$$n$$$ lowercase characters of Latin alphabet.", "output_spec": "Print string $$$t$$$, which consists of the same set of characters (and each characters appears exactly the same number of times) as string $$$s$$$. Moreover, $$$t$$$ should have the maximum possible value of palindromic count among all such strings strings. If there are multiple such strings, print any of them.", "sample_inputs": ["5\noolol", "16\ngagadbcgghhchbdf"], "sample_outputs": ["ololo", "abccbaghghghgdfd"], "notes": "NoteIn the first example, string \"ololo\" has $$$9$$$ palindromic substrings: \"o\", \"l\", \"o\", \"l\", \"o\", \"olo\", \"lol\", \"olo\", \"ololo\". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.In the second example, the palindromic count of string \"abccbaghghghgdfd\" is $$$29$$$."}, "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 val C = Array.ofDim[Int](26)\n rep(N) { i =>\n C(S(i) - 'a') += 1\n }\n\n C.zipWithIndex.sortBy(_._1) foreach { case (cnt1, a1) =>\n rep(cnt1) { i =>\n out.print(('a' + a1).toChar)\n }\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}"}], "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 C = Array.ofDim[Int](26)\n rep(N) { i =>\n C(S(i) - 'a') += 1\n }\n\n C.zipWithIndex.sortBy(_._1).reverse.grouped(2) foreach { g =>\n if (g.length > 1) {\n val (cnt1, a1) = g(0)\n val (cnt2, a2) = g(1)\n\n // a1a1a1a2a1a2a1\n rep(cnt1 - cnt2) { i =>\n out.print(('a' + a1).toChar)\n }\n rep(cnt2) { i =>\n out.print(('a' + a2).toChar)\n out.print(('a' + a1).toChar)\n }\n } else {\n val (cnt1, a1) = g(0)\n rep(cnt1) { i =>\n out.print(('a' + a1).toChar)\n }\n }\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": "8616ede6867c8aacde986a123ec8a921"} {"nl": {"description": "The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.", "input_spec": "The first line contains an integer n, which is the number of people in the crew (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Then follow n lines. The i-th of those lines contains two words \u2014 the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.", "output_spec": "Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.", "sample_inputs": ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"], "sample_outputs": ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"], "notes": null}, "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(\" \")).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}"}, {"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"} {"nl": {"description": "Lena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of $$$n$$$ rows and $$$m$$$ columns, and each cell is either black or white. The coordinates $$$(i,j)$$$ denote the cell which belongs to the $$$i$$$-th row and $$$j$$$-th column for every $$$1\\leq i \\leq n$$$ and $$$1\\leq j \\leq m$$$. To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.More formally, let there be $$$k \\ge 1$$$ black cells in the matrix with coordinates $$$(x_i,y_i)$$$ for every $$$1\\leq i \\leq k$$$. Lena should choose a cell $$$(a,b)$$$ that minimizes $$$$$$\\max_{i=1}^{k}(|a-x_i|+|b-y_i|).$$$$$$As Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose? ", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\\leq t\\leq 10\\,000$$$)\u00a0\u2014 the number of test cases. This is followed by the test cases description. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2\\leq n,m \\leq 1000$$$) \u00a0\u2014 the dimensions of the matrix. The following $$$n$$$ lines contain $$$m$$$ characters each, each character is either 'W' or 'B'. The $$$j$$$-th character in the $$$i$$$-th of these lines is 'W' if the cell $$$(i,j)$$$ is white, and 'B' if the cell $$$(i,j)$$$ is black. It is guaranteed that at least one black cell exists. It is guaranteed that the sum of $$$n\\cdot m$$$ does not exceed $$$10^6$$$.", "output_spec": "For each test case, output the optimal cell $$$(a,b)$$$ to choose. If multiple answers exist, output any.", "sample_inputs": ["5\n3 2\nBW\nWW\nWB\n3 3\nWWB\nWBW\nBWW\n2 3\nBBB\nBBB\n5 5\nBWBWB\nWBWBW\nBWBWB\nWBWBW\nBWBWB\n9 9\nWWWWWWWWW\nWWWWWWWWW\nBWWWWWWWW\nWWWWWWWWW\nWWWWBWWWW\nWWWWWWWWW\nWWWWWWWWW\nWWWWWWWWW\nWWWWWWWWB"], "sample_outputs": ["2 1\n2 2\n1 2\n3 3\n6 5"], "notes": "NoteIn the first test case the two black cells have coordinates $$$(1,1)$$$ and $$$(3,2)$$$. The four optimal cells are $$$(1,2)$$$, $$$(2,1)$$$, $$$(2,2)$$$ and $$$(3,1)$$$. It can be shown that no other cell minimizes the maximum Manhattan distance to every black cell.In the second test case it is optimal to choose the black cell $$$(2,2)$$$ with maximum Manhattan distance being $$$2$$$."}, "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n var AA = List[Int]()\r\n var AAA = List[Int]()\r\n if ((s1+s2) % 2 == 0) {\r\n AA ::= (s1 + s2) /2\r\n }\r\n else {\r\n AA ::= (s1 + s2 + 1) / 2\r\n AA ::= (s1 + s2 - 1) / 2\r\n }\r\n if ((s3+s4) % 2 == 0) {\r\n AAA ::= (s3 + s4) /2\r\n }\r\n else {\r\n AAA ::= (s3 + s4 + 1) / 2\r\n AAA ::= (s3 + s4 - 1) / 2\r\n }\r\n var qqq = 0\r\n for {h <- AA;\r\n f <- AAA\r\n if (h+f) % 2 ==0}{\r\n qqq+=1\r\n aa = (h + f) / 2\r\n bb = (h - f) / 2\r\n }\r\n if (qqq == 0) {\r\n if (s2 - s1 > s4 - s3) {\r\n aa = (AA.last + AAA.last+1) / 2\r\n bb = (AA.last - AAA.last-1) / 2\r\n }\r\n else {\r\n aa = (AA.last + AAA.last+1) / 2\r\n bb = (AA.last - AAA.last+1) / 2\r\n }\r\n }\r\n aa +=1\r\n bb +=1\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n var AA = List[Int]()\r\n var AAA = List[Int]()\r\n if ((s1+s2) % 2 == 0) {\r\n AA ::= (s1 + s2) /2\r\n }\r\n else {\r\n AA ::= (s1 + s2 + 1) / 2\r\n AA ::= (s1 + s2 - 1) / 2\r\n }\r\n if ((s3+s4) % 2 == 0) {\r\n AAA ::= (s3 + s4) /2\r\n }\r\n else {\r\n AAA ::= (s3 + s4 + 1) / 2\r\n AAA ::= (s3 + s4 - 1) / 2\r\n }\r\n var qqq = 0\r\n for {h <- AA;\r\n f <- AAA\r\n if (h+f) % 2 ==0}{\r\n qqq+=1\r\n aa = (h + f) / 2\r\n bb = (h - f) / 2\r\n }\r\n if (qqq == 0) {\r\n if (s2 - s1 > s4 - s3) {\r\n aa = (AA.last + AAA.last+1) / 2\r\n bb = (AA.last - AAA.last+1) / 2\r\n }\r\n }\r\n aa +=1\r\n bb +=1\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins: Long = 100000000\r\n for {o <- scala.math.max(0, -10 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 10);\r\n p <- scala.math.max(-m+1,-10 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +10)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o\r\n da = p\r\n }\r\n }\r\n sa = sa+2\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins = 1000000\r\n for {o <- scala.math.max(0, -10 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 10);\r\n p <- scala.math.max(-m+1,-10 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +10)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o\r\n da = p\r\n }\r\n }\r\n sa = sa+2\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins = 100000000\r\n for {o <- scala.math.max(0, -10 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 10);\r\n p <- scala.math.max(-m+1,-10 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +10)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o\r\n da = p\r\n }\r\n }\r\n sa = sa+2\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins = 100000000\r\n for {o <- scala.math.max(0, -1 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 1);\r\n p <- scala.math.max(-m+1,-1 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +1)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o\r\n da = p\r\n }\r\n }\r\n sa = sa+2\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins = 100000000\r\n for {o <- scala.math.max(0, -1 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 1);\r\n p <- scala.math.max(-m+1,-1 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +1)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o+2\r\n da = p\r\n }\r\n }\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins = 100000000\r\n for {o <- scala.math.max(0, -5 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 5);\r\n p <- scala.math.max(-m+1,-5 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +5)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o+2\r\n da = p\r\n }\r\n }\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\r\nimport scala.math.abs\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var sa = 0\r\n var da = 0\r\n var aa = 0\r\n var bb = 0\r\n var mins = 10000000\r\n for {o <- scala.math.max(0, -3 + (s1+s2)/2) to scala.math.min(m+n-2,(s1+s2)/2 + 3);\r\n p <- scala.math.max(-m+1,-3 + (s3+s4/2)) to scala.math.min(n-1, (s3+s4)/2 +3)\r\n if (o+p) % 2 == 0} {\r\n if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {\r\n mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))\r\n sa = o+2\r\n da = p\r\n }\r\n }\r\n aa = (sa+da) / 2\r\n bb = (sa - da) / 2\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n if ((((s2+s1 + 4) / 2) - ((s3 + s4) / 2) ) % 2 !=0 ) {\r\n if ((s2+s1+4) % 2 == 1) {\r\n aa = (((s2+s1+4)/2) + 1 + ((s3 + s4) / 2)) / 2\r\n bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2\r\n }\r\n else if (((s3+s4) % 2 == 1) && (s3+s4 >= 0)) {\r\n aa = (((s2+s1+4)/2) + 1 + ((s3 + s4) / 2)) / 2\r\n bb = (((s2+s1+4)/2) - 1 - ((s3 + s4) / 2)) / 2\r\n }\r\n else if (((s3+s4) % 2 == 1) && (s3+s4 < 0)) {\r\n aa = (((s2+s1+4)/2) - 1 + ((s3 + s4) / 2)) / 2\r\n bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2\r\n }\r\n else if (s2 - s1 > s4 - s3){\r\n aa = (((s2+s1+4)/2) - 1 + ((s3 + s4) / 2)) / 2\r\n bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2\r\n }\r\n else if (s2 - s1 > s4 - s3){\r\n aa = (((s2+s1+4)/2) + 1 + ((s3 + s4) / 2)) / 2\r\n bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2\r\n }\r\n }\r\n else {\r\n aa = (((s2+s1+4)/2) + ((s3 + s4) / 2)) / 2\r\n bb = (((s2+s1+4)/2) - ((s3 + s4) / 2)) / 2\r\n }\r\n output.println(aa.toString+\" \"+ bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n if (((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {\r\n if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if ((s1+s2+4) % 2 == 1) {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n else {\r\n aa = (1*scala.math.signum(s3+s4) + ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (-1*scala.math.signum(s3+s4) + ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n\r\n }\r\n }\r\n else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if (s2 -s1 > s4-s3) {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1*scala.math.signum(s3+s4) ) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1*scala.math.signum(s3+s4) ) / 2\r\n }\r\n else {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2\r\n }\r\n }\r\n else {\r\n aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n output.println(aa.toString+\" \" + bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n if (((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {\r\n if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if ((s1+s2+4) % 2 == 1) {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n else {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n\r\n }\r\n }\r\n else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if (s2 -s1 > s4-s3) {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2\r\n }\r\n else {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2\r\n }\r\n }\r\n else {\r\n aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n output.println(aa.toString+\" \" + bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n \r\n var aa = 0\r\n var bb = 0\r\n if ( ((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {\r\n if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if ((s1+s2+4) % 2 == 1) {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n else {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n\r\n }\r\n }\r\n else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) / 2 != 0) {\r\n if (s2 -s1 > s4-s3) {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2\r\n }\r\n else {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n output.println(aa.toString+\" \" + bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n if ( ((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {\r\n if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if ((s1+s2+4) % 2 == 1) {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n else {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n\r\n }\r\n }\r\n else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) / 2 != 0) {\r\n if (s2 -s1 > s4-s3) {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2\r\n }\r\n else {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n output.println(aa.toString+\" \" + bb.toString)\r\n }\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n def scan1(s: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {\r\n if (A(j)(s-j) == \"B\"(0))\r\n i = false\r\n }\r\n i\r\n }\r\n def scan2(d: Int, A: Array[String]): Boolean = {\r\n var i= true\r\n for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {\r\n if (A(j)(j-d) == \"B\"(0))\r\n i = false\r\n }\r\n i\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 A = ListBuffer.empty[String]\r\n for (j <- 1 to n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n A+= tokenizer.nextToken()\r\n }\r\n var s1 = 0\r\n val B = A.toArray\r\n while (scan1(s1,B)) {\r\n s1+=1\r\n }\r\n var s2 = n+m-2\r\n while (scan1(s2,B)) {\r\n s2-=1\r\n }\r\n var s3 = -m+1\r\n while (scan2(s3,B)) {\r\n s3+=1\r\n }\r\n\r\n var s4 = n-1\r\n while (scan2(s4,B)) {\r\n s4-=1\r\n }\r\n var aa = 0\r\n var bb = 0\r\n if ( ((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {\r\n if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if ((s1+s2+4) % 2 == 1) {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n else {\r\n aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n\r\n }\r\n }\r\n else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {\r\n if (s2 -s1 > s4-s3) {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2\r\n }\r\n else {\r\n aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2\r\n bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2\r\n }\r\n }\r\n else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2\r\n bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2\r\n }\r\n output.println(aa.toString+\" \" + bb.toString)\r\n }\r\n }\r\n}"}], "src_uid": "cffcbdd58cc02f96d70d0819fef5131d"} {"nl": {"description": "Permutation $$$p$$$ is a sequence of integers $$$p=[p_1, p_2, \\dots, p_n]$$$, consisting of $$$n$$$ distinct (unique) positive integers between $$$1$$$ and $$$n$$$, inclusive. For example, the following sequences are permutations: $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. The following sequences are not permutations: $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $$$p$$$ of length $$$n$$$. You don't know this permutation, you only know the array $$$q$$$ of prefix maximums of this permutation. Formally: $$$q_1=p_1$$$, $$$q_2=\\max(p_1, p_2)$$$, $$$q_3=\\max(p_1, p_2,p_3)$$$, ... $$$q_n=\\max(p_1, p_2,\\dots,p_n)$$$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $$$q$$$ for this permutation is equal to the given array).", "input_spec": "The first line contains integer number $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ $$$(1 \\le n \\le 10^{5})$$$\u00a0\u2014 the number of elements in the secret code permutation $$$p$$$. The second line of a test case contains $$$n$$$ integers $$$q_1, q_2, \\dots, q_n$$$ $$$(1 \\le q_i \\le n)$$$\u00a0\u2014 elements of the array $$$q$$$ for secret permutation. It is guaranteed that $$$q_i \\le q_{i+1}$$$ for all $$$i$$$ ($$$1 \\le i < n$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print: If it's impossible to find such a permutation $$$p$$$, print \"-1\" (without quotes). Otherwise, print $$$n$$$ distinct integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$). If there are multiple possible answers, you can print any of them. ", "sample_inputs": ["4\n5\n1 3 4 5 5\n4\n1 1 3 4\n2\n2 2\n1\n1"], "sample_outputs": ["1 3 4 5 2 \n-1\n2 1 \n1"], "notes": "NoteIn the first test case of the example answer $$$[1,3,4,5,2]$$$ is the only possible answer: $$$q_{1} = p_{1} = 1$$$; $$$q_{2} = \\max(p_{1}, p_{2}) = 3$$$; $$$q_{3} = \\max(p_{1}, p_{2}, p_{3}) = 4$$$; $$$q_{4} = \\max(p_{1}, p_{2}, p_{3}, p_{4}) = 5$$$; $$$q_{5} = \\max(p_{1}, p_{2}, p_{3}, p_{4}, p_{5}) = 5$$$. It can be proved that there are no answers for the second test case of the example."}, "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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "negative_code": [], "src_uid": "81912dccb339d675e09df40919f9f6fe"} {"nl": {"description": "One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $$$n$$$ machines, and the power of the $$$i$$$-th machine is $$$a_i$$$. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $$$x$$$, then choose one machine and reduce the power of its machine by $$$x$$$ times, and at the same time increase the power of one another machine by $$$x$$$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $$$i$$$ and $$$j$$$, and one integer $$$x$$$ such that $$$x$$$ is a divisor of $$$a_i$$$, and change powers as following: $$$a_i = \\frac{a_i}{x}$$$, $$$a_j = a_j \\cdot x$$$Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 5 \\cdot 10^4$$$)\u00a0\u2014 the number of machines. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 100$$$)\u00a0\u2014 the powers of the machines.", "output_spec": "Print one integer\u00a0\u2014 minimum total power.", "sample_inputs": ["5\n1 2 3 4 5", "4\n4 2 4 4", "5\n2 4 2 3 7"], "sample_outputs": ["14", "14", "18"], "notes": "NoteIn the first example, the farmer can reduce the power of the $$$4$$$-th machine by $$$2$$$ times, and increase the power of the $$$1$$$-st machine by $$$2$$$ times, then the powers will be: $$$[2, 2, 3, 2, 5]$$$.In the second example, the farmer can reduce the power of the $$$3$$$-rd machine by $$$2$$$ times, and increase the power of the $$$2$$$-nd machine by $$$2$$$ times. At the same time, the farmer can leave is be as it is and the total power won't change.In the third example, it is optimal to leave it be as it is."}, "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(\u221ax)\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"}, {"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}"}], "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"} {"nl": {"description": "This is the hard version of the problem. The only difference is that in this version $$$n \\leq 200000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 200000$$$) \u2014 the number of potions. The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$) which represent the change in health after drinking that potion.", "output_spec": "Output a single integer, the maximum number of potions you can drink without your health becoming negative.", "sample_inputs": ["6\n4 -4 1 -3 1 -3"], "sample_outputs": ["5"], "notes": "NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point"}, "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": "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"}], "negative_code": [], "src_uid": "b4a4448af5b61fe5a8467a8d0e12fba8"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print the answer to it \u2014 YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["3\n6 9\n1 1\n1 2"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero: choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$; choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$. "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 \u306b\u3059\u308b\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}"}, {"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}"}], "negative_code": [], "src_uid": "0a720a0b06314fde783866b47f35af81"} {"nl": {"description": "A company of $$$n$$$ friends wants to order exactly two pizzas. It is known that in total there are $$$9$$$ pizza ingredients in nature, which are denoted by integers from $$$1$$$ to $$$9$$$.Each of the $$$n$$$ friends has one or more favorite ingredients: the $$$i$$$-th of friends has the number of favorite ingredients equal to $$$f_i$$$ ($$$1 \\le f_i \\le 9$$$) and your favorite ingredients form the sequence $$$b_{i1}, b_{i2}, \\dots, b_{if_i}$$$ ($$$1 \\le b_{it} \\le 9$$$).The website of CodePizza restaurant has exactly $$$m$$$ ($$$m \\ge 2$$$) pizzas. Each pizza is characterized by a set of $$$r_j$$$ ingredients $$$a_{j1}, a_{j2}, \\dots, a_{jr_j}$$$ ($$$1 \\le r_j \\le 9$$$, $$$1 \\le a_{jt} \\le 9$$$) , which are included in it, and its price is $$$c_j$$$.Help your friends choose exactly two pizzas in such a way as to please the maximum number of people in the company. It is known that a person is pleased with the choice if each of his/her favorite ingredients is in at least one ordered pizza. If there are several ways to choose two pizzas so as to please the maximum number of friends, then choose the one that minimizes the total price of two pizzas.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^5, 2 \\le m \\le 10^5$$$) \u2014 the number of friends in the company and the number of pizzas, respectively. Next, the $$$n$$$ lines contain descriptions of favorite ingredients of the friends: the $$$i$$$-th of them contains the number of favorite ingredients $$$f_i$$$ ($$$1 \\le f_i \\le 9$$$) and a sequence of distinct integers $$$b_{i1}, b_{i2}, \\dots, b_{if_i}$$$ ($$$1 \\le b_{it} \\le 9$$$). Next, the $$$m$$$ lines contain pizza descriptions: the $$$j$$$-th of them contains the integer price of the pizza $$$c_j$$$ ($$$1 \\le c_j \\le 10^9$$$), the number of ingredients $$$r_j$$$ ($$$1 \\le r_j \\le 9$$$) and the ingredients themselves as a sequence of distinct integers $$$a_{j1}, a_{j2}, \\dots, a_{jr_j}$$$ ($$$1 \\le a_{jt} \\le 9$$$).", "output_spec": "Output two integers $$$j_1$$$ and $$$j_2$$$ ($$$1 \\le j_1,j_2 \\le m$$$, $$$j_1 \\ne j_2$$$) denoting the indices of two pizzas in the required set. If there are several solutions, output any of them. Pizza indices can be printed in any order.", "sample_inputs": ["3 4\n2 6 7\n4 2 3 9 5\n3 2 3 9\n100 1 7\n400 3 3 2 5\n100 2 9 2\n500 3 2 9 5", "4 3\n1 1\n1 2\n1 3\n1 4\n10 4 1 2 3 4\n20 4 1 2 3 4\n30 4 1 2 3 4", "1 5\n9 9 8 7 6 5 4 3 2 1\n3 4 1 2 3 4\n1 4 5 6 7 8\n4 4 1 3 5 7\n1 4 2 4 6 8\n5 4 1 9 2 8"], "sample_outputs": ["2 3", "1 2", "2 4"], "notes": null}, "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 case class Restaurant(i: Int, cost: Int)\n\n // toInt\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val F = Array.ofDim[Int](N)\n REP(N) { i =>\n val f = ni()\n var fav = 0\n REP(f) { _ =>\n val k = ni() - 1\n fav |= 1 << k\n }\n F(i) = fav\n }\n \n val R = Array.ofDim[Restaurant](1 << 9, 2)\n REP(M) { i =>\n val c, r = ni()\n var offer = 0\n REP(r) { _ =>\n val k = ni() - 1\n offer |= 1 << k\n }\n if (R(offer)(0) == null) {\n R(offer)(0) = Restaurant(i, c)\n } else if (R(offer)(1) == null || R(offer)(1).cost > c) {\n R(offer)(1) = Restaurant(i, c)\n if (R(offer)(0).cost > R(offer)(1).cost) {\n val t = R(offer)(0)\n R(offer)(0) = R(offer)(1)\n R(offer)(1) = t\n }\n }\n }\n\n val C = Array.ofDim[Int](1 << 9)\n REP(1 << 9) { fav =>\n REP(N) { i =>\n if ((F(i) & fav) == F(i)) { // F(i) \u2208 fav\n C(fav) += 1\n }\n }\n }\n\n var mxFriends = 0\n var minCost = 2e9.toInt + 1\n var ans = (-1, -1)\n REP(1 << 9) { o1 =>\n REP(1 << 9) { o2 =>\n val (r1, r2) = if (o1 != o2) {\n (R(o1)(0), R(o2)(0))\n } else {\n (R(o1)(0), R(o2)(1))\n }\n if (r1 != null && r2 != null) {\n if (C(o1 | o2) > mxFriends) {\n mxFriends = C(o1 | o2)\n minCost = r1.cost + r2.cost\n ans = (r1.i, r2.i)\n }\n if (C(o1 | o2) == mxFriends && r1.cost + r2.cost < minCost) {\n minCost = r1.cost + r2.cost\n ans = (r1.i, r2.i)\n }\n }\n }\n }\n out.println(s\"${ans._1 + 1} ${ans._2 + 1}\")\n }\n}"}], "negative_code": [], "src_uid": "cc49df31741e921cd5c2db0a900a6bb5"} {"nl": {"description": "You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way. Initially, you place block $$$1$$$ at $$$(0, 0)$$$. For $$$2 \\le i \\le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \\ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently: Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\le c_i \\le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output $$$n$$$ integers. The $$$r$$$-th of them should be the maximum size of an tower of color $$$r$$$ you can form by following the given rules. If you cannot form any tower of color $$$r$$$, the $$$r$$$-th integer should be $$$0$$$.", "sample_inputs": ["6\n\n7\n\n1 2 3 1 2 3 1\n\n6\n\n4 2 2 2 4 4\n\n1\n\n1\n\n5\n\n5 4 5 3 5\n\n6\n\n3 3 3 1 3 3\n\n8\n\n1 2 3 4 4 3 2 1"], "sample_outputs": ["3 2 2 0 0 0 0 \n0 3 0 2 0 0 \n1 \n0 0 1 1 1 \n1 0 4 0 0 0 \n2 2 2 2 0 0 0 0"], "notes": "NoteIn the first test case, one of the possible ways to form a tower of color $$$1$$$ and size $$$3$$$ is: place block $$$1$$$ at position $$$(0, 0)$$$; place block $$$2$$$ to the right of block $$$1$$$, at position $$$(1, 0)$$$; place block $$$3$$$ above block $$$2$$$, at position $$$(1, 1)$$$; place block $$$4$$$ to the left of block $$$3$$$, at position $$$(0, 1)$$$; place block $$$5$$$ to the left of block $$$4$$$, at position $$$(-1, 1)$$$; place block $$$6$$$ above block $$$5$$$, at position $$$(-1, 2)$$$; place block $$$7$$$ to the right of block $$$6$$$, at position $$$(0, 2)$$$. The blocks at positions $$$(0, 0)$$$, $$$(0, 1)$$$, and $$$(0, 2)$$$ all have color $$$1$$$, forming an tower of size $$$3$$$.In the second test case, note that the following placement is not valid, since you are not allowed to place block $$$6$$$ under block $$$5$$$: It can be shown that it is impossible to form a tower of color $$$4$$$ and size $$$3$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to $$$1$$$. More formally, a sequence $$$s_1, s_2, \\ldots, s_{n}$$$ is beautiful if $$$|s_i - s_{i+1}| = 1$$$ for all $$$1 \\leq i \\leq n - 1$$$.Trans has $$$a$$$ numbers $$$0$$$, $$$b$$$ numbers $$$1$$$, $$$c$$$ numbers $$$2$$$ and $$$d$$$ numbers $$$3$$$. He wants to construct a beautiful sequence using all of these $$$a + b + c + d$$$ numbers.However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?", "input_spec": "The only input line contains four non-negative integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$0 < a+b+c+d \\leq 10^5$$$).", "output_spec": "If it is impossible to construct a beautiful sequence satisfying the above constraints, print \"NO\" (without quotes) in one line. Otherwise, print \"YES\" (without quotes) in the first line. Then in the second line print $$$a + b + c + d$$$ integers, separated by spaces\u00a0\u2014 a beautiful sequence. There should be $$$a$$$ numbers equal to $$$0$$$, $$$b$$$ numbers equal to $$$1$$$, $$$c$$$ numbers equal to $$$2$$$ and $$$d$$$ numbers equal to $$$3$$$. If there are multiple answers, you can print any of them.", "sample_inputs": ["2 2 2 1", "1 2 3 4", "2 2 2 3"], "sample_outputs": ["YES\n0 1 0 1 2 3 2", "NO", "NO"], "notes": "NoteIn the first test, it is easy to see, that the sequence is beautiful because the difference between any two consecutive numbers is equal to $$$1$$$. Also, there are exactly two numbers, equal to $$$0$$$, $$$1$$$, $$$2$$$ and exactly one number, equal to $$$3$$$.It can be proved, that it is impossible to construct beautiful sequences in the second and third tests."}, "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 import scala.collection.mutable.ArrayBuffer\n case class Edge(u: Int, id: Int)\n type G = Array[ArrayBuffer[Edge]]\n\nobject EulerianTrail {\n def makeUDPath(g: G, m: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n var odds = 0\n var s = g.indexWhere(_.nonEmpty)\n REP(n) { v =>\n val odd = g(v).length % 2 == 1\n if (odd) {\n s = v\n odds += 1\n }\n }\n\n (s, odds == 0 || odds == 2)\n }\n }\n\n def makeDPath(g: G, m: Int, s0: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n\n var s = ArrayBuffer[Int]()\n val in = Array.ofDim[Int](n)\n REP(n) { v =>\n REP(g(v).length) { i =>\n val u = g(v)(i).u\n in(u) += 1\n }\n }\n\n var plus, minus = 0\n var ok = true\n REP(n) { v =>\n // in - out\n if (in(v) == g(v).length + 1) {\n plus += 1\n } else if (in(v) + 1 == g(v).length) {\n minus += 1\n s += v // \u53ce\u652f\u30de\u30a4\u30ca\u30b9\u306e\u70b9\u304b\u3089\u59cb\u3081\u308b\n } else {\n //\uff11\u3053\u4ee5\u4e0a\u305a\u308c\u3066\u3044\u308b\u3068\u30a2\u30a6\u30c8\n ok &&= in(v) == g(v).length\n }\n }\n\n (s0, ok && (s.isEmpty || s.contains(s0)) && (plus == 0 && minus == 0 || plus == 1 && minus == 1))\n } map { path =>\n // \u3061\u3087\u3046\u3069\u9006\u3055\u307e\u306b\u306a\u3063\u3066\u3044\u308b\u306e\u3067\u3001\u6709\u5411\u30b0\u30e9\u30d5\u306e\u5834\u5408\u306freverse\u3057\u306a\u3044\u3068\u3044\u3051\u306a\u3044\n REP((m + 1)/2) { i =>\n val t = path(i)\n path(i) = path(m - i)\n path(m - i) = t\n }\n path\n }\n }\n\n private def makePath(g: G, m: Int)(f: G => (Int, Boolean)): Option[Array[Int]] = {\n val n = g.length\n val path = Array.ofDim[Int](m + 1)\n var pi = 0\n val used = Array.ofDim[Boolean](m)\n val ix = Array.ofDim[Int](n)\n\n val stack = Array.ofDim[Int](m + 1)\n var si = 0\n\n val (s, preCondition) = f(g)\n\n def dfs(s: Int): Unit = {\n stack(si) = s; si += 1\n while(si > 0) {\n val v = stack(si-1)\n while(ix(v) < g(v).length && used(g(v)(ix(v)).id)) ix(v) += 1\n if (ix(v) == g(v).length) {\n si -= 1\n path(pi) = v; pi += 1\n } else {\n used(g(v)(ix(v)).id) = true\n stack(si) = g(v)(ix(v)).u; si += 1; ix(v) += 1\n }\n }\n }\n\n if (!preCondition) {\n None\n } else {\n dfs(s)\n if (pi == m + 1) Some(path) else None\n }\n }\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val A, B, C, D = ni()\n val N = A + B + C + D\n val Cnt = Array(A, B, C, D)\n\n if (N == 1) {\n REP(4) { i =>\n if (Cnt(i) > 0) {\n out.println(\"YES\")\n out.println(i)\n return\n }\n }\n }\n\n REP(4) { s =>\n REP(4) { t =>\n val cnt = Array.ofDim[Int](4)\n cnt(s) += 1; cnt(t) += 1\n var ok = true\n REP(4) { k =>\n ok &&= Cnt(k) >= cnt(k)\n }\n var e01, e10 = A\n var e23, e32 = D\n if (s == 0) e10 -= 1\n if (t == 0) e01 -= 1\n if (s == 3) e23 -= 1\n if (t == 3) e32 -= 1\n var e21 = B - e01\n var e12 = C - e32\n if (s == 1) e21 -= 1\n if (s == 2) e12 -= 1\n\n if (e01 >= 0 && e10 >= 0 && e12 >= 0 && e21 >= 0 && e23 >= 0 && e32 >= 0 &&\n e01 + e10 + e12 + e21 + e23 + e32 == N - 1 &&\n e10 + (if (s == 0) 1 else 0) == A &&\n e01 + e21 + (if (s == 1) 1 else 0) == B &&\n e32 + e12 + (if (s == 2) 1 else 0) == C &&\n e23 + (if (s == 3) 1 else 0) == D\n ) {\n val g = Array.fill(4)(ArrayBuffer[Edge]())\n REP(e01) { i => g(0) += Edge(1, i) }\n REP(e10, e01) { i => g(1) += Edge(0, i) }\n REP(e12, e01 + e10) { i => g(1) += Edge(2, i) }\n REP(e21, e01 + e10 + e12) { i => g(2) += Edge(1, i) }\n REP(e23, e01 + e10 + e12 + e21) { i => g(2) += Edge(3, i) }\n REP(e32, e01 + e10 + e12 + e21 + e23) { i => g(3) += Edge(2, i) }\n EulerianTrail.makeDPath(g, N - 1, s) match {\n case None =>\n case Some(path) =>\n debug(s\"$s $t $e01 $e10 $e12 $e21 $e23 $e32\")\n out.println(\"YES\")\n out.println(path.mkString(\" \"))\n return\n }\n }\n }\n }\n out.println(\"NO\")\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 import scala.collection.mutable.ArrayBuffer\n case class Edge(u: Int, id: Int)\n type G = Array[ArrayBuffer[Edge]]\n\nobject EulerianTrail {\n def makeUDPath(g: G, m: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n var odds = 0\n var s = g.indexWhere(_.nonEmpty)\n REP(n) { v =>\n val odd = g(v).length % 2 == 1\n if (odd) {\n s = v\n odds += 1\n }\n }\n\n (s, odds == 0 || odds == 2)\n }\n }\n\n def makeDPath(g: G, m: Int, s0: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n\n var s = -1\n val in = Array.ofDim[Int](n)\n REP(n) { v =>\n REP(g(v).length) { i =>\n val u = g(v)(i).u\n in(u) += 1\n }\n }\n\n var plus, minus = 0\n REP(n) { v =>\n // in - out\n if (in(v) > g(v).length) {\n plus += 1\n } else if (in(v) < g(v).length) {\n minus += 1\n s = v // \u53ce\u652f\u30de\u30a4\u30ca\u30b9\u306e\u70b9\u304b\u3089\u59cb\u3081\u308b\n }\n }\n\n (s0, (s == -1 || s == s0) && (plus == 0 && minus == 0 || plus == 1 && minus == 1))\n } map { path =>\n // \u3061\u3087\u3046\u3069\u9006\u3055\u307e\u306b\u306a\u3063\u3066\u3044\u308b\u306e\u3067\u3001\u6709\u5411\u30b0\u30e9\u30d5\u306e\u5834\u5408\u306freverse\u3057\u306a\u3044\u3068\u3044\u3051\u306a\u3044\n REP((m + 1)/2) { i =>\n val t = path(i)\n path(i) = path(m - i)\n path(m - i) = t\n }\n path\n }\n }\n\n private def makePath(g: G, m: Int)(f: G => (Int, Boolean)): Option[Array[Int]] = {\n val n = g.length\n val path = Array.ofDim[Int](m + 1)\n var pi = 0\n val used = Array.ofDim[Boolean](m)\n val ix = Array.ofDim[Int](n)\n\n val stack = Array.ofDim[Int](m + 1)\n var si = 0\n\n val (s, preCondition) = f(g)\n\n def dfs(s: Int): Unit = {\n stack(si) = s; si += 1\n while(si > 0) {\n val v = stack(si-1)\n while(ix(v) < g(v).length && used(g(v)(ix(v)).id)) ix(v) += 1\n if (ix(v) == g(v).length) {\n si -= 1\n path(pi) = v; pi += 1\n } else {\n used(g(v)(ix(v)).id) = true\n stack(si) = g(v)(ix(v)).u; si += 1; ix(v) += 1\n }\n }\n }\n\n if (!preCondition) {\n None\n } else {\n dfs(s)\n if (pi == m + 1) Some(path) else None\n }\n }\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val A, B, C, D = ni()\n val N = A + B + C + D\n val Cnt = Array(A, B, C, D)\n\n if (N == 1) {\n REP(4) { i =>\n if (Cnt(i) > 0) {\n out.println(\"YES\")\n out.println(i)\n return\n }\n }\n }\n\n REP(4) { s =>\n REP(4) { t =>\n val cnt = Array.ofDim[Int](4)\n cnt(s) += 1; cnt(t) += 1\n var ok = true\n REP(4) { k =>\n ok &&= Cnt(k) >= cnt(k)\n }\n var e01, e10 = A\n var e23, e32 = D\n if (s == 0) e10 -= 1\n if (t == 0) e01 -= 1\n if (s == 3) e23 -= 1\n if (t == 3) e32 -= 1\n var e21 = B - e01\n var e12 = C - e32\n if (s == 1) e21 -= 1\n if (s == 2) e12 -= 1\n\n if (e01 >= 0 && e10 >= 0 && e12 >= 0 && e21 >= 0 && e23 >= 0 && e32 >= 0 &&\n e01 + e10 + e12 + e21 + e23 + e32 == N - 1 &&\n e10 + (if (s == 0) 1 else 0) == A &&\n e01 + e21 + (if (s == 1) 1 else 0) == B &&\n e32 + e12 + (if (s == 2) 1 else 0) == C &&\n e23 + (if (s == 3) 1 else 0) == D\n ) {\n val g = Array.fill(4)(ArrayBuffer[Edge]())\n REP(e01) { i => g(0) += Edge(1, i) }\n REP(e10, e01) { i => g(1) += Edge(0, i) }\n REP(e12, e01 + e10) { i => g(1) += Edge(2, i) }\n REP(e21, e01 + e10 + e12) { i => g(2) += Edge(1, i) }\n REP(e23, e01 + e10 + e12 + e21) { i => g(2) += Edge(3, i) }\n REP(e32, e01 + e10 + e12 + e21 + e23) { i => g(3) += Edge(2, i) }\n EulerianTrail.makeDPath(g, N - 1, s) match {\n case None =>\n case Some(path) =>\n debug(s\"$s $t $e01 $e10 $e12 $e21 $e23 $e32\")\n out.println(\"YES\")\n out.println(path.mkString(\" \"))\n return\n }\n }\n }\n }\n out.println(\"NO\")\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 import scala.collection.mutable.ArrayBuffer\n case class Edge(u: Int, id: Int)\n type G = Array[ArrayBuffer[Edge]]\n\nobject EulerianTrail {\n def makeUDPath(g: G, m: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n var odds = 0\n var s = g.indexWhere(_.nonEmpty)\n REP(n) { v =>\n val odd = g(v).length % 2 == 1\n if (odd) {\n s = v\n odds += 1\n }\n }\n\n (s, odds == 0 || odds == 2)\n }\n }\n\n def makeDPath(g: G, m: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n\n var s = 0\n val in = Array.ofDim[Int](n)\n REP(n) { v =>\n if (g(v).nonEmpty) s = v\n REP(g(v).length) { i =>\n val u = g(v)(i).u\n in(u) += 1\n }\n }\n\n var plus, minus = 0\n REP(n) { v =>\n // in - out\n if (in(v) > g(v).length) {\n plus += 1\n } else if (in(v) < g(v).length) {\n minus += 1\n s = v // \u53ce\u652f\u30de\u30a4\u30ca\u30b9\u306e\u70b9\u304b\u3089\u59cb\u3081\u308b\n }\n }\n\n (s, plus == 0 && minus == 0 || plus == 1 && minus == 1)\n } map { path =>\n // \u3061\u3087\u3046\u3069\u9006\u3055\u307e\u306b\u306a\u3063\u3066\u3044\u308b\u306e\u3067\u3001\u6709\u5411\u30b0\u30e9\u30d5\u306e\u5834\u5408\u306freverse\u3057\u306a\u3044\u3068\u3044\u3051\u306a\u3044\n REP((m + 1)/2) { i =>\n val t = path(i)\n path(i) = path(m - i)\n path(m - i) = t\n }\n path\n }\n }\n\n private def makePath(g: G, m: Int)(f: G => (Int, Boolean)): Option[Array[Int]] = {\n val n = g.length\n val path = Array.ofDim[Int](m + 1)\n var pi = 0\n val used = Array.ofDim[Boolean](m)\n val ix = Array.ofDim[Int](n)\n\n val stack = Array.ofDim[Int](m + 1)\n var si = 0\n\n val (s, preCondition) = f(g)\n\n def dfs(s: Int): Unit = {\n stack(si) = s; si += 1\n while(si > 0) {\n val v = stack(si-1)\n while(ix(v) < g(v).length && used(g(v)(ix(v)).id)) ix(v) += 1\n if (ix(v) == g(v).length) {\n si -= 1\n path(pi) = v; pi += 1\n } else {\n used(g(v)(ix(v)).id) = true\n stack(si) = g(v)(ix(v)).u; si += 1; ix(v) += 1\n }\n }\n }\n\n if (!preCondition) {\n None\n } else {\n dfs(s)\n if (pi == m + 1) Some(path) else None\n }\n }\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def test(e01: Int, e12: Int, e23: Int) = {\n val g = Array.fill(4)(ArrayBuffer[Edge]())\n REP(e01) { i =>\n g(0) += Edge(1, i)\n g(1) += Edge(0, i)\n }\n REP(e12, e01) { i =>\n g(1) += Edge(2, i)\n g(2) += Edge(1, i)\n }\n REP(e23, e01 + e12) { i =>\n g(2) += Edge(3, i)\n g(3) += Edge(2, i)\n }\n\n EulerianTrail.makeUDPath(g, e01 + e12 + e23)\n }\n\n def solve(): Unit = {\n val A, B, C, D = ni()\n val N = A + B + C + D\n val Cnt = Array(A, B, C, D)\n\n if (N == 1) {\n REP(4) { i =>\n if (Cnt(i) > 0) {\n out.println(\"YES\")\n out.println(i)\n return\n }\n }\n }\n\n REP(4) { i =>\n REP(4) { j =>\n val cnt = Array.ofDim[Int](4)\n cnt(i) += 1; cnt(j) += 1\n var ok = true\n REP(4) { k =>\n ok &&= Cnt(k) >= cnt(k)\n }\n\n if (ok) {\n var e01 = A * 2\n var e23 = D * 2\n if (i == 0) e01 -= 1\n if (j == 0) e01 -= 1\n if (i == 3) e23 -= 1\n if (j == 3) e23 -= 1\n val e12 = N - 1 - e01 - e23\n if (e01 >= 0 && e12 >= 0 && e23 >= 0) {\n test(e01, e12, e23) match {\n case Some(path) =>\n val used = Array.ofDim[Int](4)\n REP(N) { k =>\n used(path(k)) += 1\n }\n REP(4) { k =>\n ok &&= Cnt(k) == used(k)\n }\n if (ok) {\n debug(s\"$i $j $e01 $e12 $e23\")\n out.println(\"YES\")\n out.println(path.mkString(\" \"))\n return\n }\n\n case None =>\n }\n }\n }\n }\n }\n out.println(\"NO\")\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 import scala.collection.mutable.ArrayBuffer\n case class Edge(u: Int, id: Int)\n type G = Array[ArrayBuffer[Edge]]\n\nobject EulerianTrail {\n def makeUDPath(g: G, m: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n var odds = 0\n var s = g.indexWhere(_.nonEmpty)\n REP(n) { v =>\n val odd = g(v).length % 2 == 1\n if (odd) {\n s = v\n odds += 1\n }\n }\n\n (s, odds == 0 || odds == 2)\n }\n }\n\n def makeDPath(g: G, m: Int, s0: Int): Option[Array[Int]] = {\n makePath(g, m) { g =>\n val n = g.length\n\n var s = ArrayBuffer[Int]()\n val in = Array.ofDim[Int](n)\n REP(n) { v =>\n REP(g(v).length) { i =>\n val u = g(v)(i).u\n in(u) += 1\n }\n }\n\n var plus, minus = 0\n REP(n) { v =>\n // in - out\n if (in(v) > g(v).length) {\n plus += 1\n } else if (in(v) < g(v).length) {\n minus += 1\n s += v // \u53ce\u652f\u30de\u30a4\u30ca\u30b9\u306e\u70b9\u304b\u3089\u59cb\u3081\u308b\n }\n }\n\n (s0, (s.isEmpty || s.contains(s0)) && (plus == 0 && minus == 0 || plus == 1 && minus == 1))\n } map { path =>\n // \u3061\u3087\u3046\u3069\u9006\u3055\u307e\u306b\u306a\u3063\u3066\u3044\u308b\u306e\u3067\u3001\u6709\u5411\u30b0\u30e9\u30d5\u306e\u5834\u5408\u306freverse\u3057\u306a\u3044\u3068\u3044\u3051\u306a\u3044\n REP((m + 1)/2) { i =>\n val t = path(i)\n path(i) = path(m - i)\n path(m - i) = t\n }\n path\n }\n }\n\n private def makePath(g: G, m: Int)(f: G => (Int, Boolean)): Option[Array[Int]] = {\n val n = g.length\n val path = Array.ofDim[Int](m + 1)\n var pi = 0\n val used = Array.ofDim[Boolean](m)\n val ix = Array.ofDim[Int](n)\n\n val stack = Array.ofDim[Int](m + 1)\n var si = 0\n\n val (s, preCondition) = f(g)\n\n def dfs(s: Int): Unit = {\n stack(si) = s; si += 1\n while(si > 0) {\n val v = stack(si-1)\n while(ix(v) < g(v).length && used(g(v)(ix(v)).id)) ix(v) += 1\n if (ix(v) == g(v).length) {\n si -= 1\n path(pi) = v; pi += 1\n } else {\n used(g(v)(ix(v)).id) = true\n stack(si) = g(v)(ix(v)).u; si += 1; ix(v) += 1\n }\n }\n }\n\n if (!preCondition) {\n None\n } else {\n dfs(s)\n if (pi == m + 1) Some(path) else None\n }\n }\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val A, B, C, D = ni()\n val N = A + B + C + D\n val Cnt = Array(A, B, C, D)\n\n if (N == 1) {\n REP(4) { i =>\n if (Cnt(i) > 0) {\n out.println(\"YES\")\n out.println(i)\n return\n }\n }\n }\n\n REP(4) { s =>\n REP(4) { t =>\n val cnt = Array.ofDim[Int](4)\n cnt(s) += 1; cnt(t) += 1\n var ok = true\n REP(4) { k =>\n ok &&= Cnt(k) >= cnt(k)\n }\n var e01, e10 = A\n var e23, e32 = D\n if (s == 0) e10 -= 1\n if (t == 0) e01 -= 1\n if (s == 3) e23 -= 1\n if (t == 3) e32 -= 1\n var e21 = B - e01\n var e12 = C - e32\n if (s == 1) e21 -= 1\n if (s == 2) e12 -= 1\n\n if (e01 >= 0 && e10 >= 0 && e12 >= 0 && e21 >= 0 && e23 >= 0 && e32 >= 0 &&\n e01 + e10 + e12 + e21 + e23 + e32 == N - 1 &&\n e10 + (if (s == 0) 1 else 0) == A &&\n e01 + e21 + (if (s == 1) 1 else 0) == B &&\n e32 + e12 + (if (s == 2) 1 else 0) == C &&\n e23 + (if (s == 3) 1 else 0) == D\n ) {\n val g = Array.fill(4)(ArrayBuffer[Edge]())\n REP(e01) { i => g(0) += Edge(1, i) }\n REP(e10, e01) { i => g(1) += Edge(0, i) }\n REP(e12, e01 + e10) { i => g(1) += Edge(2, i) }\n REP(e21, e01 + e10 + e12) { i => g(2) += Edge(1, i) }\n REP(e23, e01 + e10 + e12 + e21) { i => g(2) += Edge(3, i) }\n REP(e32, e01 + e10 + e12 + e21 + e23) { i => g(3) += Edge(2, i) }\n EulerianTrail.makeDPath(g, N - 1, s) match {\n case None =>\n case Some(path) =>\n debug(s\"$s $t $e01 $e10 $e12 $e21 $e23 $e32\")\n out.println(\"YES\")\n out.println(path.mkString(\" \"))\n return\n }\n }\n }\n }\n out.println(\"NO\")\n }\n}"}], "src_uid": "a981e174f1f3864d50deb541834f7831"} {"nl": {"description": "Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k\u00a0\u2014 the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used).", "input_spec": "The first line of the input contains the string received by Kate. The number of digits in this string does not exceed 1\u2009000\u2009000. The second line contains the substring of n which Vasya remembers. This string can contain leading zeroes. It is guaranteed that the input data is correct, and the answer always exists.", "output_spec": "Print the smalles integer n which Vasya could pass to Kate.", "sample_inputs": ["003512\n021", "199966633300\n63"], "sample_outputs": ["30021", "3036366999"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given two even integers $$$n$$$ and $$$m$$$. Your task is to find any binary matrix $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns where every cell $$$(i,j)$$$ has exactly two neighbours with a different value than $$$a_{i,j}$$$.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $$$(x,y)$$$ are: $$$(x-1,y)$$$, $$$(x,y+1)$$$, $$$(x+1,y)$$$ and $$$(x,y-1)$$$.It can be proven that under the given constraints, an answer always exists.", "input_spec": "Each test contains multiple test cases. The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains two even integers $$$n$$$ and $$$m$$$ ($$$2 \\le n,m \\le 50$$$)\u00a0\u2014 the height and width of the binary matrix, respectively.", "output_spec": "For each test case, print $$$n$$$ lines, each of which contains $$$m$$$ numbers, equal to $$$0$$$ or $$$1$$$\u00a0\u2014 any binary matrix which satisfies the constraints described in the statement. It can be proven that under the given constraints, an answer always exists.", "sample_inputs": ["3\n\n2 4\n\n2 2\n\n4 4"], "sample_outputs": ["1 0 0 1\n0 1 1 0\n1 0\n0 1\n1 0 1 0\n0 0 1 1\n1 1 0 0\n0 1 0 1"], "notes": "NoteWhite means $$$0$$$, black means $$$1$$$. The binary matrix from the first test caseThe binary matrix from the second test caseThe binary matrix from the third test case "}, "positive_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 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"}, {"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"} {"nl": {"description": "After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game \u00abCall of Soldiers 3\u00bb.The game has (m\u2009+\u20091) players and n types of soldiers in total. Players \u00abCall of Soldiers 3\u00bb are numbered form 1 to (m\u2009+\u20091). Types of soldiers are numbered from 0 to n\u2009-\u20091. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type. Fedor is the (m\u2009+\u20091)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200920;\u00a01\u2009\u2264\u2009m\u2009\u2264\u20091000). The i-th of the next (m\u2009+\u20091) lines contains a single integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u20092n\u2009-\u20091), that describes the i-th player's army. We remind you that Fedor is the (m\u2009+\u20091)-th player.", "output_spec": "Print a single integer \u2014 the number of Fedor's potential friends.", "sample_inputs": ["7 3 1\n8\n5\n111\n17", "3 3 3\n1\n2\n3\n4"], "sample_outputs": ["0", "3"], "notes": null}, "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 = 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": "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}"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm \"by columns\": cells are numbered starting from one; cells are numbered from left to right by columns, and inside each column from top to bottom; number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \\begin{matrix} 1 & 4 & 7 & 10 & 13 \\\\ 2 & 5 & 8 & 11 & 14 \\\\ 3 & 6 & 9 & 12 & 15 \\\\ \\end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering \"by rows\": cells are numbered starting from one; cells are numbered from top to bottom by rows, and inside each row from left to right; number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \\begin{matrix} 1 & 2 & 3 & 4 & 5 \\\\ 6 & 7 & 8 & 9 & 10 \\\\ 11 & 12 & 13 & 14 & 15 \\\\ \\end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering \"by rows\", if in the numbering \"by columns\" the cell has the number $$$x$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single line containing three integers $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \\le n, m \\le 10^6$$$, $$$1 \\le x \\le n \\cdot m$$$), where $$$n$$$ and $$$m$$$ are the number of rows and columns in the table, and $$$x$$$ is the cell number. Note that the numbers in some test cases do not fit into the $$$32$$$-bit integer type, so you must use at least the $$$64$$$-bit integer type of your programming language.", "output_spec": "For each test case, output the cell number in the numbering \"by rows\".", "sample_inputs": ["5\n1 1 1\n2 2 3\n3 5 11\n100 100 7312\n1000000 1000000 1000000000000"], "sample_outputs": ["1\n2\n9\n1174\n1000000000000"], "notes": null}, "positive_code": [{"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 nmx: Seq[BigInt] = readLine.split(' ').toList.map(x => BigInt(x))\r\n val n = nmx(0)\r\n val m = nmx(1)\r\n val x = nmx(2)\r\n val row = Row(n)\r\n val col = Col(m)\r\n\r\n val indices = getIndicesForColumnOrdering(x, row)\r\n val numberForRowOrdering = getNumberForRowOrderingIndices(row, col, indices)\r\n println(numberForRowOrdering)\r\n }\r\n\r\n final case class Row(value : BigInt)\r\n final case class Col(value : BigInt)\r\n\r\n def getIndicesForColumnOrdering(number : BigInt, row : Row) : (Row, Col) = {\r\n val r = (number % row.value -1 + row.value) % row.value + 1\r\n val c = (number-1) / row.value + 1\r\n (Row(r), Col(c))\r\n }\r\n\r\n def getNumberForRowOrderingIndices(row : Row, col : Col, indices : (Row, Col)): BigInt ={\r\n (indices._1.value - 1) * col.value + indices._2 .value\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "e519e4495c9acef4c4a614aef73cb322"} {"nl": {"description": "You are given a string $$$s$$$ consisting of lowercase Latin letters and $$$q$$$ queries for this string.Recall that the substring $$$s[l; r]$$$ of the string $$$s$$$ is the string $$$s_l s_{l + 1} \\dots s_r$$$. For example, the substrings of \"codeforces\" are \"code\", \"force\", \"f\", \"for\", but not \"coder\" and \"top\".There are two types of queries: $$$1~ pos~ c$$$ ($$$1 \\le pos \\le |s|$$$, $$$c$$$ is lowercase Latin letter): replace $$$s_{pos}$$$ with $$$c$$$ (set $$$s_{pos} := c$$$); $$$2~ l~ r$$$ ($$$1 \\le l \\le r \\le |s|$$$): calculate the number of distinct characters in the substring $$$s[l; r]$$$. ", "input_spec": "The first line of the input contains one string $$$s$$$ consisting of no more than $$$10^5$$$ lowercase Latin letters. The second line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^5$$$) \u2014 the number of queries. The next $$$q$$$ lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.", "output_spec": "For each query of the second type print the answer for it \u2014 the number of distinct characters in the required substring in this query.", "sample_inputs": ["abacaba\n5\n2 1 4\n1 4 b\n1 5 b\n2 4 6\n2 1 7", "dfcbbcfeeedbaea\n15\n1 6 e\n1 4 b\n2 6 14\n1 7 b\n1 12 c\n2 6 8\n2 1 6\n1 7 c\n1 2 f\n1 10 a\n2 7 9\n1 10 a\n1 14 b\n1 1 f\n2 1 11"], "sample_outputs": ["3\n1\n2", "5\n2\n5\n2\n6"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "7a79c60749ee13c69284ba8fe34b63b3"} {"nl": {"description": "Theofanis has a string $$$s_1 s_2 \\dots s_n$$$ and a character $$$c$$$. He wants to make all characters of the string equal to $$$c$$$ using the minimum number of operations.In one operation he can choose a number $$$x$$$ ($$$1 \\le x \\le n$$$) and for every position $$$i$$$, where $$$i$$$ is not divisible by $$$x$$$, replace $$$s_i$$$ with $$$c$$$. Find the minimum number of operations required to make all the characters equal to $$$c$$$ and the $$$x$$$-s that he should use in his operations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$3 \\le n \\le 3 \\cdot 10^5$$$) and a lowercase Latin letter $$$c$$$\u00a0\u2014 the length of the string $$$s$$$ and the character the resulting string should consist of. The second line of each test case contains a string $$$s$$$ of lowercase Latin letters\u00a0\u2014 the initial string. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, firstly print one integer $$$m$$$\u00a0\u2014 the minimum number of operations required to make all the characters equal to $$$c$$$. Next, print $$$m$$$ integers $$$x_1, x_2, \\dots, x_m$$$ ($$$1 \\le x_j \\le n$$$)\u00a0\u2014 the $$$x$$$-s that should be used in the order they are given. It can be proved that under given constraints, an answer always exists. If there are multiple answers, print any.", "sample_inputs": ["3\n4 a\naaaa\n4 a\nbaaa\n4 b\nbzyx"], "sample_outputs": ["0\n1\n2\n2 \n2 3"], "notes": "NoteLet's describe what happens in the third test case: $$$x_1 = 2$$$: we choose all positions that are not divisible by $$$2$$$ and replace them, i.\u00a0e. bzyx $$$\\rightarrow$$$ bzbx; $$$x_2 = 3$$$: we choose all positions that are not divisible by $$$3$$$ and replace them, i.\u00a0e. bzbx $$$\\rightarrow$$$ bbbb. "}, "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 val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val c = readString()(0)\n val s = readString()\n var cnt = 0\n for (ch <- s) {\n if (ch != c)\n cnt += 1\n }\n if (cnt == 0) {\n writer.println(0)\n } else {\n var ans = n+1\n var found = false\n while (ans > 1 && !found) {\n ans -= 1\n var ok = true\n var mul = ans\n while (mul <= n && ok) {\n if (s(mul-1) != c)\n ok = false\n mul += ans\n }\n if (ok)\n found = true\n }\n if (found) {\n writer.println(1)\n writer.println(ans)\n } else {\n writer.println(2)\n writer.print(n-1)\n writer.print(' ')\n writer.println(n)\n }\n }\n }\n writer.flush()\n}\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 val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val c = readString()(0)\n val s = readString()\n var cnt = 0\n for (ch <- s) {\n if (ch != c)\n cnt += 1\n }\n if (cnt == 0) {\n writer.println(0)\n } else {\n if (s(s.length-1) == c) {\n writer.println(1)\n writer.println(n)\n } else {\n if (cnt == 1) {\n writer.println(1)\n writer.println(n-1)\n } else {\n writer.println(2)\n writer.print(n-1)\n writer.print(' ')\n writer.println(n)\n }\n }\n }\n }\n writer.flush()\n}\n"}], "src_uid": "3b8969f7f2051d559a1e375ce8275c73"} {"nl": {"description": "You are given three integers $$$a$$$, $$$b$$$, and $$$c$$$. Determine if one of them is the sum of the other two.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 9261$$$)\u00a0\u2014 the number of test cases. The description of each test case consists of three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$0 \\leq a, b, c \\leq 20$$$).", "output_spec": "For each test case, output \"YES\" if one of the numbers is the sum of the other two, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["7\n\n1 4 3\n\n2 5 8\n\n9 11 20\n\n0 0 0\n\n20 20 20\n\n4 12 3\n\n15 7 8"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case, $$$1 + 3 = 4$$$.In the second test case, none of the numbers is the sum of the other two.In the third test case, $$$9 + 11 = 20$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "1b8293c51d025940eb859b0e625ab588"} {"nl": {"description": "Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i\u2009+\u20091)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i\u2009+\u20091)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. ", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300\u2009000)\u00a0\u2014 number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n)\u00a0\u2014 positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.", "output_spec": "Print n\u2009+\u20091 numbers a0,\u2009a1,\u2009...,\u2009an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on. ", "sample_inputs": ["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"], "sample_outputs": ["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"], "notes": "NoteLet's denote as O coin out of circulation, and as X \u2014 coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO \u2009\u2192\u2009 OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO \u2009\u2192\u2009 OXOX \u2009\u2192\u2009 OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX \u2009\u2192\u2009 OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges."}, "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 D_441_2 { 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 pLine = readLine\n \n val coins = (0 until n).map(x=>pLine.int).toArray\n \n //---------------------------- parameters reading :end\n \n val state = Array.fill(n)(false)\n \n \n// def count3(arr: Array[Boolean], ind: Int) = {\n// var count = 0\n// var afterGap = false\n// for(i <- (arr.length-1 to 0 by -1) ) {\n// if (afterGap && arr(i)) {\n// count += 1\n// } \n// if (!arr(i)) afterGap = true\n// }\n// count + 1\n// }\n//\n// val steps = coins.map{co =>\n// val ind = co-1\n// state(ind) = true\n// debug(\"coin: \" + co + \" -> \" + state.map(x => if(x) \"X\" else \"O\").mkString(\"\"))\n// count3(state, ind)\n// }\n \n var counts = new Array[Int](n)\n var count = 0\n var readyEnd = n\n val state2 = Array.fill(n)(false)\n for(i <- (0 until n)) {\n// if (coins(i) == 11) {\n// println(\"kmkm\")\n// }\n val ind = coins(i) -1\n state2(ind) = true\n debug(\"coin: \" + coins(i) + \" -> \" + state2.map(x => if(x) \"X\" else \"O\").mkString(\"\"))\n if (coins(i) == readyEnd) {\n readyEnd -= 1\n while (readyEnd > 0 && state2(readyEnd-1)) {\n readyEnd -= 1\n }\n } \n count += 1\n \n val ready = n - readyEnd\n debug(s\"count:$count ready:$ready\")\n counts(i) = (count - ready) + 1\n }\n \n val steps2 = counts\n \n val res = (1 +: steps2).mkString(\" \")\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\n1 3 4 2\n\"\"\"\n\nval sa2 = \"\"\"\n8\n6 8 3 4 7 2 1 5\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n\nval t4 = \"\"\"\n11\n10 8 9 4 6 3 5 1 11 7 2 \n\"\"\"\n// 10 8 9 4 6 3 5 1 11 7 2 \n// 1 2 3 4 5 6 7 8 9 6 2 1\n// 1 2 3 4 5 6 7 8 9 6 2 1 my\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 D_441_2 { 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 pLine = readLine\n \n val coins = (0 until n).map(x=>pLine.int).toArray\n \n //---------------------------- parameters reading :end\n \n val state = Array.fill(n)(false)\n \n def count(arr: Array[Boolean], ind: Int) = {\n var rightGaps = 0\n var max = 0 \n var i = arr.length-1\n var xGroup = true\n var groupSum = 0\n while (i > -1) {\n val coin = arr(i) \n if (coin) {\n if (xGroup) {\n groupSum += 1\n } else {\n groupSum += rightGaps\n }\n } else {\n if (xGroup) {\n if (groupSum > max && rightGaps > 0) max = groupSum\n rightGaps += 1\n } else {\n //nothing\n }\n groupSum = 0\n }\n xGroup = coin\n i -= 1\n }\n if (xGroup && groupSum > max && rightGaps > 0) max = groupSum\n max + 1\n }\n\n val steps = coins.map{co =>\n val ind = co-1\n state(ind) = true\n debug(\"coin: \" + co + \" -> \" + state.map(x => if(x) \"X\" else \"O\").mkString(\"\"))\n count(state, ind)\n }\n \n \n val res = (1 +: steps).mkString(\" \")\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\n1 3 4 2\n\"\"\"\n\nval sa2 = \"\"\"\n8\n6 8 3 4 7 2 1 5\n\"\"\"\n\nval sa3 = \"\"\"\n\"\"\"\n}\n\n}\n\n"}], "src_uid": "b97eeaa66e91bbcc3b5e616cb480c7af"} {"nl": {"description": "Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x\u2009=\u20090 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.What is the maximum number of apples he can collect?", "input_spec": "The first line contains one number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), the number of apple trees in Lala Land. The following n lines contains two integers each xi, ai (\u2009-\u2009105\u2009\u2264\u2009xi\u2009\u2264\u2009105, xi\u2009\u2260\u20090, 1\u2009\u2264\u2009ai\u2009\u2264\u2009105), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.", "output_spec": "Output the maximum number of apples Amr can collect.", "sample_inputs": ["2\n-1 5\n1 5", "3\n-2 2\n1 4\n-1 3", "3\n1 9\n3 5\n7 10"], "sample_outputs": ["10", "9", "9"], "notes": "NoteIn the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.In the second sample test the optimal solution is to go left to x\u2009=\u2009\u2009-\u20091, collect apples from there, then the direction will be reversed, Amr has to go to x\u2009=\u20091, collect apples from there, then the direction will be reversed and Amr goes to the final tree x\u2009=\u2009\u2009-\u20092.In the third sample test the optimal solution is to go right to x\u2009=\u20091, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left."}, "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(_ \u21d2 {\n val s = StdIn.readLine().split(\" \")\n s(0).toInt \u2192 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 \u21d2 applesAcc\n case _ \u21d2 eatApples(left.tail, right, applesAcc + left.head._2, \"right\")\n }\n } else {\n right match {\n case Nil \u21d2 applesAcc\n case _ \u21d2 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._\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"}, {"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"} {"nl": {"description": "As you know, an undirected connected graph with n nodes and n\u2009-\u20091 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The first line contains two space-separated integers d (0\u2009\u2264\u2009d\u2009\u2264\u20092000) and n (1\u2009\u2264\u2009n\u2009\u2264\u20092000). The second line contains n space-separated positive integers a1,\u2009a2,\u2009...,\u2009an(1\u2009\u2264\u2009ai\u2009\u2264\u20092000). Then the next n\u2009-\u20091 line each contain pair of integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.", "output_spec": "Print the number of valid sets modulo 1000000007.", "sample_inputs": ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"], "sample_outputs": ["8", "3", "41"], "notes": "NoteIn the first sample, there are exactly 8 valid sets: {1},\u2009{2},\u2009{3},\u2009{4},\u2009{1,\u20092},\u2009{1,\u20093},\u2009{3,\u20094} and {1,\u20093,\u20094}. Set {1,\u20092,\u20093,\u20094} is not valid, because the third condition isn't satisfied. Set {1,\u20094} satisfies the third condition, but conflicts with the second condition."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \\cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different. \u00a0\u00a0These subrectangles are flags. \u00a0\u00a0\u00a0\u00a0\u00a0These subrectangles are not flags. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1\\,000$$$)\u00a0\u2014 the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.", "output_spec": "In the only line print the number of subrectangles which form valid flags.", "sample_inputs": ["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"], "sample_outputs": ["6", "1"], "notes": "Note \u00a0The selected subrectangles are flags in the first example. "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val g = nm_c(N, M)\n\n val cum = Array.ofDim[Int](N, M)\n REP(M) { j =>\n REP_r(N) { i =>\n val v = if (i == N - 1) 1\n else {\n if (g(i)(j) == g(i + 1)(j)) cum(i + 1)(j) + 1 else 1\n }\n cum(i)(j) = v\n }\n }\n\n debugDim(cum)\n\n var ans = 0L\n REP(N) { i =>\n var j = 0\n while(j < M) {\n var k = j\n val w = cum(i)(j) // \uff11\u672c\u306estripe\u306e\u5e45\n if (i + w * 3 <= N) {\n val i2 = i + w\n val i3 = i + w * 2\n while (k < M &&\n g(i)(j) == g(i)(k) && cum(i)(k) == w &&\n g(i2)(j) == g(i2)(k) && cum(i2)(k) == w &&\n g(i3)(j) == g(i3)(k) && cum(i3)(k) >= w\n ) {\n k += 1\n }\n val n = k - j\n debug(s\"i:$i j:$j k:$k n:$n\")\n ans += n.toLong * (n + 1) / 2\n }\n j = max(j + 1, k)\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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, M = ni()\n val g = nm_c(N, M)\n\n val cum = Array.ofDim[Int](N, M)\n REP(M) { j =>\n REP_r(N) { i =>\n val v = if (i == N - 1) 1\n else {\n if (g(i)(j) == g(i + 1)(j)) cum(i + 1)(j) + 1 else 1\n }\n cum(i)(j) = v\n }\n }\n\n debugDim(cum)\n\n var ans = 0L\n REP(N) { i =>\n var j = 0\n while(j < M) {\n var k = j\n val w = cum(i)(j) // \uff11\u672c\u306estripe\u306e\u5e45\n if (i + w * 3 <= N) {\n val i2 = i + w\n val i3 = i + w * 2\n while (k < M && cum(i)(k) == w &&\n cum(i2)(k) == w &&\n cum(i3)(k) >= w\n ) {\n k += 1\n }\n val n = k - j\n debug(s\"i:$i j:$j k:$k n:$n\")\n ans += n.toLong * (n + 1) / 2\n }\n j = max(j + 1, k)\n }\n }\n\n out.println(ans)\n }\n}"}], "src_uid": "edc54435b62e76287da94836ad3aa86b"} {"nl": {"description": "One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $$$n$$$ non-negative integers.If there are exactly $$$K$$$ distinct values in the array, then we need $$$k = \\lceil \\log_{2} K \\rceil$$$ bits to store each value. It then takes $$$nk$$$ bits to store the whole file.To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $$$l \\le r$$$, and after that all intensity values are changed in the following way: if the intensity value is within the range $$$[l;r]$$$, we don't change it. If it is less than $$$l$$$, we change it to $$$l$$$; if it is greater than $$$r$$$, we change it to $$$r$$$. You can see that we lose some low and some high intensities.Your task is to apply this compression in such a way that the file fits onto a disk of size $$$I$$$ bytes, and the number of changed elements in the array is minimal possible.We remind you that $$$1$$$ byte contains $$$8$$$ bits.$$$k = \\lceil log_{2} K \\rceil$$$ is the smallest integer such that $$$K \\le 2^{k}$$$. In particular, if $$$K = 1$$$, then $$$k = 0$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$I$$$ ($$$1 \\le n \\le 4 \\cdot 10^{5}$$$, $$$1 \\le I \\le 10^{8}$$$)\u00a0\u2014 the length of the array and the size of the disk in bytes, respectively. The next line contains $$$n$$$ integers $$$a_{i}$$$ ($$$0 \\le a_{i} \\le 10^{9}$$$)\u00a0\u2014 the array denoting the sound file.", "output_spec": "Print a single integer\u00a0\u2014 the minimal possible number of changed elements.", "sample_inputs": ["6 1\n2 1 2 3 4 3", "6 2\n2 1 2 3 4 3", "6 1\n1 1 2 2 3 3"], "sample_outputs": ["2", "0", "2"], "notes": "NoteIn the first example we can choose $$$l=2, r=3$$$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $$$K=2$$$, and the sound file fits onto the disk. Only two values are changed.In the second example the disk is larger, so the initial file fits it and no changes are required.In the third example we have to change both 1s or both 3s."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, I = ni()\n val A = na(N)\n radixSort(A)\n val seen = mutable.HashSet[Int]()\n REP(N) { i =>\n if (!seen(A(i))) {\n seen += A(i)\n }\n }\n\n val S = seen.size\n val K = log2_ceil(S)\n var k = K\n while(k.toLong * N > I * 8) {\n k -= 1\n }\n\n debug(s\"k:$k K:$K\")\n\n if (k == K) {\n out.println(0)\n } else {\n val len = 1 << k\n var ans = N\n var l, r = 0\n var cnt = 0\n\n def next(i: Int): Int = {\n var j = i\n while(j < N && A(i) == A(j)) j += 1\n j\n }\n\n while(l < N) {\n while(r < N && cnt < len) {\n r = next(r)\n cnt += 1\n }\n val change = N - (r - l)\n debug(s\"l:$l r:$r change:$change\")\n ans = min(ans, change)\n l = next(l)\n cnt -= 1\n }\n out.println(ans)\n }\n }\n\n /**\n * log2\u3057\u3066\u5c0f\u6570\u70b9\u5207\u308a\u6368\u3066\u305f\u3082\u306e\n */\n def log2(x: Int): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\n while(a > 1) {\n i += 1\n a >>>= 1\n }\n i\n }\n\n /**\n * log2\u306e\u5c0f\u6570\u70b9\u3092\u5207\u308a\u4e0a\u3052\u305f\u3082\u306e\n */\n def log2_ceil(x: Int): Int = {\n assert(x > 0)\n if (x == 1) {\n 0\n } else {\n log2(x - 1) + 1\n }\n }\n\n /**\n * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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}"}], "negative_code": [], "src_uid": "ee4f345ac64f4444bd6e30d4818423a6"} {"nl": {"description": "Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 10^{18}$$$) \u2014 the number of computers and the number of patch cables.", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum number of hours required to copy the update files to all $$$n$$$ computers.", "sample_inputs": ["4\n8 3\n6 6\n7 1\n1 1"], "sample_outputs": ["4\n3\n6\n0"], "notes": "NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$. "}, "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 = (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"}, {"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": "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"}], "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"} {"nl": {"description": "You are given n points on Cartesian plane. Every point is a lattice point (i.\u2009e. both of its coordinates are integers), and all points are distinct.You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|,\u2009|yi|\u2009\u2264\u2009109)\u2014 coordinates of i-th point. All n points are distinct.", "output_spec": "If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.", "sample_inputs": ["5\n0 0\n0 1\n1 1\n1 -1\n2 2", "5\n0 0\n1 0\n2 1\n1 1\n2 3"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. "}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r\u2009-\u2009l\u2009+\u20091 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l\u2009+\u20091, the animal l\u2009+\u20092 swaps with the animal l\u2009+\u20093, ..., finally, the animal at position r\u2009-\u20091 swaps with the animal r.Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20\u2009000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 number of animals in the robber girl's zoo. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the height of the animal occupying the i-th place.", "output_spec": "Print the sequence of operations that will rearrange the animals by non-decreasing height. The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n)\u00a0\u2014 descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed. The number of operations should not exceed 20\u2009000. If the animals are arranged correctly from the start, you are allowed to output nothing.", "sample_inputs": ["4\n2 1 4 3", "7\n36 28 57 39 66 69 68", "5\n1 2 1 2 1"], "sample_outputs": ["1 4", "1 4\n6 7", "2 5\n3 4\n1 4\n1 4"], "notes": "NoteNote that you don't have to minimize the number of operations. Any solution that performs at most 20\u2009000 operations is allowed."}, "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 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"}, {"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"} {"nl": {"description": "Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string \"zbcdzefdzc\". The lists of positions of equal letters are: b: 2 c: 3,\u200910 d: 4,\u20098 e: 6 f: 7 z: 1,\u20095,\u20099 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5\u2009-\u20091\u2009=\u20094, 9\u2009-\u20095\u2009=\u20094, for letters c: 10\u2009-\u20093\u2009=\u20097, for letters d: 8\u2009-\u20094\u2009=\u20094. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.", "input_spec": "The single line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the length of the sought string.", "output_spec": "Print on the single line the lexicographically minimal lucky string whose length equals n.", "sample_inputs": ["5", "3"], "sample_outputs": ["abcda", "abc"], "notes": "NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), that ai\u2009<\u2009bi, and for any j (1\u2009\u2264\u2009j\u2009<\u2009i) aj\u2009=\u2009bj."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "94278e9c55f0fc82b48145ebecbc515f"} {"nl": {"description": "This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game \u00abLizards and Basements\u00bb. At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) \u2014 they lose b (1\u2009\u2264\u2009b\u2009<\u2009a\u2009\u2264\u200910) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.", "input_spec": "The first line of the input contains three integers n,\u2009a,\u2009b (3\u2009\u2264\u2009n\u2009\u2264\u200910; 1\u2009\u2264\u2009b\u2009<\u2009a\u2009\u2264\u200910). The second line contains a sequence of n integers \u2014 h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u200915), where hi is the amount of health points the i-th archer has.", "output_spec": "In the first line print t \u2014 the required minimum amount of fire balls. In the second line print t numbers \u2014 indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n\u2009-\u20091. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.", "sample_inputs": ["3 2 1\n2 2 2", "4 3 1\n1 4 1 1"], "sample_outputs": ["3\n2 2 2", "4\n2 2 3 3"], "notes": null}, "positive_code": [{"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}"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Dreamoon likes coloring cells very much.There is a row of $$$n$$$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $$$1$$$ to $$$n$$$.You are given an integer $$$m$$$ and $$$m$$$ integers $$$l_1, l_2, \\ldots, l_m$$$ ($$$1 \\le l_i \\le n$$$)Dreamoon will perform $$$m$$$ operations.In $$$i$$$-th operation, Dreamoon will choose a number $$$p_i$$$ from range $$$[1, n-l_i+1]$$$ (inclusive) and will paint all cells from $$$p_i$$$ to $$$p_i+l_i-1$$$ (inclusive) in $$$i$$$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these $$$m$$$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $$$p_i$$$ in each operation to satisfy all constraints.", "input_spec": "The first line contains two integers $$$n,m$$$ ($$$1 \\leq m \\leq n \\leq 100\\,000$$$). The second line contains $$$m$$$ integers $$$l_1, l_2, \\ldots, l_m$$$ ($$$1 \\leq l_i \\leq n$$$).", "output_spec": "If it's impossible to perform $$$m$$$ operations to satisfy all constraints, print \"'-1\" (without quotes). Otherwise, print $$$m$$$ integers $$$p_1, p_2, \\ldots, p_m$$$ ($$$1 \\leq p_i \\leq n - l_i + 1$$$), after these $$$m$$$ operations, all colors should appear at least once and all cells should be colored. If there are several possible solutions, you can print any.", "sample_inputs": ["5 3\n3 2 2", "10 1\n1"], "sample_outputs": ["2 4 1", "-1"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x,\u2009y,\u2009z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa\u00b7yb\u00b7zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x,\u2009y,\u2009z (0\u2009\u2264\u2009x,\u2009y,\u2009z;\u00a0x\u2009+\u2009y\u2009+\u2009z\u2009\u2264\u2009S), that the distance between the center of the Universe and the point (x,\u2009y,\u2009z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00\u2009=\u20091.", "input_spec": "The first line contains a single integer S (1\u2009\u2264\u2009S\u2009\u2264\u2009103) \u2014 the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0\u2009\u2264\u2009a,\u2009b,\u2009c\u2009\u2264\u2009103) \u2014 the numbers that describe the metric of mushroom scientists.", "output_spec": "Print three real numbers \u2014 the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10\u2009-\u20096. We think that ln(0)\u2009=\u2009\u2009-\u2009\u221e.", "sample_inputs": ["3\n1 1 1", "3\n2 0 0"], "sample_outputs": ["1.0 1.0 1.0", "3.0 0.0 0.0"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Given a sequence of integers a1,\u2009...,\u2009an and q queries x1,\u2009...,\u2009xq on it. For each query xi you have to count the number of pairs (l,\u2009r) such that 1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n and gcd(al,\u2009al\u2009+\u20091,\u2009...,\u2009ar)\u2009=\u2009xi. is a greatest common divisor of v1,\u2009v2,\u2009...,\u2009vn, that is equal to a largest positive integer that divides all vi.", "input_spec": "The first line of the input contains integer n, (1\u2009\u2264\u2009n\u2009\u2264\u2009105), denoting the length of the sequence. The next line contains n space separated integers a1,\u2009...,\u2009an, (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line of the input contains integer q, (1\u2009\u2264\u2009q\u2009\u2264\u20093\u2009\u00d7\u2009105), denoting the number of queries. Then follows q lines, each contain an integer xi, (1\u2009\u2264\u2009xi\u2009\u2264\u2009109).", "output_spec": "For each query print the result in a separate line.", "sample_inputs": ["3\n2 6 3\n5\n1\n2\n3\n4\n6", "7\n10 20 3 15 1000 60 16\n10\n1\n2\n3\n4\n5\n6\n10\n20\n60\n1000"], "sample_outputs": ["1\n2\n2\n0\n1", "14\n0\n2\n2\n2\n0\n2\n2\n1\n1"], "notes": null}, "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 cnts = Array.fill(n){ mutable.Map.empty[Int, Long] }\n \n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n \n for (i <- as.indices) {\n cnts(i).put(as(i), 1L)\n if (i > 0) {\n for (prev <- cnts(i - 1).keys) {\n val g = gcd(prev, as(i))\n cnts(i).put(g, (if (cnts(i).contains(g)) cnts(i)(g) else 0L) + cnts(i - 1)(prev))\n }\n }\n }\n \n val totals = mutable.Map.empty[Int, Long]\n for (c <- cnts) {\n for (x <- c.keys) {\n totals.put(x, (if (totals.contains(x)) totals(x) else 0L) + c(x))\n }\n }\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 x = readLine.toInt\n println(if (totals.contains(x)) totals(x) else 0L)\n }\n Console.flush\n}"}], "negative_code": [], "src_uid": "ae7c90b00cc8393fc4db14a6aad32957"} {"nl": {"description": "Vasily the bear has got a sequence of positive integers a1,\u2009a2,\u2009...,\u2009an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1,\u2009b2,\u2009...,\u2009bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by \"&\", in Pascal \u2014 by \"and\".", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an\u2009\u2264\u2009109).", "output_spec": "In the first line print a single integer k (k\u2009>\u20090), showing how many numbers to write out. In the second line print k integers b1,\u2009b2,\u2009...,\u2009bk \u2014 the numbers to write out. You are allowed to print numbers b1,\u2009b2,\u2009...,\u2009bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.", "sample_inputs": ["5\n1 2 3 4 5", "3\n1 2 4"], "sample_outputs": ["2\n4 5", "1\n4"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1,\u2009a2,\u2009...,\u2009an, then after we apply the described operation, the sequence transforms into a1,\u2009a2,\u2009...,\u2009an[,\u2009a1,\u2009a2,\u2009...,\u2009al] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.", "input_spec": "The first line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of stages to build a sequence. Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009105) \u2014 the number to add. Type 2 means copying a prefix of length li to the end ci times, in this case the line further contains two integers li,\u2009ci (1\u2009\u2264\u2009li\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009ci\u2009\u2264\u2009104), li is the length of the prefix, ci is the number of copyings. It is guaranteed that the length of prefix li is never larger than the current length of the sequence. The next line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print the elements that Sereja is interested in, in the order in which their numbers occur in the input. ", "sample_inputs": ["6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16"], "sample_outputs": ["1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4"], "notes": null}, "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 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"} {"nl": {"description": "Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters \u2014 for different colours.", "input_spec": "The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters \u2014 the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. ", "output_spec": "Output one of the four words without inverted commas: \u00abforward\u00bb \u2014 if Peter could see such sequences only on the way from A to B; \u00abbackward\u00bb \u2014 if Peter could see such sequences on the way from B to A; \u00abboth\u00bb \u2014 if Peter could see such sequences both on the way from A to B, and on the way from B to A; \u00abfantasy\u00bb \u2014 if Peter could not see such sequences. ", "sample_inputs": ["atob\na\nb", "aaacaaa\naca\naa"], "sample_outputs": ["forward", "both"], "notes": "NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B."}, "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 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 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": "//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"}, {"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"} {"nl": {"description": "You are given array $$$a_1, a_2, \\ldots, a_n$$$, consisting of non-negative integers.Let's define operation of \"elimination\" with integer parameter $$$k$$$ ($$$1 \\leq k \\leq n$$$) as follows: Choose $$$k$$$ distinct array indices $$$1 \\leq i_1 < i_2 < \\ldots < i_k \\le n$$$. Calculate $$$x = a_{i_1} ~ \\& ~ a_{i_2} ~ \\& ~ \\ldots ~ \\& ~ a_{i_k}$$$, where $$$\\&$$$ denotes the bitwise AND operation (notes section contains formal definition). Subtract $$$x$$$ from each of $$$a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$$$; all other elements remain untouched. Find all possible values of $$$k$$$, such that it's possible to make all elements of array $$$a$$$ equal to $$$0$$$ using a finite number of elimination operations with parameter $$$k$$$. It can be proven that exists at least one possible $$$k$$$ for any array $$$a$$$.Note that you firstly choose $$$k$$$ and only after that perform elimination operations with value $$$k$$$ you've chosen initially.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 200\\,000$$$)\u00a0\u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i < 2^{30}$$$)\u00a0\u2014 array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\\,000$$$.", "output_spec": "For each test case, print all values $$$k$$$, such that it's possible to make all elements of $$$a$$$ equal to $$$0$$$ in a finite number of elimination operations with the given parameter $$$k$$$. Print them in increasing order.", "sample_inputs": ["5\n4\n4 4 4 4\n4\n13 7 25 19\n6\n3 5 3 1 7 1\n1\n1\n5\n0 0 0 0 0"], "sample_outputs": ["1 2 4\n1 2\n1\n1\n1 2 3 4 5"], "notes": "NoteIn the first test case: If $$$k = 1$$$, we can make four elimination operations with sets of indices $$$\\{1\\}$$$, $$$\\{2\\}$$$, $$$\\{3\\}$$$, $$$\\{4\\}$$$. Since $$$\\&$$$ of one element is equal to the element itself, then for each operation $$$x = a_i$$$, so $$$a_i - x = a_i - a_i = 0$$$. If $$$k = 2$$$, we can make two elimination operations with, for example, sets of indices $$$\\{1, 3\\}$$$ and $$$\\{2, 4\\}$$$: $$$x = a_1 ~ \\& ~ a_3$$$ $$$=$$$ $$$a_2 ~ \\& ~ a_4$$$ $$$=$$$ $$$4 ~ \\& ~ 4 = 4$$$. For both operations $$$x = 4$$$, so after the first operation $$$a_1 - x = 0$$$ and $$$a_3 - x = 0$$$, and after the second operation\u00a0\u2014 $$$a_2 - x = 0$$$ and $$$a_4 - x = 0$$$. If $$$k = 3$$$, it's impossible to make all $$$a_i$$$ equal to $$$0$$$. After performing the first operation, we'll get three elements equal to $$$0$$$ and one equal to $$$4$$$. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to $$$0$$$. If $$$k = 4$$$, we can make one operation with set $$$\\{1, 2, 3, 4\\}$$$, because $$$x = a_1 ~ \\& ~ a_2 ~ \\& ~ a_3 ~ \\& ~ a_4$$$ $$$= 4$$$. In the second test case, if $$$k = 2$$$ then we can make the following elimination operations: Operation with indices $$$\\{1, 3\\}$$$: $$$x = a_1 ~ \\& ~ a_3$$$ $$$=$$$ $$$13 ~ \\& ~ 25 = 9$$$. $$$a_1 - x = 13 - 9 = 4$$$ and $$$a_3 - x = 25 - 9 = 16$$$. Array $$$a$$$ will become equal to $$$[4, 7, 16, 19]$$$. Operation with indices $$$\\{3, 4\\}$$$: $$$x = a_3 ~ \\& ~ a_4$$$ $$$=$$$ $$$16 ~ \\& ~ 19 = 16$$$. $$$a_3 - x = 16 - 16 = 0$$$ and $$$a_4 - x = 19 - 16 = 3$$$. Array $$$a$$$ will become equal to $$$[4, 7, 0, 3]$$$. Operation with indices $$$\\{2, 4\\}$$$: $$$x = a_2 ~ \\& ~ a_4$$$ $$$=$$$ $$$7 ~ \\& ~ 3 = 3$$$. $$$a_2 - x = 7 - 3 = 4$$$ and $$$a_4 - x = 3 - 3 = 0$$$. Array $$$a$$$ will become equal to $$$[4, 4, 0, 0]$$$. Operation with indices $$$\\{1, 2\\}$$$: $$$x = a_1 ~ \\& ~ a_2$$$ $$$=$$$ $$$4 ~ \\& ~ 4 = 4$$$. $$$a_1 - x = 4 - 4 = 0$$$ and $$$a_2 - x = 4 - 4 = 0$$$. Array $$$a$$$ will become equal to $$$[0, 0, 0, 0]$$$. Formal definition of bitwise AND:Let's define bitwise AND ($$$\\&$$$) as follows. Suppose we have two non-negative integers $$$x$$$ and $$$y$$$, let's look at their binary representations (possibly, with leading zeroes): $$$x_k \\dots x_2 x_1 x_0$$$ and $$$y_k \\dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of number $$$x$$$, and $$$y_i$$$ is the $$$i$$$-th bit of number $$$y$$$. Let $$$r = x ~ \\& ~ y$$$ is a result of operation $$$\\&$$$ on number $$$x$$$ and $$$y$$$. Then binary representation of $$$r$$$ will be $$$r_k \\dots r_2 r_1 r_0$$$, where:$$$$$$ r_i = \\begin{cases} 1, ~ \\text{if} ~ x_i = 1 ~ \\text{and} ~ y_i = 1 \\\\ 0, ~ \\text{if} ~ x_i = 0 ~ \\text{or} ~ y_i = 0 \\end{cases} $$$$$$"}, "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 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 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[Long](n+1)\n for (i <- 1 to n) {\n arr(i) = readLong()\n }\n var ans = -1\n for (k <- 0 to 32) {\n var cnt = 0\n for (i <- 1 to n) {\n if (arr(i) % 2 == 1)\n cnt += 1\n arr(i) /= 2L\n }\n if (cnt > 0) {\n if (ans == -1)\n ans = cnt\n else\n ans = gcd(ans, cnt)\n }\n }\n if (ans == -1) {\n for (i <- 1 to n) {\n writer.print(i + \" \")\n }\n } else {\n for (i <- 1 to n) {\n if (ans % i == 0)\n writer.print(i + \" \")\n }\n }\n writer.println()\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "81f4bc9ac72ed39da8614131954d0d99"} {"nl": {"description": "Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1,\u20092,\u2009...,\u2009K and the center in the point (z,\u20090) a (K,\u2009z)-set. Thus, on the square were painted a (N,\u2009x)-set and a (M,\u2009y)-set. You have to find out how many parts those sets divided the square into.", "input_spec": "The first line contains integers N,\u2009x,\u2009M,\u2009y. (1\u2009\u2264\u2009N,\u2009M\u2009\u2264\u2009100000,\u2009\u2009-\u2009100000\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009100000,\u2009x\u2009\u2260\u2009y).", "output_spec": "Print the sought number of parts.", "sample_inputs": ["1 0 1 1", "1 0 1 2", "3 3 4 7"], "sample_outputs": ["4", "3", "17"], "notes": "NotePicture for the third sample: "}, "positive_code": [{"source_code": "import math.max\nimport math.min\nobject P040C extends App {\n val param = readLine().split(' ').map(_.toInt)\n var l = param(3) - param(1)\n var n = param(0)\n var m = param(2)\n if (l < 0) {\n l = -l\n n = param(2)\n m = param(0)\n }\n\n var nr: Long = 0\n for (i <- 1 to n) {\n if (i <= l) {\n val nc = max(0, min(m, l+i-1) - (l-i+1) + 1)\n nr += max(2 * nc - 1, 0)\n }\n else {\n val nc = max(0, min(m, l+i-1) - (i-l) + 1);\n nr += max(2 * (nc -1), 0)\n }\n }\n print(n + m + 1 + nr)\n}\n \n"}], "negative_code": [{"source_code": "import math.max\nimport math.min\nobject P040C extends App {\n val param = readLine().split(' ').map(_.toInt)\n var l = param(3) - param(1)\n var n = param(0)\n var m = param(2)\n if (l < 0) {\n l = -l\n n = param(2)\n m = param(0)\n }\n\n var nr = 0\n for (i <- 1 to n) {\n if (i <= l) {\n val nc = max(0, min(m, l+i-1) - (l-i+1) + 1)\n nr += max(2 * nc - 1, 0)\n }\n else {\n val nc = max(0, min(m, l+i-1) - (i-l) + 1);\n nr += max(2 * (nc -1), 0)\n }\n }\n print(n + m + 1 + nr)\n}\n \n"}, {"source_code": "import math.max\nimport math.min\nobject P040C extends App {\n val param = readLine().split(' ').map(_.toInt)\n var l = param(3) - param(1)\n var n = param(0)\n var m = param(2)\n if (l < 0) {\n l = -l\n n = param(2)\n m = param(0)\n }\n\n var nr = 0\n for (i <- 1 to n) {\n val nc = max(0, min(m, l+i-1) - max(0, l-i+1) + 1)\n nr += max(2 * nc - 1, 0)\n }\n print(n + m + 1 + nr)\n}\n \n"}], "src_uid": "ebaf9444531bb6ba6c3322dfa8edb69c"} {"nl": {"description": "Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181\u2009\u2192\u20091945181\u2009\u2192\u2009194519\u2009\u2192\u200919919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.", "input_spec": "The first line of the input contains integer a (1\u2009\u2264\u2009a\u2009\u2264\u200910100000). Number a doesn't have any zeroes.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263\u2009-\u20091. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["369727", "123456789987654321", "1"], "sample_outputs": ["2", "1", "1"], "notes": "NoteNotes to the samplesIn the first sample Inna can get the following numbers: 369727\u2009\u2192\u200999727\u2009\u2192\u20099997, 369727\u2009\u2192\u200999727\u2009\u2192\u20099979.In the second sample, Inna can act like this: 123456789987654321\u2009\u2192\u200912396789987654321\u2009\u2192\u20091239678998769321."}, "positive_code": [{"source_code": "object B extends App {\n\n val as = readLine.map(_ - '0')\n\n var prev = as.head\n var n = BigInt(1)\n var s = BigInt(0)\n \n for (a <- as.tail) {\n if (prev + a == 9) s += 1 \n else if (s > 0) {\n if (s % 2 == 0) n = n * ((s + 2) / 2)\n s = 0 \n }\n prev = a\n }\n \n if (s > 0 && s % 2 == 0) n = n * ((s + 2) / 2)\n \n println(n)\n}"}], "negative_code": [{"source_code": "object B extends App {\n\n val as = readLine.map(_ - '0')\n\n var prev = as.head\n var n = 1\n var s = 0\n \n for (a <- as.tail) {\n if (prev + a == 9) s += 1 \n else if (s > 0) {\n if (s % 2 == 0) n *= s\n s = 0 \n }\n prev = a\n }\n \n if (s > 0 && s % 2 == 0) n *= s\n \n println(n)\n}"}, {"source_code": "object B extends App {\n\n val as = readLine.map(_ - '0')\n\n var prev = as.head\n var n = 1\n var s = 0\n \n for (a <- as.tail) {\n if (prev + a == 9) s += 1 \n else if (s > 0) {\n n *= s\n s = 0 \n }\n prev = a\n }\n \n if (s > 0) n *= s\n \n println(n)\n}"}], "src_uid": "bb1e110a7f53e6f7d43ddced7407f3d1"} {"nl": {"description": "Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.", "input_spec": "First line of input contains an integer $$$t$$$ $$$(1 \\le t \\le 100)$$$ \u00a0\u2014 the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \\le n \\le 10^3)$$$ \u00a0\u2014 the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.", "output_spec": "For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.", "sample_inputs": ["4\n1\n2\n1\n3\n3\n102\n4\n2069"], "sample_outputs": ["2\n1\n1\n2"], "notes": "NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins."}, "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": "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"}, {"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"} {"nl": {"description": "In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings \"abc\" and \"abca\" suit him, while the string \"aba\" doesn't. He also want the number of letters 'c' in his string to be as little as possible.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the length of the string.", "output_spec": "Print the string that satisfies all the constraints. If there are multiple answers, print any of them.", "sample_inputs": ["2", "3"], "sample_outputs": ["aa", "bba"], "notes": "NoteA palindrome is a sequence of characters which reads the same backward and forward."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x,\u2009y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1\u2009000\u2009000.", "input_spec": "The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.", "output_spec": "If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print \"Impossible\". The length of your answer must not exceed 1\u2009000\u2009000.", "sample_inputs": ["1 2 3 4", "1 2 2 1"], "sample_outputs": ["Impossible", "0110"], "notes": null}, "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): 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"}, {"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"} {"nl": {"description": "Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2\u00b7x\u2009+\u20091\u2009\u2264\u2009n) and take a coin from each chest with numbers x, 2\u00b7x, 2\u00b7x\u2009+\u20091. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of chests with coins. The second line contains a sequence of space-separated integers: a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000), where ai is the number of coins in the chest number i at the beginning of the game.", "output_spec": "Print a single integer \u2014 the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.", "sample_inputs": ["1\n1", "3\n1 2 3"], "sample_outputs": ["-1", "3"], "notes": "NoteIn the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.In the second sample there is only one possible move x\u2009=\u20091. This move should be repeated at least 3 times to empty the third chest."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Monocarp has got an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote $$$k$$$ as the mathematic mean of these elements (note that it's possible that $$$k$$$ is not an integer). The mathematic mean of an array of $$$n$$$ elements is the sum of elements divided by the number of these elements (i.\u2009e. sum divided by $$$n$$$).Monocarp wants to delete exactly two elements from $$$a$$$ so that the mathematic mean of the remaining $$$(n - 2)$$$ elements is still equal to $$$k$$$.Your task is to calculate the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in the array. The second line contains a sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^{9}$$$), where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print one integer \u2014 the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).", "sample_inputs": ["4\n4\n8 8 8 8\n3\n50 20 10\n5\n1 4 7 3 5\n7\n1 2 3 4 5 6 7"], "sample_outputs": ["6\n0\n2\n3"], "notes": "NoteIn the first example, any pair of elements can be removed since all of them are equal.In the second example, there is no way to delete two elements so the mathematic mean doesn't change.In the third example, it is possible to delete the elements on positions $$$1$$$ and $$$3$$$, or the elements on positions $$$4$$$ and $$$5$$$."}, "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 val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n)\n var sum = 0L\n for (i <- 0 until n) {\n arr(i) = readInt()\n sum += arr(i).toLong\n }\n val mp = mutable.Map[Double, Int]()\n val mean = sum / n.toDouble\n var cnt = 0L\n var k = 0d\n for (i <- 0 until n) {\n k = arr(i) - mean\n if (mp.contains(-1*k)) {\n cnt += mp(-1*k).toLong\n }\n if (!mp.contains(k))\n mp(k) = 1\n else\n mp(k) += 1\n }\n writer.println(cnt)\n }\n writer.flush()\n}\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 val rem = 1000000007\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 }\n val mp = mutable.Map[Int, Int]()\n val mean = arr.sum / n\n var cnt = 0\n var k = 0\n for (i <- 0 until n) {\n k = arr(i) - mean\n if (mp.contains(-1*k)) {\n cnt += mp(-1*k)\n }\n if (!mp.contains(k))\n mp(k) = 1\n else\n mp(k) += 1\n }\n writer.println(cnt)\n }\n writer.flush()\n}\n"}], "src_uid": "4e9efd8faa7327e37352f2ebccf5945f"} {"nl": {"description": "You are given $$$n$$$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $$$(n-1)$$$ of the given $$$n$$$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.Find any point with integer coordinates that belongs to at least $$$(n-1)$$$ given rectangles.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 132\\,674$$$) \u2014 the number of given rectangles. Each the next $$$n$$$ lines contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9 \\le x_1 < x_2 \\le 10^9$$$, $$$-10^9 \\le y_1 < y_2 \\le 10^9$$$) \u2014 the coordinates of the bottom left and upper right corners of a rectangle.", "output_spec": "Print two integers $$$x$$$ and $$$y$$$ \u2014 the coordinates of any point that belongs to at least $$$(n-1)$$$ given rectangles.", "sample_inputs": ["3\n0 0 1 1\n1 1 2 2\n3 0 4 1", "3\n0 0 1 1\n0 1 1 2\n1 0 2 1", "4\n0 0 5 5\n0 0 4 4\n1 1 4 4\n1 1 4 4", "5\n0 0 10 8\n1 2 6 7\n2 3 5 6\n3 4 4 5\n8 1 9 2"], "sample_outputs": ["1 1", "1 1", "1 1", "3 4"], "notes": "NoteThe picture below shows the rectangles in the first and second samples. The possible answers are highlighted. The picture below shows the rectangles in the third and fourth samples. "}, "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 case class Rect(l: Int, b: Int, r: Int, t: Int) {\n def add(that: Rect) = {\n Rect(max(l, that.l), max(b, that.b), min(r, that.r), min(t, that.t))\n }\n\n def isValid = l <= r && b <= t\n }\n val A = Array.ofDim[Rect](N)\n REP(N) { i =>\n val l, b, r, t = ni()\n A(i) = Rect(l, b, r, t)\n }\n\n val Zero = Rect(-1e9.toInt, -1e9.toInt, 1e9.toInt, 1e9.toInt)\n val L, R = Array.ofDim[Rect](N + 2)\n L(0) = Zero\n R(N + 1) = Zero\n REP(N) { i =>\n L(i + 1) = A(i).add(L(i))\n }\n\n REP_r(N) { i =>\n R(i + 1) = A(i).add(R(i + 2))\n }\n\n val rect = map(N) { i =>\n L(i).add(R(i + 2))\n }.find(_.isValid).get\n out.println(s\"${rect.l} ${rect.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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)\n def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {\n val A1, A2 = Array.ofDim[Int](n)\n REP(n) { i =>\n A1(i) = ni() + offset\n A2(i) = ni() + offset\n }\n (A1, A2)\n }\n def nm(n: Int, m: Int): Array[Array[Int]] = {\n val A = Array.ofDim[Int](n, m)\n REP(n) { i =>\n REP(m) { j =>\n A(i)(j) = ni()\n }\n }\n A\n }\n def 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": "6b049bd466b050f2dd0a305a381bc0bf"} {"nl": {"description": "Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \\le i \\le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to: Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\\{0,1,...,n - 1\\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.", "input_spec": "The first line contains an integer $$$n$$$ ($$$3 \\le n \\le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.", "sample_inputs": ["3\n1 3 2", "3\n1000000000 1000000000 1000000000"], "sample_outputs": ["1", "1999982505"], "notes": "NoteIn the first example, we first reorder $$$\\{1, 3, 2\\}$$$ into $$$\\{1, 2, 3\\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\\{1, 2, 4\\}$$$."}, "positive_code": [{"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 m = in.nextInt()\n val data = in.nextLineInt(m).sorted\n val lastIndex = m - 1\n val max = data(lastIndex)\n\n val base1 = math.ceil(math.pow(max, 1d / lastIndex)).toInt\n val base2 = math.floor(math.pow(max, 1d / lastIndex)).toInt\n\n var sum1 = 0d\n var sum2 = 0d\n var i = 0\n\n data.foreach(d => {\n val cur1 = Math.pow(base1, i)\n sum1 += Math.abs(d - cur1)\n\n val cur2 = Math.pow(base2, i)\n sum2 += Math.abs(d - cur2)\n i += 1\n })\n printf(\"%.0f\\n\", math.min(sum1, sum2))\n// println(math.min(sum1, sum2))\n }\n // 2000017493\n // 1999982505\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": "\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 m = in.nextInt()\n val data = in.nextLineInt(m)\n val max = data.max\n// val base = test3(20, 2)\n val base = test3(max, m - 1)\n var sum = 0L\n var i = 0\n // 1420172\n // 104639754\n // 83377718\n// println(base)\n data.sorted.foreach(d => {\n val cur = Math.pow(base, i)\n sum += Math.abs(cur - d).toLong\n i += 1\n })\n println(sum)\n }\n // 2000017493\n // 1999982505\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 test3(number: Int, e: Int) = {\n val sqrtNumber = Math.ceil(Math.sqrt(number)).toInt\n var minDiff = Integer.MAX_VALUE.toDouble\n\n var targetExp = 1\n var targetBase = 2\n 1.to(sqrtNumber)\n .foreach(b => {\n val powerNumber = Math.pow(b, e)\n if (Math.abs(number.toDouble - powerNumber) < minDiff) {\n minDiff = number - powerNumber\n targetBase = b\n targetExp = e\n }\n })\n// println(targetBase, targetExp)\n targetBase\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 m = in.nextInt()\n val data = in.nextLineInt(m)\n val max = data.max\n val base = test3(max, m - 1)\n var sum = 0L\n var i = 0\n// println(base)\n data.sorted.foreach(d => {\n val cur = Math.pow(base, i)\n sum += Math.abs(cur - d).toLong\n i += 1\n })\n println(sum)\n }\n // 2000017493\n // 1999982505\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 test3(number: Int, e: Int) = {\n val sqrtNumber = Math.sqrt(number).toInt\n var minDiff = Integer.MAX_VALUE\n\n var targetExp = 1\n var targetBase = 2\n 2.until(sqrtNumber + 2)\n .foreach(b => {\n val powerNumber = Math.pow(b, e).toInt\n if (Math.abs(number - powerNumber) <= minDiff) {\n minDiff = number - powerNumber\n targetBase = b\n targetExp = e\n }\n })\n// println(targetBase, targetExp)\n targetBase\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 m = in.nextInt()\n val data = in.nextLineInt(m)\n val max = data.max\n val base = test3(max, m - 1)\n var sum = 0L\n var i = 0\n// println(base)\n data.sorted.foreach(d => {\n val cur = Math.pow(base, i)\n sum += Math.abs(cur - d).toLong\n i += 1\n })\n println(sum)\n }\n // 2000017493\n // 1999982505\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 test3(number: Int, e: Int) = {\n val sqrtNumber = Math.ceil(Math.sqrt(number)).toInt\n var minDiff = Integer.MAX_VALUE\n\n var targetExp = 1\n var targetBase = 2\n 1.to(sqrtNumber)\n .foreach(b => {\n val powerNumber = Math.pow(b, e).toInt\n if (Math.abs(number - powerNumber) <= minDiff) {\n minDiff = number - powerNumber\n targetBase = b\n targetExp = e\n }\n })\n// println(targetBase, targetExp)\n targetBase\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 m = in.nextInt()\n val data = in.nextLineInt(m).sorted\n val lastIndex = m - 1\n val max = data(lastIndex)\n\n val base1 = math.ceil(math.pow(max, 1d / lastIndex)).toInt\n val base2 = math.floor(math.pow(max, 1d / lastIndex)).toInt\n\n var sum1 = 0L\n var sum2 = 0L\n var i = 0\n\n data.foreach(d => {\n val cur1 = Math.pow(base1, i)\n sum1 += Math.abs(d - cur1).toLong\n\n val cur2 = Math.pow(base2, i)\n sum2 += Math.abs(d - cur2).toLong\n i += 1\n })\n println(math.min(sum1, sum2))\n }\n // 2000017493\n // 1999982505\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": "54e9c6f24c430c5124d840b5a65a1bc4"} {"nl": {"description": "An array of integers $$$p_{1},p_{2}, \\ldots,p_{n}$$$ is called a permutation if it contains each number from $$$1$$$ to $$$n$$$ exactly once. For example, the following arrays are permutations: $$$[3,1,2], [1], [1,2,3,4,5]$$$ and $$$[4,3,1,2]$$$. The following arrays are not permutations: $$$[2], [1,1], [2,3,4]$$$.There is a hidden permutation of length $$$n$$$.For each index $$$i$$$, you are given $$$s_{i}$$$, which equals to the sum of all $$$p_{j}$$$ such that $$$j < i$$$ and $$$p_{j} < p_{i}$$$. In other words, $$$s_i$$$ is the sum of elements before the $$$i$$$-th element that are smaller than the $$$i$$$-th element.Your task is to restore the permutation.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^{5}$$$)\u00a0\u2014 the size of the permutation. The second line contains $$$n$$$ integers $$$s_{1}, s_{2}, \\ldots, s_{n}$$$ ($$$0 \\le s_{i} \\le \\frac{n(n-1)}{2}$$$). It is guaranteed that the array $$$s$$$ corresponds to a valid permutation of length $$$n$$$.", "output_spec": "Print $$$n$$$ integers $$$p_{1}, p_{2}, \\ldots, p_{n}$$$ \u2014 the elements of the restored permutation. We can show that the answer is always unique.", "sample_inputs": ["3\n0 0 0", "2\n0 1", "5\n0 1 1 1 10"], "sample_outputs": ["3 2 1", "1 2", "1 4 3 2 5"], "notes": "NoteIn the first example for each $$$i$$$ there is no index $$$j$$$ satisfying both conditions, hence $$$s_i$$$ are always $$$0$$$.In the second example for $$$i = 2$$$ it happens that $$$j = 1$$$ satisfies the conditions, so $$$s_2 = p_1$$$.In the third example for $$$i = 2, 3, 4$$$ only $$$j = 1$$$ satisfies the conditions, so $$$s_2 = s_3 = s_4 = 1$$$. For $$$i = 5$$$ all $$$j = 1, 2, 3, 4$$$ are possible, so $$$s_5 = p_1 + p_2 + p_3 + p_4 = 10$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\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 \u304cLong\u3068\u304b\u3058\u3083\u306a\u3044\u5834\u5408\u306f\u3053\u308c\u3089\u3092\u5b9f\u88c5\u3057\u306a\u3044\u3068\u4e0b\u306e\u5974\u3089\u304c\u4f7f\u3048\u306a\u3044\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\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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations: Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases. ", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5; 1 \\le k \\le 10^9$$$) \u2014 the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.", "sample_inputs": ["5\n4 3\n1 2 1 3\n10 6\n8 7 1 8 3 7 5 10 8 9\n5 10\n20 100 50 20 100500\n10 25\n24 24 24 24 24 24 24 24 24 24\n8 8\n1 2 3 4 5 6 7 8"], "sample_outputs": ["6\n18\n0\n227\n8"], "notes": "NoteConsider the first test case of the example: $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$; $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$; $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$; $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$; $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$; $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$; $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once."}, "positive_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(_.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"}, {"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"} {"nl": {"description": "The Central Company has an office with a sophisticated security system. There are $$$10^6$$$ employees, numbered from $$$1$$$ to $$$10^6$$$.The security system logs entrances and departures. The entrance of the $$$i$$$-th employee is denoted by the integer $$$i$$$, while the departure of the $$$i$$$-th employee is denoted by the integer $$$-i$$$.The company has some strict rules about access to its office: An employee can enter the office at most once per day. He obviously can't leave the office if he didn't enter it earlier that day. In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day. Any array of events satisfying these conditions is called a valid day.Some examples of valid or invalid days: $$$[1, 7, -7, 3, -1, -3]$$$ is a valid day ($$$1$$$ enters, $$$7$$$ enters, $$$7$$$ leaves, $$$3$$$ enters, $$$1$$$ leaves, $$$3$$$ leaves). $$$[2, -2, 3, -3]$$$ is also a valid day. $$$[2, 5, -5, 5, -5, -2]$$$ is not a valid day, because $$$5$$$ entered the office twice during the same day. $$$[-4, 4]$$$ is not a valid day, because $$$4$$$ left the office without being in it. $$$[4]$$$ is not a valid day, because $$$4$$$ entered the office and didn't leave it before the end of the day. There are $$$n$$$ events $$$a_1, a_2, \\ldots, a_n$$$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.You must partition (to cut) the array $$$a$$$ of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.For example, if $$$n=8$$$ and $$$a=[1, -1, 1, 2, -1, -2, 3, -3]$$$ then he can partition it into two contiguous subarrays which are valid days: $$$a = [1, -1~ \\boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$$$.Help the administrator to partition the given array $$$a$$$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^6 \\le a_i \\le 10^6$$$ and $$$a_i \\neq 0$$$).", "output_spec": "If there is no valid partition, print $$$-1$$$. Otherwise, print any valid partition in the following format: On the first line print the number $$$d$$$ of days ($$$1 \\le d \\le n$$$). On the second line, print $$$d$$$ integers $$$c_1, c_2, \\ldots, c_d$$$ ($$$1 \\le c_i \\le n$$$ and $$$c_1 + c_2 + \\ldots + c_d = n$$$), where $$$c_i$$$ is the number of events in the $$$i$$$-th day. If there are many valid solutions, you can print any of them. You don't have to minimize nor maximize the number of days.", "sample_inputs": ["6\n1 7 -7 3 -1 -3", "8\n1 -1 1 2 -1 -2 3 -3", "6\n2 5 -5 5 -5 -2", "3\n-8 1 1"], "sample_outputs": ["1\n6", "2\n2 6", "-1", "-1"], "notes": "NoteIn the first example, the whole array is a valid day.In the second example, one possible valid solution is to split the array into $$$[1, -1]$$$ and $$$[1, 2, -1, -2, 3, -3]$$$ ($$$d = 2$$$ and $$$c = [2, 6]$$$). The only other valid solution would be to split the array into $$$[1, -1]$$$, $$$[1, 2, -1, -2]$$$ and $$$[3, -3]$$$ ($$$d = 3$$$ and $$$c = [2, 4, 2]$$$). Both solutions are accepted.In the third and fourth examples, we can prove that there exists no valid solution. Please note that the array given in input is not guaranteed to represent a coherent set of events."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Bob has a string $$$s$$$ consisting of lowercase English letters. He defines $$$s'$$$ to be the string after removing all \"a\" characters from $$$s$$$ (keeping all other characters in the same order). He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example).You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique.", "input_spec": "The first line of input contains a string $$$t$$$ ($$$1 \\leq |t| \\leq 10^5$$$) consisting of lowercase English letters.", "output_spec": "Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print \":(\" (without double quotes, there is no space between the characters).", "sample_inputs": ["aaaaa", "aacaababc", "ababacacbbcc", "baba"], "sample_outputs": ["aaaaa", ":(", "ababacac", ":("], "notes": "NoteIn the first example, we have $$$s = $$$ \"aaaaa\", and $$$s' = $$$ \"\".In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$.In the third example, we have $$$s = $$$ \"ababacac\", and $$$s' = $$$ \"bbcc\", and $$$t = s + s' = $$$ \"ababacacbbcc\"."}, "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 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"}, {"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"} {"nl": {"description": "Two players decided to play one interesting card game.There is a deck of $$$n$$$ cards, with values from $$$1$$$ to $$$n$$$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that $$$n = 5$$$, the first player has cards with values $$$2$$$ and $$$3$$$, and the second player has cards with values $$$1$$$, $$$4$$$, $$$5$$$. Then one possible flow of the game is:The first player chooses the card $$$3$$$. The second player chooses the card $$$1$$$. As $$$3>1$$$, the first player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$, $$$3$$$, the second player has cards $$$4$$$, $$$5$$$.The first player chooses the card $$$3$$$. The second player chooses the card $$$4$$$. As $$$3<4$$$, the second player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$. The second player has cards $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$1$$$. The second player chooses the card $$$3$$$. As $$$1<3$$$, the second player gets both cards. Now the first player has only the card $$$2$$$. The second player has cards $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$2$$$. The second player chooses the card $$$4$$$. As $$$2<4$$$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$, $$$k_2$$$ ($$$2 \\le n \\le 100, 1 \\le k_1 \\le n - 1, 1 \\le k_2 \\le n - 1, k_1 + k_2 = n$$$)\u00a0\u2014 the number of cards, number of cards owned by the first player and second player correspondingly. The second line of each test case contains $$$k_1$$$ integers $$$a_1, \\dots, a_{k_1}$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the values of cards of the first player. The third line of each test case contains $$$k_2$$$ integers $$$b_1, \\dots, b_{k_2}$$$ ($$$1 \\le b_i \\le n$$$)\u00a0\u2014 the values of cards of the second player. It is guaranteed that the values of all cards are different.", "output_spec": "For each test case, output \"YES\" in a separate line, if the first player wins. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).", "sample_inputs": ["2\n2 1 1\n2\n1\n5 2 3\n2 3\n1 4 5"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first test case of the example, there is only one possible move for every player: the first player will put $$$2$$$, the second player will put $$$1$$$. $$$2>1$$$, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "3ef23f114be223255bd10131b2375b86"} {"nl": {"description": "One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?", "input_spec": "The first line contains two integers n and b (1\u2009\u2264\u2009n,\u2009b\u2009\u2264\u20092000) \u2014 the number of days and the initial number of money in bourles. The next line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20092000) \u2014 the prices of Martian dollars.", "output_spec": "Print the single number \u2014 which maximal sum of money in bourles can Vasya get by the end of day n.", "sample_inputs": ["2 4\n3 7", "4 10\n4 3 2 1", "4 10\n4 2 3 1"], "sample_outputs": ["8", "10", "15"], "notes": null}, "positive_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 Array(n, b) = readLine.split(\" \").map(_.toInt);\n var a = readLine.split(\" \").map(_.toInt);\n var best = b;\n for (i <- 0 until a.length; j <- i + 1 until a.length) {\n var countM = b / a(i);\n var mod = b % a(i);\n best = math.max(best, countM * a(j) + mod);\n }\n println(best);\n } \n}"}], "negative_code": [], "src_uid": "2c9133650d831fa6ab4c11661bcb9cbb"} {"nl": {"description": "Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot.The robot has instructions \u2014 the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move.Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once \u2014 at its last move. Moreover, the latter move cannot be skipped.Let's assume that k is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose k obstacles and the finishing cell so that the robot is able to complete the instructions successfully.", "input_spec": "The first line contains a sequence of characters without spaces s1s2... sn (1\u2009\u2264\u2009n\u2009\u2264\u2009106), consisting only of letters \"L\" and \"R\". If character si equals \"L\", then the robot on the i-th move must try to move one cell to the left. If the si-th character equals \"R\", then the robot on the i-th move must try to move one cell to the right.", "output_spec": "Print a single integer \u2014 the required number of ways. It's guaranteed that this number fits into 64-bit signed integer type.", "sample_inputs": ["RR", "RRL"], "sample_outputs": ["1", "1"], "notes": "NoteIn the first sample Valera mustn't add any obstacles and his finishing cell must be cell 2.In the second sample, Valera must add an obstacle in cell number 1, and his finishing cell must be cell number \u2009-\u20091. In this case robot skips the first two moves and on the third move he goes straight from the starting cell to the finishing one. But if Valera doesn't add any obstacles, or adds an obstacle to another cell, then the robot visits the finishing cell more than once."}, "positive_code": [{"source_code": "object Main {\n def inverse(ch: Char) = {\n ch match {\n case 'R' => 'L'\n case 'L' => 'R'\n }\n }\n\n def check(s: String, tape: Array[Int]) = {\n var pointer = s.length\n for (ch <- s) {\n if (ch == 'L') {\n if (tape(pointer - 1) != -1) {\n tape(pointer - 1) += 1\n pointer -= 1\n }\n }\n else if (ch == 'R') {\n if (tape(pointer + 1) != -1) {\n tape(pointer + 1) += 1\n pointer += 1\n }\n }\n }\n if (pointer != s.length && tape(pointer) == 1) true else false\n }\n\n def main(args: Array[String]) {\n val in = readLine()\n\n val s = if (in.last == 'L') in.map(inverse) else in\n\n var tape = new Array[Int](2 * s.length + 1)\n if (check(s, tape)) {\n println(\"1\")\n return\n }\n\n var l = 0\n var r = s.length\n var ans = 0\n while (l < r) {\n tape = new Array[Int](2 * s.length + 1)\n var m = (l + r) / 2\n tape(m) = -1\n if (check(s, tape)) {\n r = m\n ans = s.length - m\n }\n else {\n l = m + 1\n }\n }\n println(ans)\n }\n}\n"}], "negative_code": [], "src_uid": "4ac27e2dca63dab78853540bb6af723d"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$. You want to split it into exactly $$$k$$$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i.\u2009e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $$$n$$$ elements of the array $$$a$$$ must belong to exactly one of the $$$k$$$ subsegments.Let's see some examples of dividing the array of length $$$5$$$ into $$$3$$$ subsegments (not necessarily with odd sums): $$$[1, 2, 3, 4, 5]$$$ is the initial array, then all possible ways to divide it into $$$3$$$ non-empty non-intersecting subsegments are described below: $$$[1], [2], [3, 4, 5]$$$; $$$[1], [2, 3], [4, 5]$$$; $$$[1], [2, 3, 4], [5]$$$; $$$[1, 2], [3], [4, 5]$$$; $$$[1, 2], [3, 4], [5]$$$; $$$[1, 2, 3], [4], [5]$$$. Of course, it can be impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements. In this case print \"NO\". Otherwise, print \"YES\" and any possible division of the array. See the output format for the detailed explanation.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in the array and the number of subsegments, respectively. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each query, print the answer to it. If it is impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements, print \"NO\" in the first line. Otherwise, print \"YES\" in the first line and any possible division of the array in the second line. The division can be represented as $$$k$$$ integers $$$r_1$$$, $$$r_2$$$, ..., $$$r_k$$$ such that $$$1 \\le r_1 < r_2 < \\dots < r_k = n$$$, where $$$r_j$$$ is the right border of the $$$j$$$-th segment (the index of the last element that belongs to the $$$j$$$-th segment), so the array is divided into subsegments $$$[1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \\dots, [r_{k - 1} + 1, n]$$$. Note that $$$r_k$$$ is always $$$n$$$ but you should print it anyway. ", "sample_inputs": ["3\n5 3\n7 18 3 14 1\n5 4\n1 2 3 4 5\n6 2\n1 2 8 4 10 2"], "sample_outputs": ["YES\n1 3 5\nNO\nNO"], "notes": null}, "positive_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.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"}, {"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"} {"nl": {"description": "Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.For each opponent Arya knows his schedule\u00a0\u2014 whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.", "input_spec": "The first line of the input contains two integers n and d (1\u2009\u2264\u2009n,\u2009d\u2009\u2264\u2009100)\u00a0\u2014 the number of opponents and the number of days, respectively. The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.", "output_spec": "Print the only integer\u00a0\u2014 the maximum number of consecutive days that Arya will beat all present opponents.", "sample_inputs": ["2 2\n10\n00", "4 1\n0100", "4 5\n1101\n1111\n0110\n1011\n1111"], "sample_outputs": ["2", "1", "2"], "notes": "NoteIn the first and the second samples, Arya will beat all present opponents each of the d days.In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4."}, "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._\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}"}, {"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"} {"nl": {"description": "You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print the answer \u2014 the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.", "sample_inputs": ["5\n10 4\n13 9\n100 13\n123 456\n92 46"], "sample_outputs": ["2\n5\n4\n333\n0"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "d9fd10700cb122b148202a664e7f7689"} {"nl": {"description": "Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.Artem wants to paint an $$$n \\times m$$$ board. Each cell of the board should be colored in white or black. Lets $$$B$$$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $$$W$$$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if $$$B = W + 1$$$. The first coloring shown below has $$$B=5$$$ and $$$W=4$$$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has $$$B=4$$$, $$$W=4$$$ (only the bottom right cell doesn't have a neighbor with the opposite color). Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 20$$$). Each of the next $$$t$$$ lines contains two integers $$$n, m$$$ ($$$2 \\le n,m \\le 100$$$)\u00a0\u2014 the number of rows and the number of columns in the grid.", "output_spec": "For each test case print $$$n$$$ lines, each of length $$$m$$$, where $$$i$$$-th line is the $$$i$$$-th row of your colored matrix (cell labeled with 'B' means that the cell is black, and 'W' means white). Do not use quotes. It's guaranteed that under given constraints the solution always exists.", "sample_inputs": ["2\n3 2\n3 3"], "sample_outputs": ["BW\nWB\nBB\nBWB\nBWW\nBWB"], "notes": "NoteIn the first testcase, $$$B=3$$$, $$$W=2$$$.In the second testcase, $$$B=5$$$, $$$W=4$$$. You can see the coloring in the statement."}, "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 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}"}, {"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"} {"nl": {"description": "Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers $$$d, m$$$, find the number of arrays $$$a$$$, satisfying the following constraints: The length of $$$a$$$ is $$$n$$$, $$$n \\ge 1$$$ $$$1 \\le a_1 < a_2 < \\dots < a_n \\le d$$$ Define an array $$$b$$$ of length $$$n$$$ as follows: $$$b_1 = a_1$$$, $$$\\forall i > 1, b_i = b_{i - 1} \\oplus a_i$$$, where $$$\\oplus$$$ is the bitwise exclusive-or (xor). After constructing an array $$$b$$$, the constraint $$$b_1 < b_2 < \\dots < b_{n - 1} < b_n$$$ should hold. Since the number of possible arrays may be too large, you need to find the answer modulo $$$m$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) denoting the number of test cases in the input. Each of the next $$$t$$$ lines contains two integers $$$d, m$$$ ($$$1 \\leq d, m \\leq 10^9$$$). Note that $$$m$$$ is not necessary the prime!", "output_spec": "For each test case, print the number of arrays $$$a$$$, satisfying all given constrains, modulo $$$m$$$.", "sample_inputs": ["10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1"], "sample_outputs": ["1\n3\n5\n11\n17\n23\n29\n59\n89\n0"], "notes": null}, "positive_code": [{"source_code": "object D extends App {\n case class Case(d: Int, m: Int)\n\n implicit def arr2case(arr: Array[Int]): Case = arr match {\n case Array(d, m) => Case(d, m)\n case _ => throw new IllegalArgumentException\n }\n\n private def numberOfChoices(c: Case): Long = {\n val Case(d, m) = c\n\n val r = Stream\n .iterate(0)(_ + 1)\n .takeWhile(i => (1 << i) <= d)\n .foldLeft(1L) { (acc, i) =>\n val l = 1 << i\n val r = d min ((l << 1) - 1)\n\n (acc * (r - l + 2) % m)\n } - 1\n\n if (r < 0) r + m\n else r\n }\n\n val t = scala.io.StdIn.readInt()\n\n val cs = (0 until t)\n .foldLeft(List.empty[Case]) { (cs, _) =>\n val c = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n c :: cs\n }\n .reverse\n\n val ns = cs.map(numberOfChoices)\n\n ns.foreach(println)\n}"}], "negative_code": [{"source_code": "object D extends App {\n case class Case(d: Int, m: Int)\n\n implicit def arr2case(arr: Array[Int]): Case = arr match {\n case Array(d, m) => Case(d, m)\n case _ => throw new IllegalArgumentException\n }\n\n private def numberOfChoices(c: Case): Long = {\n val Case(d, m) = c\n\n (Stream.iterate(0)(_ + 1).takeWhile(i => (1 << i) <= d).foldLeft(1L) {\n (acc, i) =>\n val l = math.pow(2, i)\n val r = d min (math.pow(2, i + 1) - 1).toInt\n\n (acc * (r - l + 2) % m).toLong\n } - 1) max 0\n }\n\n val t = scala.io.StdIn.readInt()\n\n val cs = (0 until t)\n .foldLeft(List.empty[Case]) { (cs, _) =>\n val c = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n c :: cs\n }\n .reverse\n\n val ns = cs.map(numberOfChoices)\n\n ns.foreach(println)\n}"}, {"source_code": "object D extends App {\n case class Case(d: Int, m: Int)\n\n implicit def arr2case(arr: Array[Int]): Case = arr match {\n case Array(d, m) => Case(d, m)\n case _ => throw new IllegalArgumentException\n }\n\n private def numberOfChoices(c: Case): Long = {\n val Case(d, m) = c\n\n (Stream.iterate(0)(_ + 1).takeWhile(i => (1 << i) < d).foldLeft(1L) {\n (acc, i) =>\n val l = math.pow(2, i)\n val r = d min (math.pow(2, i + 1) - 1).toInt\n\n (acc * (r - l + 2) % m).toLong\n } - 1) max 0\n }\n\n val t = scala.io.StdIn.readInt()\n\n val cs = (0 until t)\n .foldLeft(List.empty[Case]) { (cs, _) =>\n val c = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n c :: cs\n }\n .reverse\n\n val ns = cs.map(numberOfChoices)\n\n ns.foreach(println)\n}"}], "src_uid": "12157ec4a71f0763a898172b38ff1ef2"} {"nl": {"description": "Try guessing the statement from this picture: You are given a non-negative integer $$$d$$$. You have to find two non-negative real numbers $$$a$$$ and $$$b$$$ such that $$$a + b = d$$$ and $$$a \\cdot b = d$$$.", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of test cases. Each test case contains one integer $$$d$$$ $$$(0 \\le d \\le 10^3)$$$.", "output_spec": "For each test print one line. If there is an answer for the $$$i$$$-th test, print \"Y\", and then the numbers $$$a$$$ and $$$b$$$. If there is no answer for the $$$i$$$-th test, print \"N\". Your answer will be considered correct if $$$|(a + b) - a \\cdot b| \\le 10^{-6}$$$ and $$$|(a + b) - d| \\le 10^{-6}$$$.", "sample_inputs": ["7\n69\n0\n1\n4\n5\n999\n1000"], "sample_outputs": ["Y 67.985071301 1.014928699\nY 0.000000000 0.000000000\nN\nY 2.000000000 2.000000000\nY 3.618033989 1.381966011\nY 997.998996990 1.001003010\nY 998.998997995 1.001002005"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to hi. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition hi\u2009\u2264\u2009hi\u2009+\u20091 holds for all i from 1 to n\u2009-\u20091.Squidward suggested the following process of sorting castles: Castles are split into blocks\u00a0\u2014 groups of consecutive castles. Therefore the block from i to j will include castles i,\u2009i\u2009+\u20091,\u2009...,\u2009j. A block may consist of a single castle. The partitioning is chosen in such a way that every castle is a part of exactly one block. Each block is sorted independently from other blocks, that is the sequence hi,\u2009hi\u2009+\u20091,\u2009...,\u2009hj becomes sorted. The partitioning should satisfy the condition that after each block is sorted, the sequence hi becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of castles Spongebob, Patrick and Squidward made from sand during the day. The next line contains n integers hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009109). The i-th of these integers corresponds to the height of the i-th castle.", "output_spec": "Print the maximum possible number of blocks in a valid partitioning.", "sample_inputs": ["3\n1 2 3", "4\n2 1 3 2"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first sample the partitioning looks like that: [1][2][3]. In the second sample the partitioning is: [2, 1][3, 2] "}, "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 sorted = data.sorted\n val res = data.zip(sorted).foldLeft(0, Map.empty[Int, Int], Map.empty[Int, Int]) {\n case ((blocks, m1, m2), (el1, el2)) if m1.isEmpty && el1 == el2 => (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 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"}, {"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"}, {"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 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"} {"nl": {"description": "Find the minimum area of a square land on which you can place two identical rectangular $$$a \\times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally, You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 100$$$)\u00a0\u2014 positive integers (you are given just the sizes, but not their positions). Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding. The picture shows a square that contains red and green rectangles. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)\u00a0\u2014the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \\le a, b \\le 100$$$)\u00a0\u2014 side lengths of the rectangles.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer must be a single integer\u00a0\u2014 minimal area of square land, that contains two rectangles with dimensions $$$a \\times b$$$.", "sample_inputs": ["8\n3 2\n4 2\n1 1\n3 1\n4 7\n1 3\n7 4\n100 100"], "sample_outputs": ["16\n16\n4\n9\n64\n9\n64\n40000"], "notes": "NoteBelow are the answers for the first two test cases: "}, "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": "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"}, {"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"} {"nl": {"description": "On a circle lie $$$2n$$$ distinct points, with the following property: however you choose $$$3$$$ chords that connect $$$3$$$ disjoint pairs of points, no point strictly inside the circle belongs to all $$$3$$$ chords. The points are numbered $$$1, \\, 2, \\, \\dots, \\, 2n$$$ in clockwise order.Initially, $$$k$$$ chords connect $$$k$$$ pairs of points, in such a way that all the $$$2k$$$ endpoints of these chords are distinct.You want to draw $$$n - k$$$ additional chords that connect the remaining $$$2(n - k)$$$ points (each point must be an endpoint of exactly one chord).In the end, let $$$x$$$ be the total number of intersections among all $$$n$$$ chords. Compute the maximum value that $$$x$$$ can attain if you choose the $$$n - k$$$ chords optimally.Note that the exact position of the $$$2n$$$ points is not relevant, as long as the property stated in the first paragraph holds.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$0 \\le k \\le n$$$) \u2014 half the number of points and the number of chords initially drawn. Then $$$k$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, \\, y_i \\le 2n$$$, $$$x_i \\ne y_i$$$) \u2014 the endpoints of the $$$i$$$-th chord. It is guaranteed that the $$$2k$$$ numbers $$$x_1, \\, y_1, \\, x_2, \\, y_2, \\, \\dots, \\, x_k, \\, y_k$$$ are all distinct.", "output_spec": "For each test case, output the maximum number of intersections that can be obtained by drawing $$$n - k$$$ additional chords.", "sample_inputs": ["4\n4 2\n8 2\n1 5\n1 1\n2 1\n2 0\n10 6\n14 6\n2 20\n9 10\n13 18\n15 12\n11 7"], "sample_outputs": ["4\n0\n1\n14"], "notes": "NoteIn the first test case, there are three ways to draw the $$$2$$$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones): We see that the third way gives the maximum number of intersections, namely $$$4$$$.In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.In the third test case, we can make at most one intersection by drawing chords $$$1-3$$$ and $$$2-4$$$, as shown below: "}, "positive_code": [{"source_code": "object C1552 {\n import scala.collection.mutable\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, k) = (int(), int())\n val pair: ArrayBuffer[Int] = ArrayBuffer.fill(2 * n)(-1)\n (0 until k).foreach { _ =>\n val (x, y) = (int() - 1, int() - 1)\n pair(x) = y\n pair(y) = x\n }\n val free = pair.zipWithIndex.filter { case (p, _) => p == -1}.map(_._2)\n val freePairs = free.size / 2\n for (i <- 0 until freePairs) {\n pair(free(i)) = free(i + freePairs)\n pair(free(i + freePairs)) = free(i)\n }\n val set = new mutable.TreeSet[Int]()\n var cnt: Long = 0\n pair.zipWithIndex.foreach { case (p, i) =>\n if (!set.contains(p)) {\n set.add(i)\n } else {\n set.remove(p)\n cnt += set.count(_ > p)\n }\n }\n println(cnt)\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"}], "negative_code": [], "src_uid": "9ca9df1ab3760edb8e7adc3be533c576"} {"nl": {"description": "At many competitions that have a word \u00abcup\u00bb in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.The nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number $$$a$$$ of rows cannot be greater than $$$5$$$ while the number $$$b$$$ of columns cannot exceed $$$20$$$. Every cell of the table will contain either an asterisk (\u00ab*\u00bb) or a letter of user's handle.Furthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks).The organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns.The winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table.", "input_spec": "The only line contains one string $$$s$$$ ($$$1 \\le |s| \\le 100$$$), comprised of uppercase and lowercase Latin letters, \u00a0\u2014 the handle of the winner.", "output_spec": "In the first line output the minimum number $$$a$$$ of rows in the table and the minimum number $$$b$$$ of columns in an optimal table with rows. The following $$$a$$$ lines should contain $$$b$$$ characters each \u00a0\u2014 any valid table.", "sample_inputs": ["tourist", "MyNameIsLifeIAmForeverByYourSideMyNameIsLife"], "sample_outputs": ["1 7\ntourist", "3 15\nMyNameIsLifeIAm\nForeverByYourSi\ndeMyNameIsL*ife"], "notes": null}, "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 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}"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Polycarp is an organizer of a Berland ICPC regional event. There are $$$n$$$ universities in Berland numbered from $$$1$$$ to $$$n$$$. Polycarp knows all competitive programmers in the region. There are $$$n$$$ students: the $$$i$$$-th student is enrolled at a university $$$u_i$$$ and has a programming skill $$$s_i$$$.Polycarp has to decide on the rules now. In particular, the number of members in the team.Polycarp knows that if he chooses the size of the team to be some integer $$$k$$$, each university will send their $$$k$$$ strongest (with the highest programming skill $$$s$$$) students in the first team, the next $$$k$$$ strongest students in the second team and so on. If there are fewer than $$$k$$$ students left, then the team can't be formed. Note that there might be universities that send zero teams.The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is $$$0$$$.Help Polycarp to find the strength of the region for each choice of $$$k$$$ from $$$1$$$ to $$$n$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of universities and the number of students. The second line of each testcase contains $$$n$$$ integers $$$u_1, u_2, \\dots, u_n$$$ ($$$1 \\le u_i \\le n$$$)\u00a0\u2014 the university the $$$i$$$-th student is enrolled at. The third line of each testcase contains $$$n$$$ integers $$$s_1, s_2, \\dots, s_n$$$ ($$$1 \\le s_i \\le 10^9$$$)\u00a0\u2014 the programming skill of the $$$i$$$-th student. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase print $$$n$$$ integers: the strength of the region\u00a0\u2014 the total skill of the members of the present teams\u00a0\u2014 for each choice of team size $$$k$$$.", "sample_inputs": ["4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n3083"], "sample_outputs": ["29 28 26 19 0 0 0 \n24907 20705 22805 9514 0 0 0 0 0 0 \n43 43 43 32 38 43 \n3083"], "notes": "NoteIn the first testcase the teams from each university for each $$$k$$$ are: $$$k=1$$$: university $$$1$$$: $$$[6], [5], [5], [3]$$$; university $$$2$$$: $$$[8], [1], [1]$$$; $$$k=2$$$: university $$$1$$$: $$$[6, 5], [5, 3]$$$; university $$$2$$$: $$$[8, 1]$$$; $$$k=3$$$: university $$$1$$$: $$$[6, 5, 5]$$$; university $$$2$$$: $$$[8, 1, 1]$$$; $$$k=4$$$: university $$$1$$$: $$$[6, 5, 5, 3]$$$; "}, "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 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"}, {"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"} {"nl": {"description": "Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.", "input_spec": "The first input line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of students and the number of subjects, correspondingly. Next n lines each containing m characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.", "output_spec": "Print the single number \u2014 the number of successful students in the given group.", "sample_inputs": ["3 3\n223\n232\n112", "3 5\n91728\n11828\n11111"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.In the second sample test each student is the best at at least one subject."}, "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": "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"}, {"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"} {"nl": {"description": "You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.How many operations will you need to perform until the next operation does not have any points to delete?", "input_spec": "Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc. The number of the points is between 1 and 106.", "output_spec": "Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.", "sample_inputs": ["aabb", "aabcaa"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first test case, the first operation will delete two middle points and leave points \"ab\", which will be deleted with the second operation. There will be no points left to apply the third operation to.In the second test case, the first operation will delete the four points in the middle, leaving points \"aa\". None of them have neighbors of other colors, so the second operation can't be applied."}, "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject D extends App {\n\n case class Segment(var n: Int, c: Char)\n\n val s = readLine\n\n var prev = '-'\n var sameCount = 0\n val segments = ArrayBuffer.empty[Segment]\n\n for (c <- s) {\n if (c == prev) {\n sameCount += 1\n } else {\n if (sameCount > 0) segments += Segment(sameCount, prev)\n prev = c\n sameCount = 1\n }\n }\n\n segments += Segment(sameCount, prev)\n\n var res = 0\n\n while (segments.size > 1) {\n\n res += 1\n\n segments.head.n -= 1\n segments.last.n -= 1\n for (i <- 1 until segments.size - 1) segments(i).n -= 2\n\n val nonEmptySegments = segments.filter(_.n > 0)\n\n segments.clear()\n for (segment <- nonEmptySegments) {\n if (segments.isEmpty || segments.last.c != segment.c) {\n segments += segment\n } else {\n segments.last.n += segment.n\n }\n }\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "a26b23f2b667b7cb3d10f2389fa2cb53"} {"nl": {"description": "Vasya has his favourite number $$$n$$$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $$$d_1, d_2, \\ldots, d_k$$$, such that $$$1 \\leq d_i \\leq 9$$$ for all $$$i$$$ and $$$d_1 + d_2 + \\ldots + d_k = n$$$.Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $$$d_1, d_2, \\ldots, d_k$$$. Help him!", "input_spec": "The first line contains a single integer $$$n$$$\u00a0\u2014 the number that Vasya wants to split ($$$1 \\leq n \\leq 1000$$$).", "output_spec": "In the first line print one integer $$$k$$$\u00a0\u2014 the number of digits in the partition. Note that $$$k$$$ must satisfy the inequality $$$1 \\leq k \\leq n$$$. In the next line print $$$k$$$ digits $$$d_1, d_2, \\ldots, d_k$$$ separated by spaces. All digits must satisfy the inequalities $$$1 \\leq d_i \\leq 9$$$. You should find a partition of $$$n$$$ in which the number of different digits among $$$d_1, d_2, \\ldots, d_k$$$ will be minimal possible among all partitions of $$$n$$$ into non-zero digits. Among such partitions, it is allowed to find any. It is guaranteed that there exists at least one partition of the number $$$n$$$ into digits.", "sample_inputs": ["1", "4", "27"], "sample_outputs": ["1\n1", "2\n2 2", "3\n9 9 9"], "notes": "NoteIn the first test, the number $$$1$$$ can be divided into $$$1$$$ digit equal to $$$1$$$.In the second test, there are $$$3$$$ partitions of the number $$$4$$$ into digits in which the number of different digits is $$$1$$$. This partitions are $$$[1, 1, 1, 1]$$$, $$$[2, 2]$$$ and $$$[4]$$$. Any of these partitions can be found. And, for example, dividing the number $$$4$$$ to the digits $$$[1, 1, 2]$$$ isn't an answer, because it has $$$2$$$ different digits, that isn't the minimum possible number."}, "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 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}"}, {"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"} {"nl": {"description": "Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1\u2009\u2264\u2009i\u2009\u2264\u2009n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: If i\u2009\u2260\u2009n, move from pile i to pile i\u2009+\u20091; If pile located at the position of student is not empty, remove one box from it.GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1,\u2009a2,\u2009... an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty.", "output_spec": "In a single line, print one number, minimum time needed to remove all the boxes in seconds.", "sample_inputs": ["2 1\n1 1", "3 2\n1 0 2", "4 100\n3 4 5 4"], "sample_outputs": ["4", "5", "5"], "notes": "NoteFirst sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second).Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds.Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "ed0a8a10e03de931856e287f9e650e1a"} {"nl": {"description": "Polycarp must pay exactly $$$n$$$ burles at the checkout. He has coins of two nominal values: $$$1$$$ burle and $$$2$$$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.Thus, Polycarp wants to minimize the difference between the count of coins of $$$1$$$ burle and $$$2$$$ burles being used. Help him by determining two non-negative integer values $$$c_1$$$ and $$$c_2$$$ which are the number of coins of $$$1$$$ burle and $$$2$$$ burles, respectively, so that the total value of that number of coins is exactly $$$n$$$ (i.\u2009e. $$$c_1 + 2 \\cdot c_2 = n$$$), and the absolute value of the difference between $$$c_1$$$ and $$$c_2$$$ is as little as possible (i.\u2009e. you must minimize $$$|c_1-c_2|$$$).", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line. This line contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) \u2014 the number of burles to be paid by Polycarp.", "output_spec": "For each test case, output a separate line containing two integers $$$c_1$$$ and $$$c_2$$$ ($$$c_1, c_2 \\ge 0$$$) separated by a space where $$$c_1$$$ is the number of coins of $$$1$$$ burle and $$$c_2$$$ is the number of coins of $$$2$$$ burles. If there are multiple optimal solutions, print any one.", "sample_inputs": ["6\n1000\n30\n1\n32\n1000000000\n5"], "sample_outputs": ["334 333\n10 10\n1 0\n10 11\n333333334 333333333\n1 2"], "notes": "NoteThe answer for the first test case is \"334 333\". The sum of the nominal values of all coins is $$$334 \\cdot 1 + 333 \\cdot 2 = 1000$$$, whereas $$$|334 - 333| = 1$$$. One can't get the better value because if $$$|c_1 - c_2| = 0$$$, then $$$c_1 = c_2$$$ and $$$c_1 \\cdot 1 + c_1 \\cdot 2 = 1000$$$, but then the value of $$$c_1$$$ isn't an integer.The answer for the second test case is \"10 10\". The sum of the nominal values is $$$10 \\cdot 1 + 10 \\cdot 2 = 30$$$ and $$$|10 - 10| = 0$$$, whereas there's no number having an absolute value less than $$$0$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.Mr. Kitayuta wants you to process the following q queries.In the i-th query, he gives you two integers \u2014 ui and vi.Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.", "input_spec": "The first line of the input contains space-separated two integers \u2014 n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers \u2014 ai, bi (1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009n) and ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i\u2009\u2260\u2009j, (ai,\u2009bi,\u2009ci)\u2009\u2260\u2009(aj,\u2009bj,\u2009cj). The next line contains a integer \u2014 q (1\u2009\u2264\u2009q\u2009\u2264\u2009100), denoting the number of the queries. Then follows q lines, containing space-separated two integers \u2014 ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n). It is guaranteed that ui\u2009\u2260\u2009vi.", "output_spec": "For each query, print the answer in a separate line.", "sample_inputs": ["4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4"], "sample_outputs": ["2\n1\n0", "1\n1\n1\n1\n2"], "notes": "NoteLet's consider the first sample. The figure above shows the first sample. Vertex 1 and vertex 2 are connected by color 1 and 2. Vertex 3 and vertex 4 are connected by color 3. Vertex 1 and vertex 4 are not connected by any single color. "}, "positive_code": [{"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}"}, {"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\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"}, {"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}"}], "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"} {"nl": {"description": "You are given a sequence of numbers a1,\u2009a2,\u2009...,\u2009an, and a number m.Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.", "input_spec": "The first line contains two numbers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009106, 2\u2009\u2264\u2009m\u2009\u2264\u2009103) \u2014 the size of the original sequence and the number such that sum should be divisible by it. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "In the single line print either \"YES\" (without the quotes) if there exists the sought subsequence, or \"NO\" (without the quotes), if such subsequence doesn't exist.", "sample_inputs": ["3 5\n1 2 3", "1 6\n5", "4 6\n3 1 1 3", "6 6\n5 5 5 5 5 5"], "sample_outputs": ["YES", "NO", "YES", "YES"], "notes": "NoteIn the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.In the third sample test you need to choose two numbers 3 on the ends.In the fourth sample test you can take the whole subsequence."}, "positive_code": [{"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 }"}, {"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._\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"}, {"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"}], "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"} {"nl": {"description": "One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $$$s$$$ towards a faraway galaxy. Recently they've received a response $$$t$$$ which they believe to be a response from aliens! The scientists now want to check if the signal $$$t$$$ is similar to $$$s$$$.The original signal $$$s$$$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $$$t$$$, however, does not look as easy as $$$s$$$, but the scientists don't give up! They represented $$$t$$$ as a sequence of English letters and say that $$$t$$$ is similar to $$$s$$$ if you can replace all zeros in $$$s$$$ with some string $$$r_0$$$ and all ones in $$$s$$$ with some other string $$$r_1$$$ and obtain $$$t$$$. The strings $$$r_0$$$ and $$$r_1$$$ must be different and non-empty.Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $$$r_0$$$ and $$$r_1$$$) that transform $$$s$$$ to $$$t$$$.", "input_spec": "The first line contains a string $$$s$$$ ($$$2 \\le |s| \\le 10^5$$$) consisting of zeros and ones\u00a0\u2014 the original signal. The second line contains a string $$$t$$$ ($$$1 \\le |t| \\le 10^6$$$) consisting of lowercase English letters only\u00a0\u2014 the received signal. It is guaranteed, that the string $$$s$$$ contains at least one '0' and at least one '1'.", "output_spec": "Print a single integer\u00a0\u2014 the number of pairs of strings $$$r_0$$$ and $$$r_1$$$ that transform $$$s$$$ to $$$t$$$. In case there are no such pairs, print $$$0$$$.", "sample_inputs": ["01\naaaaaa", "001\nkokokokotlin"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first example, the possible pairs $$$(r_0, r_1)$$$ are as follows: \"a\", \"aaaaa\" \"aa\", \"aaaa\" \"aaaa\", \"aa\" \"aaaaa\", \"a\" The pair \"aaa\", \"aaa\" is not allowed, since $$$r_0$$$ and $$$r_1$$$ must be different.In the second example, the following pairs are possible: \"ko\", \"kokotlin\" \"koko\", \"tlin\" "}, "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 def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }\n\n val s, t = readLine\n\n val n = t.length\n val PRIME = 1303L\n val MOD = 1000000007L\n val MODB = BigInt(MOD)\n var pmul = 1L\n\n val ps, pinvs = Array.ofDim[Long](n + 1)\n val hs = Array.ofDim[Long](n + 1)\n\n var h = 0L\n for (i <- 0 to t.length) {\n ps(i) = pmul\n pinvs(i) = BigInt(pmul).modInverse(MODB).toLong\n hs(i) = h\n if (i < n) h = (h + t(i) * pmul) % MOD\n pmul = pmul * PRIME % MOD\n }\n\n def hash(from: Int, until: Int) = (hs(until) - hs(from) + MOD) * pinvs(from) % MOD\n\n val zeros = s.count(_ == '0')\n val ones = s.count(_ == '1')\n val firstZero = s.indexOf('0')\n val firstOne = s.indexOf('1')\n\n var res = 0L\n\n var r0len = 1\n while (r0len <= n) {\n val remain = n.toLong - zeros.toLong * r0len\n if (remain > 0 && remain % ones == 0) {\n val r1len = (remain / ones).toInt\n val r0pos = firstZero * r1len\n val r1pos = firstOne * r0len\n if (r0pos + r0len <= n && r1pos + r1len <= n) {\n val r0hash = hash(r0pos, r0pos + r0len)\n val r1hash = hash(r1pos, r1pos + r1len)\n if (r0hash != r1hash) {\n var pos = 0\n var i = 0\n var ok = true\n while (i < s.length && ok) {\n if (s(i) == '0') {\n if (hash(pos, pos + r0len) != r0hash) ok = false\n pos += r0len\n } else {\n if (hash(pos, pos + r1len) != r1hash) ok = false\n pos += r1len\n }\n i += 1\n }\n //println(r0len, r1len, r0hash, r1hash, ok)\n if (ok) res += 1\n }\n }\n }\n r0len += 1\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "37bef742c08e1969b609e39fd6eb8f69"} {"nl": {"description": "A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared \u2014 the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?", "input_spec": "The first line of the input contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the initial number of compilation errors. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the errors the compiler displayed for the first time. The third line contains n\u2009-\u20091 space-separated integers b1,\u2009b2,\u2009...,\u2009bn\u2009-\u20091 \u2014 the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n\u2009-\u20092 space-separated integers \u04411,\u2009\u04412,\u2009...,\u2009\u0441n\u2009-\u20092 \u2014 the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one. ", "output_spec": "Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively. ", "sample_inputs": ["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"], "sample_outputs": ["8\n123", "1\n3"], "notes": "NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step. "}, "positive_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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.", "output_spec": "Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4\n0 0 1 0", "5\n1 0 1 0 1"], "sample_outputs": ["1", "3"], "notes": "NoteIn the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost."}, "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) / 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}"}, {"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"} {"nl": {"description": "Pavel loves grid mazes. A grid maze is an n\u2009\u00d7\u2009m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500, 0\u2009\u2264\u2009k\u2009<\u2009s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze. Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals \".\", then the corresponding cell is empty and if the character equals \"#\", then the cell is a wall.", "output_spec": "Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as \"X\", the other cells must be left without changes (that is, \".\" and \"#\"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.", "sample_inputs": ["3 4 2\n#..#\n..#.\n#...", "5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#"], "sample_outputs": ["#.X#\nX.#.\n#...", "#XXX\n#X#.\nX#..\n...#\n.#.#"], "notes": null}, "positive_code": [{"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\n val Array(n, m, k) = readInts(3)\n val as = Array.fill(n)(readLine.toCharArray)\n val color = Array.fill(n, m)(0.toByte)\n \n def dfs(i: Int, j: Int, _toAdd: Int): Int = {\n \n if (color(i)(j) == 1 || _toAdd == 0 || as(i)(j) != '.') {\n _toAdd\n } else {\n color(i)(j) = 1\n var toAdd = _toAdd\n if (i > 0) toAdd = dfs(i - 1, j, toAdd)\n if (i < n - 1) toAdd = dfs(i + 1, j, toAdd)\n if (j > 0) toAdd = dfs(i, j - 1, toAdd)\n if (j < m - 1) toAdd = dfs(i, j + 1, toAdd)\n color(i)(j) = 2\n if (toAdd > 0) {\n as(i)(j) = 'X'\n toAdd -= 1\n }\n toAdd\n }\n }\n \n var i0, j0 = -1\n \n for (i <- 0 until n; j <- 0 until m) if (as(i)(j) == '.') {\n i0 = i; j0 = j\n }\n \n if (i0 >= 0) dfs(i0, j0, k)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n for (a <- as) println(a.mkString(\"\"))\n Console.flush\n}"}], "negative_code": [], "src_uid": "3aba4a129e24ca2f06f5f3ef13415b8b"} {"nl": {"description": " William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \\dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \\le i \\le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet.", "input_spec": "The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \\le n \\le 10^3, 1 \\le d \\le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n, x_i \\neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$.", "output_spec": "Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions.", "sample_inputs": ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"], "sample_outputs": ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"], "notes": "NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. "}, "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 * b.compareTo(that.b)\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 = 1000010\n val mp = mutable.Map[Char, Int]()\n\n val t = 1//readInt()\n\n for (tt <- 1 to t) {\n val n = readInt()\n val k = readInt()\n val sz = new Array[Int](n+1)\n val par = new Array[Int](n+1)\n val mark = new Array[Boolean](n+1)\n\n def father(v: Int): Int = {\n if (par(v) == 0)\n return v\n par(v) = father(par(v))\n return par(v)\n }\n def merge(a: Int, b:Int): Unit = {\n val v = father(a)\n val u = father(b)\n if (v == u)\n return\n if (sz(v) >= sz(u)) {\n par(u) = v\n sz(v) += sz(u)\n } else {\n par(v) = u\n sz(u) += sz(v)\n }\n }\n\n\n var sum = 0\n var ans = 0\n for (i <- 1 to n)\n sz(i) = 1\n var a = 0\n var b = 0\n for (i <- 1 to k) {\n sum = 0\n for (j <- 1 to n)\n mark(j) = false\n a = readInt()\n b = readInt()\n merge(a, b)\n a = father(a)\n var comp = Vector[pair]()\n for (j <- 1 to n) {\n b = father(j)\n if (!mark(b)) {\n mark(b) = true\n comp :+= pair(b, sz(b))\n sum += sz(b) - 1\n }\n }\n comp = comp.sorted\n ans = sz(comp(0).a) - 1\n for (i <- 1 to i-sum) {\n ans += sz(comp(i).a)\n }\n writer.println(ans)\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}\n"}], "negative_code": [], "src_uid": "29bc7a22baa3dc6bb508b00048e50114"} {"nl": {"description": "Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1\u2009+\u2009c2\u00b7(x\u2009-\u20091)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group. ", "input_spec": "The first line contains three integers n, c1 and c2 (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009c1,\u2009c2\u2009\u2264\u2009107)\u00a0\u2014 the number of visitors and parameters for determining the ticket prices for a group. The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.", "output_spec": "Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.", "sample_inputs": ["3 4 1\n011", "4 7 2\n1101"], "sample_outputs": ["8", "18"], "notes": "NoteIn the first test one group of three people should go to the attraction. Then they have to pay 4\u2009+\u20091\u2009*\u2009(3\u2009-\u20091)2\u2009=\u20098.In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7\u2009+\u20092\u2009*\u2009(2\u2009-\u20091)2\u2009=\u20099. Thus, the total price for two groups is 18."}, "positive_code": [{"source_code": "object Main extends App {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n val a, b = sc.nextLong()\n val s = sc.next()\n var cnt = 0\n for (i <- 0 to n - 1) {\n if (s.charAt(i) == '1') cnt = cnt + 1\n }\n \n var ans = 1e18.toLong\n for (i <- 1 to cnt) {\n var t1 = (n / i).toLong\n var t2 = (n % i).toLong\n // println(t1 + \" \" + t2)\n var x1 = (a + b * (t1 - 1) * (t1 - 1)) * (i - t2)\n var x2 = (a + b * t1 * t1) * t2\n if (ans > x1 + x2) ans = x1 + x2\n }\n print(ans)\n}"}], "negative_code": [{"source_code": "object Main extends App {\n val sc = new java.util.Scanner(System.in)\n val n, a, b = sc.nextInt()\n val s = sc.next()\n var cnt = 0\n for (i <- 0 to n - 1) {\n if (s.charAt(i) == '1') cnt = cnt + 1\n }\n \n var ans = 1e18.toLong\n for (i <- 1 to cnt) {\n var t1 = n / i\n var t2 = n % i\n // println(t1 + \" \" + t2)\n var x1 = (a + b * (t1 - 1) * (t1 - 1)).toLong * (i - t2)\n var x2 = (a + b * t1 * t1).toLong * t2\n if (ans > x1 + x2) ans = x1 + x2\n }\n print(ans)\n}"}], "src_uid": "78d013b01497053b8e321fe7b6ce3760"} {"nl": {"description": "Andrew has $$$n$$$ piles with stones. The $$$i$$$-th pile contains $$$a_i$$$ stones. He wants to make his table clean so he decided to put every stone either to the $$$1$$$-st or the $$$n$$$-th pile.Andrew can perform the following operation any number of times: choose $$$3$$$ indices $$$1 \\le i < j < k \\le n$$$, such that the $$$j$$$-th pile contains at least $$$2$$$ stones, then he takes $$$2$$$ stones from the pile $$$j$$$ and puts one stone into pile $$$i$$$ and one stone into pile $$$k$$$. Tell Andrew what is the minimum number of operations needed to move all the stones to piles $$$1$$$ and $$$n$$$, or determine if it's impossible.", "input_spec": "The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10\\,000$$$)\u00a0\u2014 the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$3 \\leq n \\leq 10^5$$$)\u00a0\u2014 the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the minimum number of operations needed to move stones to piles $$$1$$$ and $$$n$$$, or print $$$-1$$$ if it's impossible.", "sample_inputs": ["4\n5\n1 2 2 3 6\n3\n1 3 1\n3\n1 2 1\n4\n3 1 1 2"], "sample_outputs": ["4\n-1\n1\n-1"], "notes": "NoteIn the first test case, it is optimal to do the following: Select $$$(i, j, k) = (1, 2, 5)$$$. The array becomes equal to $$$[2, 0, 2, 3, 7]$$$. Select $$$(i, j, k) = (1, 3, 4)$$$. The array becomes equal to $$$[3, 0, 0, 4, 7]$$$. Twice select $$$(i, j, k) = (1, 4, 5)$$$. The array becomes equal to $$$[5, 0, 0, 0, 9]$$$. This array satisfy the statement, because every stone is moved to piles $$$1$$$ and $$$5$$$. There are $$$4$$$ operations in total.In the second test case, it's impossible to put all stones into piles with numbers $$$1$$$ and $$$3$$$: At the beginning there's only one possible operation with $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 1, 2]$$$. Now there is no possible operation and the array doesn't satisfy the statement, so the answer is $$$-1$$$. In the third test case, it's optimal to do the following: Select $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 0, 2]$$$. This array satisfies the statement, because every stone is moved to piles $$$1$$$ and $$$3$$$. The is $$$1$$$ operation in total.In the fourth test case, it's impossible to do any operation, and the array doesn't satisfy the statement, so the answer is $$$-1$$$."}, "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 = readLongs()\n val medium = a.slice(1, size - 1)\n val answer: Long = if (medium.count(_ == 1) == medium.length ||\n (medium.length == 1 && medium.head % 2 == 1)) {\n -1\n } else {\n val removeOneCount = medium.count(_ % 2 == 1)\n (medium.sum + removeOneCount) / 2\n }\n println(answer)\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"}], "negative_code": [], "src_uid": "5b99775142b4a28b6b1069367602448f"} {"nl": {"description": "Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1\u2009\u2264\u2009p\u2009<\u2009|s|) and perform one of the following actions: either replace letter sp with the one that alphabetically follows it and replace letter sp\u2009+\u20091 with the one that alphabetically precedes it; or replace letter sp with the one that alphabetically precedes it and replace letter sp\u2009+\u20091 with the one that alphabetically follows it. Let us note that letter \"z\" doesn't have a defined following letter and letter \"a\" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The input data contains several tests. The first line contains the only integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009104) \u2014 the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.", "output_spec": "For each word you should print the number of different other words that coincide with it in their meaning \u2014 not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["1\nab", "1\naaaaaaaaaaa", "2\nya\nklmbfxzb"], "sample_outputs": ["1", "0", "24\n320092793"], "notes": "NoteSome explanations about the operation: Note that for each letter, we can clearly define the letter that follows it. Letter \"b\" alphabetically follows letter \"a\", letter \"c\" follows letter \"b\", ..., \"z\" follows letter \"y\". Preceding letters are defined in the similar manner: letter \"y\" precedes letter \"z\", ..., \"a\" precedes letter \"b\". Note that the operation never changes a word's length. In the first sample you can obtain the only other word \"ba\". In the second sample you cannot obtain any other word, so the correct answer is 0.Consider the third sample. One operation can transform word \"klmbfxzb\" into word \"klmcexzb\": we should choose p\u2009=\u20094, and replace the fourth letter with the following one (\"b\" \u2009\u2192\u2009 \"c\"), and the fifth one \u2014 with the preceding one (\"f\" \u2009\u2192\u2009 \"e\"). Also, we can obtain many other words from this one. An operation can transform word \"ya\" only into one other word \"xb\". Word \"ya\" coincides in its meaning with words \"xb\", \"wc\", \"vd\", ..., \"ay\" (overall there are 24 other words). The word \"klmbfxzb has many more variants \u2014 there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 \u2014 the number 3320092814 modulo 109\u2009+\u20097"}, "positive_code": [{"source_code": "//package round110.div1\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 03.03.12\n * Time: 12:16\n * To change this template use File | Settings | File Templates.\n */\n\n\nobject C {\n\n import math.{min, max}\n\n val mod = 1000000007\n\n def count(s: String): Int =\n (nums(s.length - 1)(s map (c => c - 'a') sum) - 1) % mod toInt\n\n val nums = Array.ofDim[Array[Long]](101)\n nums(0) = Array.fill(26)(1L)\n for (i <- 1 to 100) nums(i) = nums(i - 1) next\n\n\n def main(args: Array[String]) = (1 to readInt) foreach (_ => println(count(readLine)))\n\n\n class Result(val data: Array[Long]) {\n override def toString = \"Result(\" + data.mkString(\",\") + \")\"\n\n def next = {\n val result = Array.ofDim[Long](data.length + 25)\n for (i <- 0 until result.length) {\n for (j <- max(0, i - 25) to min(data.length - 1, i)\n ) result(i) += data(j)\n result(i) %= mod\n }\n result\n }\n }\n\n implicit def toResult(array: Array[Long]): Result = new Result(array)\n\n\n}"}], "negative_code": [], "src_uid": "75f64fc53b88a06c58a219f11da8efb7"} {"nl": {"description": "Vasya has the square chessboard of size n\u2009\u00d7\u2009n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009min(100\u2009000,\u2009n2))\u00a0\u2014 the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n)\u00a0\u2014 the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.", "output_spec": "Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.", "sample_inputs": ["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"], "sample_outputs": ["4 2 0", "16 9", "9999800001"], "notes": "NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack. "}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Tomorrow is a difficult day for Polycarp: he has to attend $$$a$$$ lectures and $$$b$$$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $$$c$$$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $$$d$$$ practical classes, after which it is unusable.Polycarp's pencilcase can hold no more than $$$k$$$ writing implements, so if Polycarp wants to take $$$x$$$ pens and $$$y$$$ pencils, they will fit in the pencilcase if and only if $$$x + y \\le k$$$.Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then the test cases follow. Each test case is described by one line containing five integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ and $$$k$$$, separated by spaces ($$$1 \\le a, b, c, d, k \\le 100$$$) \u2014 the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.", "output_spec": "For each test case, print the answer as follows: If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer $$$-1$$$. Otherwise, print two non-negative integers $$$x$$$ and $$$y$$$ \u2014 the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).", "sample_inputs": ["3\n7 5 4 5 8\n7 5 4 5 2\n20 53 45 26 4"], "sample_outputs": ["7 1\n-1\n1 3"], "notes": "NoteThere are many different answers for the first test case; $$$x = 7$$$, $$$y = 1$$$ is only one of them. For example, $$$x = 3$$$, $$$y = 1$$$ is also correct.$$$x = 1$$$, $$$y = 3$$$ is the only correct answer for the third test case."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $$$(a, b)$$$ exist, where $$$1 \\leq a, b \\leq n$$$, for which $$$\\frac{\\operatorname{lcm}(a, b)}{\\operatorname{gcd}(a, b)} \\leq 3$$$.In this problem, $$$\\operatorname{gcd}(a, b)$$$ denotes the greatest common divisor of the numbers $$$a$$$ and $$$b$$$, and $$$\\operatorname{lcm}(a, b)$$$ denotes the smallest common multiple of the numbers $$$a$$$ and $$$b$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$1 \\le n \\le 10^8$$$).", "output_spec": "For each test case output a single integer \u2014 the number of pairs of integers satisfying the condition.", "sample_inputs": ["6\n\n1\n\n2\n\n3\n\n4\n\n5\n\n100000000"], "sample_outputs": ["1\n4\n7\n10\n11\n266666666"], "notes": "NoteFor $$$n = 1$$$ there is exactly one pair of numbers\u00a0\u2014 $$$(1, 1)$$$ and it fits.For $$$n = 2$$$, there are only $$$4$$$ pairs\u00a0\u2014 $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$ and they all fit.For $$$n = 3$$$, all $$$9$$$ pair are suitable, except $$$(2, 3)$$$ and $$$(3, 2)$$$, since their $$$\\operatorname{lcm}$$$ is $$$6$$$, and $$$\\operatorname{gcd}$$$ is $$$1$$$, which doesn't fit the condition."}, "positive_code": [{"source_code": "object _1717A 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 = n + 2*(n/2) + 2*(n/3)\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"}], "negative_code": [], "src_uid": "a6b6d9ff2ac5c367c00a64a387cc9e36"} {"nl": {"description": "You are given a string $$$s$$$. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ lines follow, each representing a test case. Each line contains one string $$$s$$$ ($$$1 \\le |s| \\le 100$$$); each character of $$$s$$$ is either 0 or 1.", "output_spec": "Print $$$t$$$ integers, where the $$$i$$$-th integer is the answer to the $$$i$$$-th testcase (the minimum number of 0's that you have to erase from $$$s$$$).", "sample_inputs": ["3\n010011\n0\n1111000"], "sample_outputs": ["2\n0\n0"], "notes": "NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111)."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "5de66fbb594bb317654366fd2290c4d3"} {"nl": {"description": "Nastia has $$$2$$$ positive integers $$$A$$$ and $$$B$$$. She defines that: The integer is good if it is divisible by $$$A \\cdot B$$$; Otherwise, the integer is nearly good, if it is divisible by $$$A$$$. For example, if $$$A = 6$$$ and $$$B = 4$$$, the integers $$$24$$$ and $$$72$$$ are good, the integers $$$6$$$, $$$660$$$ and $$$12$$$ are nearly good, the integers $$$16$$$, $$$7$$$ are neither good nor nearly good.Find $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$A$$$ and $$$B$$$ ($$$1 \\le A \\le 10^6$$$, $$$1 \\le B \\le 10^6$$$)\u00a0\u2014 numbers that Nastia has.", "output_spec": "For each test case print: \"YES\" and $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \\le x, y, z \\le 10^{18}$$$) such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$. \"NO\" if no answer exists. YES NO If there are multiple answers, print any.", "sample_inputs": ["3\n5 3\n13 2\n7 11"], "sample_outputs": ["YES\n10 50 60\nYES\n169 39 208\nYES\n28 154 182"], "notes": "NoteIn the first test case: $$$60$$$\u00a0\u2014 good number; $$$10$$$ and $$$50$$$\u00a0\u2014 nearly good numbers.In the second test case: $$$208$$$\u00a0\u2014 good number; $$$169$$$ and $$$39$$$\u00a0\u2014 nearly good numbers.In the third test case: $$$154$$$\u00a0\u2014 good number; $$$28$$$ and $$$182$$$\u00a0\u2014 nearly good numbers."}, "positive_code": [{"source_code": "object testing {\r\n def main(args: Array[String]): Unit = {\r\n val T = readLine().toInt;\r\n for(i <- 1 to T){\r\n val s = readLine().split(\" \");\r\n val A = s(0).toLong;\r\n val B = s(1).toLong;\r\n if(B == 1){\r\n println(\"NO\");\r\n }else {\r\n println(\"YES\");\r\n println(A + \" \" + A * (2 * B - 1) + \" \" + (2 * A * B));\r\n }\r\n }\r\n }\r\n}"}], "negative_code": [{"source_code": "object testing {\r\n def main(args: Array[String]): Unit = {\r\n val T = readLine().toInt;\r\n for(i <- 1 to T){\r\n val s = readLine().split(\" \");\r\n val A = s(0).toInt;\r\n val B = s(1).toInt;\r\n if(B == 1){\r\n println(\"NO\");\r\n }else {\r\n println(\"YES\");\r\n println(A + \" \" + A * (2 * B - 1) + \" \" + (2 * A * B));\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "object testing {\r\n def main(args: Array[String]): Unit = {\r\n val T = readLine().toInt;\r\n for(i <- 1 to T){\r\n val s = readLine().split(\" \");\r\n val A = s(0).toInt;\r\n val B = s(1).toInt;\r\n if(B == 1){\r\n println(\"NO\");\r\n }else {\r\n println(\"YES\");\r\n println(A + \" \" + A * (B - 1) + \" \" + (A * B));\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "object testing {\r\n def main(args: Array[String]): Unit = {\r\n val T = readLine().toInt;\r\n for(i <- 1 to T){\r\n val s = readLine().split(\" \");\r\n val A = s(0).toInt;\r\n val B = s(1).toInt;\r\n if(B == 1){\r\n println(\"NO\");\r\n }else {\r\n println(\"YES\");\r\n println((A * B) + \" \" + A + \" \" + A * (B - 1));\r\n }\r\n }\r\n }\r\n}"}], "src_uid": "f10aa45956e930df3df0e23f2592c8f1"} {"nl": {"description": "You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).", "sample_inputs": ["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"], "notes": "NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES."}, "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"}, {"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"}], "negative_code": [], "src_uid": "c3df88e22a17492d4eb0f3239a27d404"} {"nl": {"description": "Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: $$$f(0) = a$$$; $$$f(1) = b$$$; $$$f(n) = f(n-1) \\oplus f(n-2)$$$ when $$$n > 1$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation. You are given three integers $$$a$$$, $$$b$$$, and $$$n$$$, calculate $$$f(n)$$$.You have to answer for $$$T$$$ independent test cases.", "input_spec": "The input contains one or more independent test cases. The first line of input contains a single integer $$$T$$$ ($$$1 \\le T \\le 10^3$$$), the number of test cases. Each of the $$$T$$$ following lines contains three space-separated integers $$$a$$$, $$$b$$$, and $$$n$$$ ($$$0 \\le a, b, n \\le 10^9$$$) respectively.", "output_spec": "For each test case, output $$$f(n)$$$.", "sample_inputs": ["3\n3 4 2\n4 5 0\n325 265 1231232"], "sample_outputs": ["7\n4\n76"], "notes": "NoteIn the first example, $$$f(2) = f(0) \\oplus f(1) = 3 \\oplus 4 = 7$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 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"}, {"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"} {"nl": {"description": "You are the head of a large enterprise. $$$n$$$ people work at you, and $$$n$$$ is odd (i.\u2009e. $$$n$$$ is not divisible by $$$2$$$).You have to distribute salaries to your employees. Initially, you have $$$s$$$ dollars for it, and the $$$i$$$-th employee should get a salary from $$$l_i$$$ to $$$r_i$$$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible.To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: the median of the sequence $$$[5, 1, 10, 17, 6]$$$ is $$$6$$$, the median of the sequence $$$[1, 2, 1]$$$ is $$$1$$$. It is guaranteed that you have enough money to pay the minimum salary, i.e $$$l_1 + l_2 + \\dots + l_n \\le s$$$.Note that you don't have to spend all your $$$s$$$ dollars on salaries.You have to answer $$$t$$$ test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^5$$$) \u2014 the number of test cases. The first line of each query contains two integers $$$n$$$ and $$$s$$$ ($$$1 \\le n < 2 \\cdot 10^5$$$, $$$1 \\le s \\le 2 \\cdot 10^{14}$$$) \u2014 the number of employees and the amount of money you have. The value $$$n$$$ is not divisible by $$$2$$$. The following $$$n$$$ lines of each query contain the information about employees. The $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^9$$$). It is guaranteed that the sum of all $$$n$$$ over all queries does not exceed $$$2 \\cdot 10^5$$$. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i.\u2009e. $$$\\sum\\limits_{i=1}^{n} l_i \\le s$$$.", "output_spec": "For each test case print one integer \u2014 the maximum median salary that you can obtain.", "sample_inputs": ["3\n3 26\n10 12\n1 4\n10 11\n1 1337\n1 1000000000\n5 26\n4 4\n2 4\n6 8\n5 6\n2 7"], "sample_outputs": ["11\n1337\n6"], "notes": "NoteIn the first test case, you can distribute salaries as follows: $$$sal_1 = 12, sal_2 = 2, sal_3 = 11$$$ ($$$sal_i$$$ is the salary of the $$$i$$$-th employee). Then the median salary is $$$11$$$.In the second test case, you have to pay $$$1337$$$ dollars to the only employee.In the third test case, you can distribute salaries as follows: $$$sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7$$$. Then the median salary is $$$6$$$."}, "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 /**\n * \u5358\u8abf\u6e1b\u5c11\n * [l, h) \u65b9\u5f0f\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\n def sort(a: Array[Long]): Array[Long] = {\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val MAX = 1e9.toInt\n val inf = 1e15.toLong\n REP(ni()) { _ =>\n val n = ni()\n var s = nl()\n val (l, r) = na2(n)\n s -= sumL(l)\n\n val v = Array.ofDim[Long](n)\n def f(x: Int): Boolean = {\n REP(n) { i =>\n v(i) = if (r(i) < x) inf\n else if (l(i) >= x) 0\n else {\n x - l(i)\n }\n }\n\n Workspace.sort(v)\n var cnt = 0L\n REP((n + 1) / 2) { i =>\n if (v(i) == inf) return false\n cnt += v(i)\n }\n s >= cnt\n }\n\n val ans = findMax(f, 1, MAX)\n out.println(ans)\n }\n }\n}"}], "negative_code": [], "src_uid": "c95450a2ec25c0a7404b954056e38ba6"} {"nl": {"description": "You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi,\u2009yi (xi\u2009<\u2009yi) in the permuted array a. Let's define the value di\u2009=\u2009yi\u2009-\u2009xi \u2014 the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .", "input_spec": "The only line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105).", "output_spec": "Print 2n integers \u2014 the permuted array a that minimizes the value of the sum s.", "sample_inputs": ["2", "1"], "sample_outputs": ["1 1 2 2", "1 1"], "notes": null}, "positive_code": [{"source_code": "\n/**\n * Created by octavian on 11/02/2016.\n */\nobject Permutation {\n\n def main(args: Array[String]) = {\n\n //System.setIn(new FileInputStream(\"./src/permutation.in\"))\n //System.setOut(new PrintStream(new FileOutputStream(\"./src/permutation.out\")))\n\n val n = readInt()\n var result: Array[Int] = Array.ofDim[Int](2 * n + 1)\n\n\n for (i <- 1 to n / 2) {\n result(i) = 2 * (i - 1) + 1\n result(n - i + 1) = 2 * (i - 1) + 1\n }\n\n for (i <- 1 to n / 2) {\n result(n + i) = 2 * i\n result(2 * n - i) = 2 * i\n }\n\n result(2 * n) = n\n\n if (n % 2 == 0) {\n result(2 * n - (n / 2)) = n\n }\n else {\n result(n - (n / 2)) = n\n }\n\n println(result.tail.mkString(\" \"))\n }\n\n}\n"}], "negative_code": [], "src_uid": "c234cb0321e2bd235cd539a63364b152"} {"nl": {"description": "String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k\u2009-\u20091)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, \"abaaba\" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.", "input_spec": "The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5\u00b7106. The string is case-sensitive.", "output_spec": "Output the only number \u2014 the sum of the polindrome degrees of all the string's prefixes.", "sample_inputs": ["a2A", "abacaba"], "sample_outputs": ["1", "6"], "notes": null}, "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}"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "0090979443c294ef6aed7cd09201c9ef"} {"nl": {"description": "Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m\u2009\u00d7\u2009m of this matrix contains at least one zero. Consider the following problem:You are given two integers n and m. You have to construct an m-free square matrix of size n\u2009\u00d7\u2009n such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.You don't have to solve this problem. Instead, you have to construct a few tests for it.You will be given t numbers x1, x2, ..., xt. For every , find two integers ni and mi (ni\u2009\u2265\u2009mi) such that the answer for the aforementioned problem is exactly xi if we set n\u2009=\u2009ni and m\u2009=\u2009mi.", "input_spec": "The first line contains one integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009100) \u2014 the number of tests you have to construct. Then t lines follow, i-th line containing one integer xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109). Note that in hacks you have to set t\u2009=\u20091.", "output_spec": "For each test you have to construct, output two positive numbers ni and mi (1\u2009\u2264\u2009mi\u2009\u2264\u2009ni\u2009\u2264\u2009109) such that the maximum number of 1's in a mi-free ni\u2009\u00d7\u2009ni matrix is exactly xi. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer \u2009-\u20091. ", "sample_inputs": ["3\n21\n0\n1"], "sample_outputs": ["5 2\n1 1\n-1"], "notes": null}, "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(t) = readInts(1)\n\n def calc1(n: Long, m: Long): Long = {\n val d = n / m\n n * n - d * d\n }\n\n def calcM(n: Long, x: Long): Long = {\n val d = n * n - x\n if (d <= 0) 0 else n / Math.sqrt(d).toInt\n }\n\n for (_ <- 1 to t) {\n\n val Array(x) = readInts(1)\n var n = Math.sqrt(x).toInt\n var res = \"-1\"\n\n var i = 0\n while (i < 10000 && res == \"-1\") {\n val m = calcM(n, x)\n if (m > 0 && m <= n && calc1(n, m) == x) res = s\"$n $m\"\n n += 1\n i += 1\n }\n\n println(res)\n }\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(t) = readInts(1)\n\n def calc1(n: Long, m: Long): Long = {\n val d = n / m\n n * n - d * d\n }\n\n def calcM(n: Long, x: Long): Long = {\n val d = n * n - x\n if (d < 0) 0 else Math.sqrt(d).toInt\n }\n\n for (_ <- 1 to t) {\n\n val Array(x) = readInts(1)\n var n = Math.sqrt(x).toInt\n var res = \"-1\"\n\n for (_ <- 1 to 1000) {\n val m = calcM(n, x)\n if (m > 0 && calc1(n, m) == x) res = s\"$n $m\"\n n += 1\n }\n\n println(res)\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(t) = readInts(1)\n\n def calc1(n: Long, m: Long): Long = {\n val d = n / m\n n * n - d * d\n }\n\n for (_ <- 1 to t) {\n\n val Array(x) = readInts(1)\n var n = Math.sqrt(x).toInt\n var res = \"-1\"\n\n for (_ <- 1 to 10) {\n var m = 1\n while (m <= n && res == \"-1\") {\n if (calc1(n, m) == x) res = s\"$n $m\"\n m += 1\n }\n n += 1\n }\n\n println(res)\n }\n}\n"}], "src_uid": "4566b8b5ea437b856524ac16e038b3d8"} {"nl": {"description": "Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi \u2014 the number of the gas type and its position.One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.", "input_spec": "The first line of the input contains four positive integers e,\u2009s,\u2009n,\u2009m (1\u2009\u2264\u2009e,\u2009s\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points. Next n lines contain two integers each ti,\u2009xi (1\u2009\u2264\u2009ti\u2009\u2264\u20093,\u2009\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109), representing the type of the i-th gas station (1 represents Regular-92, 2 \u2014 Premium-95 and 3 \u2014 Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right. The last line contains m integers fi (\u2009-\u2009109\u2009\u2264\u2009fi\u2009<\u2009e). Start positions don't necessarily follow in order from left to right. No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.", "output_spec": "Print exactly m lines. The i-th of them should contain two integers \u2014 the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value. If there is no way to get to Johanna from point fi, the i-th line should look like that \"-1 -1\" (two numbers minus one without the quotes).", "sample_inputs": ["8 4 1 1\n2 4\n0", "9 3 2 3\n2 3\n1 6\n-1 0 1", "20 9 2 4\n1 5\n2 10\n-1 0 1 2"], "sample_outputs": ["0 4", "-1 -1\n3 3\n3 2", "-1 -1\n-1 -1\n-1 -1\n-1 -1"], "notes": null}, "positive_code": [{"source_code": "\nimport java.io._\nimport java.util.ArrayList\n\nobject E_Kojo_And_Furarri_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 class Station(val typpe:Int, val coord:Long) {\n var used = 0l\n var total1 = 0l\n var total2 = 0l\n var total3 = 0l\n var broken = false\n var start = false\n var startInd = 0l\n override def toString(): String = {\n var str = coord + \"_\" + typeStr(typpe) + used + \"[\" + total1 + \",\" + total2 + \"]\"\n if (start) str = \"s\" + str\n return str\n }\n def setupTotal(next:Station) = {\n if (next != null) {\n total1 = next.total1\n total2 = next.total2\n total3 = next.total3\n }\n typpe match {\n case 3 => total3 += used\n case 2 => total2 += used\n case 1 => total1 += used\n }\n }\n def incrTotal(value:Long) = {\n typpe match {\n case 3 => total3 += value\n case 2 => total2 += value\n case 1 => total1 += value\n }\n }\n \n \n def decrTotal(v1:Long, v2:Long) = {\n total1 -= v1\n total2 -= v2\n }\n }\n def typeStr(typpe:Int) = {\n typpe match {\n case 3 => \"A\"\n case 2 => \"B\"\n case 1 => \"C\"\n }\n }\n \n val is = System.in\n \n //COMMENT ME !\n// val is = new ByteArrayInputStream(s9.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 e_total = line1(0).toLong\n val s_tank = line1(1).toLong\n val n_stations = line1(2).toInt\n val m_points = line1(3).toInt\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val line = br.readLine().trim().split(\" \")\n stations ::= new Station(line(0).toInt, line(1).toInt)\n }\n stations = stations.filter(_.coord < e_total)\n db(stations.mkString(\" -> \"))\n db(\"AFTER STATIONS LOADED\")\n var starts = List[Station]()\n val line2 = br.readLine().split(\" \")\n for (i <- 0 until line2.length) {\n val start = new Station(3, line2(i).toLong)\n start.start = true;\n start.startInd = i\n stations ::= start\n starts ::= start\n }\n stations = stations.sortWith { (a,b) => a.coord > b.coord}\n db(stations.mkString(\" -> \"))\n db(\"AFTER STARTS LOADED\")\n //---------------------------- parameters reading end --------------------------------\n \n var resSize = 0\n var prevCoord = e_total\n var next:Station = null\n var broken = false\n var processed = List[Station]()\n var toProcess = stations\n val result = new StringBuilder()\n while (resSize < m_points) {\n val st = toProcess.head\n val diff = prevCoord - st.coord \n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n } else { \n st.used = diff\n st.setupTotal(next)\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist(processed, st, rest)\n st.used = st.used + redisted._1\n st.incrTotal(redisted._1)\n st.decrTotal(redisted._2, redisted._3)\n }\n }\n \n if (st.start) {\n resSize += 1\n db(st.coord + \": \" + stations.mkString(\" -> \"))\n } else {\n next = st\n prevCoord = st.coord\n processed ::= st\n }\n toProcess = toProcess.tail\n }\n \n starts = starts.sortWith{(a,b) => a.startInd < b.startInd }\n \n \n for(st <- starts) {\n// if (debugV) print(st.coord + \": \")\n if (st.broken) {\n result.append(\"-1 -1\\n\") \n } else {\n result.append(st.total1 + \" \" + st.total2 + \"\\n\")\n }\n }\n println(result.toString())\n \n def redist(li: List[Station], st:Station, rest:Long):(Long,Long,Long) = {\n if (li == Nil || rest == 0) { return (0,0,0) }\n var result = 0l\n var result1 = 0l\n var result2 = 0l\n val next = li.head\n var toReduce = 0l\n if (next.typpe < st.typpe) {\n toReduce = Math.min(rest, next.used)\n if (!st.start) { //save only for real station\n next.used = next.used- toReduce\n }\n if (next.typpe == 1) {\n result1 = toReduce\n } else if (next.typpe == 2) {\n result2 = toReduce\n }\n val left = rest - toReduce\n result = toReduce\n val other = redist(li.tail, st, left)\n result += other._1\n result1 += other._2\n result2 += other._3\n }\n return (result, result1, result2)\n }\n \n\n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n8 4 1 1\n2 4\n0\n\"\"\"\n\nval sa2 = \"\"\"\n9 3 2 3\n2 3\n1 6\n-1 0 1\n\"\"\"\n\nval sa3 = \"\"\"\n20 9 2 4\n1 5\n2 10\n-1 0 1 2\n\"\"\"\n\nval s7 = \"\"\"\n67 10 9 10\n3 -1\n1 59\n1 39\n1 -11\n2 29\n1 9\n1 19\n1 49\n3 77\n27 14 21 36 0 13 57 41 20 28\n\"\"\"\n\nval s8 = \"\"\"\n216 15 19 10\n2 -31\n2 100\n3 230\n1 57\n3 42\n1 157\n2 186\n1 113\n2 -16\n3 245\n2 142\n1 86\n2 -3\n3 201\n3 128\n3 12\n3 171\n2 27\n2 72\n98 197 114 0 155 35 36 11 146 27\n\"\"\"\n\nval s9 = \"\"\"\n386 20 29 30\n1 349\n2 482\n1 112\n1 93\n2 189\n1 207\n2 35\n2 -5\n1 422\n1 442\n1 402\n2 238\n3 258\n3 54\n2 369\n2 290\n2 329\n3 74\n3 -62\n2 170\n1 462\n2 15\n2 222\n1 309\n3 150\n1 -25\n3 130\n1 271\n1 -43\n351 250 91 102 0 286 123 93 100 205 328 269 188 83 73 35 188 223 73 215 199 64 47 379 61 298 295 65 158 211\n\"\"\"\n//========================= samples end ==================== \n}"}], "negative_code": [{"source_code": "\nimport java.io._\nimport java.lang.Long\nimport scala.annotation.tailrec\n\n//#322 (Div. 2) E\n//581/problem/E \nobject E_Kojo_And_Furarri {\n \n class Station(val typpe:Int, val coordinate:Long) {\n var O_value = 0l\n private var _ex_value = 0l\n def ex_value = _ex_value\n def ex_value_= (vv: Long) { _ex_value = vv; calc_value = vv}\n var broken = false\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n var calc_value = 0l\n \n override def toString(): String = {\n var str = \"\"\n var t = \"A\"\n typpe match {\n case 3 => t = \"A\"\n case 2 => t = \"B\"\n case 1 => t = \"C\"\n }\n str += coordinate + \"_\" + t\n if (broken) {\n str += \"-1\"\n } else {\n str += O_value + \"(\" + ex_value + \")\"\n str += \"[\" + total_1 + \",\" + total_2 + \"]\"\n }\n return str\n }\n \n def resetCalc() {calc_value = ex_value}\n }\n\n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var debugMode = false\n\n val line1 = br.readLine().split(\" \")\n val e_total = line1(0).toLong\n val s_tank = line1(1).toLong\n val n_stations = line1(2).toInt\n val m_points = line1(3).toInt\n\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val s_line = br.readLine().split(\" \")\n val s_coo = s_line(1).toLong\n if (s_coo < e_total) {\n stations = new Station(s_line(0).toInt, s_coo) :: stations\n }\n }\n stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}\n val line2 = br.readLine().split(\" \")\n var starts = List[Long]()\n for (i <- 0 until line2.length) {\n starts = line2(i).toLong :: starts\n }\n starts = starts.reverse\n\n \n \n //test inp\n \n// val inp = \"\"\"8 4 1 1\n//2 4\n//0\"\"\".split(\"\\n\")\n\n// val inp = \"\"\"9 3 2 3\n//2 3\n//1 6\n//-1 0 1\"\"\".split(\"\\n\")\n \n// val inp = \"\"\"20 9 2 4\n//1 5\n//2 10\n//-1 0 1 2\"\"\".split(\"\\n\") \n \n //system 7\n// val inp = \"\"\"67 10 9 10\n//3 -1\n//1 59\n//1 39\n//1 -11\n//2 29\n//1 9\n//1 19\n//1 49\n//3 77\n//27 14 21 36 0 13 57 41 20 28\n//\"\"\".split(\"\\n\") \n\n //system 8\n// val inp = \"\"\"216 15 19 10\n//2 -31\n//2 100\n//3 230\n//1 57\n//3 42\n//1 157\n//2 186\n//1 113\n//2 -16\n//3 245\n//2 142\n//1 86\n//2 -3\n//3 201\n//3 128\n//3 12\n//3 171\n//2 27\n//2 72\n//98 197 114 0 155 35 36 11 146 27\"\"\".split(\"\\n\")\n//// debugMode = true\n// val line1 = inp(0).trim().split(\" \")\n// val e_total = line1(0).toLong\n// val s_tank = line1(1).toLong\n// val n_stations = line1(2).toInt\n// val m_points = line1(3).toInt\n// var stations = List[Station]()\n// for (i <- 1 to n_stations) {\n// val s_line = inp(i).trim.split(\" \")\n// val s_coo = s_line(1).toLong\n// if (s_coo < e_total) {\n// stations = new Station(s_line(0).toInt, s_coo) :: stations\n// }\n// }\n// stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}\n// val line2 = inp(n_stations+1).trim.split(\" \")\n// var starts = List[Long]()\n// for (i <- 0 until line2.length) {\n// starts = line2(i).toLong :: starts\n// }\n// starts = starts.reverse\n// starts = List(98) //!!!!!\n \n \n \n def redist2(toRedis: List[Station], st: Station, restTotal: Long, marking: Boolean): Long = {\n if (toRedis == Nil) { return 0 }\n var result = 0l\n val next = toRedis.head\n if (restTotal == 0) return 0\n var toReduce = 0l\n if (next.typpe < st.typpe) {\n if (marking) {\n toReduce = Math.min(restTotal, next.ex_value)\n next.ex_value = next.ex_value - toReduce\n } else {\n toReduce = Math.min(restTotal, next.calc_value)\n next.calc_value = next.calc_value - toReduce\n }\n result = toReduce + redist2(toRedis.tail, next, restTotal - toReduce, marking)\n }\n return result\n }\n \n \n def mark(toMark: List[Station], end: Long): List[Station] = {\n var result = List[Station]()\n var prevCoord = end\n var broken = false\n for (st <- toMark) {\n val diff = prevCoord - st.coordinate\n prevCoord = st.coordinate\n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n st.ex_value = -1\n } else {\n st.O_value = diff\n st.ex_value = st.O_value\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist2(result, st, rest, true)\n st.O_value = st.O_value + redisted\n st.ex_value = st.O_value\n }\n }\n result = st :: result\n printMarks(result)\n }\n result\n }\n \n def printMarks(marks: List[Station]) {\n if (!debugMode) return\n var str = \"\"\n for(st <- marks) {\n str += st.toString() + \" -> \"\n }\n println(str)\n }\n \n def debug(str: String) {\n if (debugMode)\n println(str)\n }\n \n //mark\n val marked = mark(stations, e_total)\n debug(\"------- MARKED -------\")\n\n //update total\n updateTotal(stations,0,0,0,true)\n \n printMarks(marked)\n debug(\"------- TOTALLED -------\")\n \n //calc starts\n for (point <- starts) {\n marked.foreach { _.resetCalc() }\n calcPoint(point)\n }\n \n def calcPoint(point: Long) {\n val tankEnd = point + s_tank\n if (tankEnd >= e_total) {\n printRes(0,0)\n return\n }\n var li = findStList(point, marked)\n if (li == Nil || li.head.broken || tankEnd < li.head.coordinate) {\n printRes(-1,-1)\n return\n }\n val diff = li.head.coordinate - point \n\n val startSt = new Station(3, point)\n redist2(li, startSt, s_tank - diff, false)\n li = startSt :: li\n updateTotal(li.reverse,0,0,0,false) \n \n printRes(startSt.total_1, startSt.total_2)\n\n }\n \n def printRes(t92:Long, t95:Long) {\n println(t92 +\" \" + t95)\n }\n \n @tailrec\n def findStList(start: Long, li: List[Station]): List[Station] = {\n if (li == Nil || start < li.head.coordinate) li\n else findStList(start, li.tail)\n }\n \n @tailrec\n def updateTotal(toTotal: List[Station], total_1: Long, total_2: Long, total_3: Long, marking:Boolean):Unit = {\n if (toTotal == Nil) return\n val st = toTotal.head\n if (st.broken) {\n st.total_1 = -1\n st.total_2 = -1\n st.total_3 = -1\n } else {\n st.total_1 = total_1\n st.total_2 = total_2\n st.total_3 = total_3\n var value = st.ex_value\n if (!marking) {\n value = st.calc_value\n }\n st.typpe match {\n case 1 => st.total_1 += value\n case 2 => st.total_2 += value\n case 3 => st.total_3 += value\n } \n }\n updateTotal(toTotal.tail, st.total_1, st.total_2, st.total_3, marking)\n }\n \n\n }\n}"}, {"source_code": "\n\nimport java.io._\nimport java.lang.Long\nimport scala.annotation.tailrec\n\n//#322 (Div. 2) E\n//581/problem/E \nobject E_Kojo_And_Furarri {\n \n\n\n def main(args: Array[String]): Unit = {\n var marking = true\n \n class Station(val typpe:Int, val coordinate:Long) {\n var O_value = 0l\n private var _ex_value = 0l\n def ex_value = _ex_value\n def ex_value_= (vv: Long) { _ex_value = vv; calc_value = vv}\n private var _broken = false\n def broken = _broken\n def broken_=(vv:Boolean) {_broken = vv; calc_broken = vv}\n var calc_broken = false\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n var calc_value = 0l\n \n override def toString(): String = {\n var str = \"\"\n var t = \"A\"\n typpe match {\n case 3 => t = \"A\"\n case 2 => t = \"B\"\n case 1 => t = \"C\"\n }\n str += coordinate + \"_\" + t\n if (broken) {\n str += \"-1\"\n } else {\n if (marking) {\n str += O_value + \"(\" + ex_value + \")\"\n } else {\n str += O_value + \"(\" + calc_value + \")\"\n }\n str += \"[\" + total_1 + \",\" + total_2 + \"]\"\n }\n return str\n }\n \n def resetCalc() {calc_value = ex_value; calc_broken = calc_broken}\n }\n \n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var debugMode = false\n\n\n val line1 = br.readLine().split(\" \")\n val e_total = line1(0).toLong\n val s_tank = line1(1).toLong\n val n_stations = line1(2).toInt\n val m_points = line1(3).toInt\n\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val s_line = br.readLine().split(\" \")\n val s_coo = s_line(1).toLong\n if (s_coo < e_total) {\n stations = new Station(s_line(0).toInt, s_coo) :: stations\n }\n }\n stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}\n val line2 = br.readLine().split(\" \")\n var starts = List[Long]()\n for (i <- 0 until line2.length) {\n starts = line2(i).toLong :: starts\n }\n starts = starts.reverse\n\n \n \n //test inp\n \n// val inp = \"\"\"8 4 1 1\n//2 4\n//0\"\"\".split(\"\\n\")\n\n// val inp = \"\"\"9 3 2 3\n//2 3\n//1 6\n//-1 0 1\"\"\".split(\"\\n\")\n \n// val inp = \"\"\"20 9 2 4\n//1 5\n//2 10\n//-1 0 1 2\"\"\".split(\"\\n\") \n \n //system 7\n// val inp = \"\"\"67 10 9 10\n//3 -1\n//1 59\n//1 39\n//1 -11\n//2 29\n//1 9\n//1 19\n//1 49\n//3 77\n//27 14 21 36 0 13 57 41 20 28\n//\"\"\".split(\"\\n\") \n\n //system 8\n// val inp = \"\"\"216 15 19 10\n//2 -31\n//2 100\n//3 230\n//1 57\n//3 42\n//1 157\n//2 186\n//1 113\n//2 -16\n//3 245\n//2 142\n//1 86\n//2 -3\n//3 201\n//3 128\n//3 12\n//3 171\n//2 27\n//2 72\n//98 197 114 0 155 35 36 11 146 27\"\"\".split(\"\\n\")\n \n//val inp = \"\"\"386 20 29 30\n//1 349\n//2 482\n//1 112\n//1 93\n//2 189\n//1 207\n//2 35\n//2 -5\n//1 422\n//1 442\n//1 402\n//2 238\n//3 258\n//3 54\n//2 369\n//2 290\n//2 329\n//3 74\n//3 -62\n//2 170\n//1 462\n//2 15\n//2 222\n//1 309\n//3 150\n//1 -25\n//3 130\n//1 271\n//1 -43\n//351 250 91 102 0 286 123 93 100 205 328 269 188 83 73 35 188 223 73 215 199 64 47 379 61 298 295 65 158 211\n//\"\"\".split(\"\\n\")\n//\n//// debugMode = true\n// val line1 = inp(0).trim().split(\" \")\n// val e_total = line1(0).toLong\n// val s_tank = line1(1).toLong\n// val n_stations = line1(2).toInt\n// val m_points = line1(3).toInt\n// var stations = List[Station]()\n// for (i <- 1 to n_stations) {\n// val s_line = inp(i).trim.split(\" \")\n// val s_coo = s_line(1).toLong\n// if (s_coo < e_total) {\n// stations = new Station(s_line(0).toInt, s_coo) :: stations\n// }\n// }\n// stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}\n// val line2 = inp(n_stations+1).trim.split(\" \")\n// var starts = List[Long]()\n// for (i <- 0 until line2.length) {\n// starts = line2(i).toLong :: starts\n// }\n// starts = starts.reverse\n// starts = List(286)\n// starts = List(188)\n// starts = List(269)\n// starts = List(64)\n \n \n \n def redist2(toRedis: List[Station], st: Station, restTotal: Long, marking: Boolean): Long = {\n if (toRedis == Nil) { return 0 }\n var result = 0l\n val next = toRedis.head\n if (restTotal == 0) return 0\n var toReduce = 0l\n if (next.typpe < st.typpe) {\n if (marking) {\n toReduce = Math.min(restTotal, next.ex_value)\n next.ex_value = next.ex_value - toReduce\n } else {\n toReduce = Math.min(restTotal, next.calc_value)\n next.calc_value = next.calc_value - toReduce\n }\n result = toReduce + redist2(toRedis.tail, st, restTotal - toReduce, marking)\n }\n return result\n }\n \n \n def mark(toMark: List[Station], end: Long, marking:Boolean, distLimit: Long): List[Station] = {\n var result = List[Station]()\n var prevCoord = end\n var broken = false\n for (st <- toMark) {\n// if (st.coordinate == 93) {\n// println(\"it's it\")\n// }\n val diff = prevCoord - st.coordinate\n prevCoord = st.coordinate\n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n st.ex_value = -1\n st.calc_value = -1\n } else {\n if (marking) {\n st.O_value = diff\n st.ex_value = st.O_value\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist2(result, st, rest, marking)\n// st.O_value = st.O_value + redisted\n st.ex_value = st.O_value + redisted\n }\n } else {\n st.calc_broken = false\n st.calc_value = st.O_value\n val rest = s_tank - diff\n if (rest > 0) {\n// if (result == Nil) {\n// val redisted = Math.min(rest, distLimit)\n// st.calc_value = st.O_value + redisted\n// } else {\n val redisted = redist2(result, st, rest, marking)\n st.calc_value = st.O_value + redisted\n// }\n }\n }\n }\n result = st :: result\n printMarks(result)\n }\n result\n }\n \n def printMarks(marks: List[Station]) {\n if (!debugMode) return\n var str = \"\"\n for(st <- marks) {\n str += st.toString() + \" -> \"\n }\n println(str)\n }\n \n def debug(str: String) {\n if (debugMode)\n println(str)\n }\n \n //mark\n val marked = mark(stations, e_total, true, 0)\n debug(\"------- MARKED -------\")\n\n //update total\n updateTotal(stations,0,0,0,true)\n \n printMarks(marked)\n debug(\"------- TOTALLED -------\")\n \n //calc starts\n marking = false\n for (point <- starts) {\n marked.foreach { _.resetCalc() }\n calcPoint(point)\n }\n \n def calcPoint(point: Long) {\n val tankEnd = point + s_tank\n if (tankEnd >= e_total) {\n printRes(0,0)\n return\n }\n var li = findStList(point, marked)\n \n var toReset = getForReset(li, point + s_tank*3)\n var toResetInv = toReset._1.reverse\n debug(\"----- BEFORE RESET -----\")\n printMarks(toResetInv)\n mark(toResetInv, toReset._2, false, toReset._3)\n debug(\"----- AFTER RESET -----\")\n printMarks(toResetInv)\n \n if (li == Nil || li.head.broken || tankEnd < li.head.coordinate) {\n printRes(-1,-1)\n return\n }\n val diff = li.head.coordinate - point \n\n val startSt = new Station(3, point)\n \n redist2(li, startSt, s_tank - diff, false)\n li = startSt :: li\n updateTotal(li.reverse,0,0,0,false) \n printMarks(li)\n \n// if (debugMode) \n// print(\"point=\" + point + \" \")\n printRes(startSt.total_1, startSt.total_2)\n\n }\n \n def getForReset(all:List[Station], max:Long): (List[Station], Long, Long) ={\n if (all == Nil) return (Nil, e_total, 0)\n if (all.head.coordinate < max) {\n val nextRes = getForReset(all.tail, max) \n var limit = nextRes._3\n if (all.tail != Nil) {\n limit = Math.min(limit, all.tail.head.coordinate - all.head.coordinate)\n }\n (all.head :: nextRes._1, nextRes._2, limit)\n } else {\n (Nil, all.head.coordinate, s_tank - all.head.ex_value)\n }\n }\n \n def printRes(t92:Long, t95:Long) {\n println(t92 +\" \" + t95)\n }\n \n @tailrec\n def findStList(start: Long, li: List[Station]): List[Station] = {\n if (li == Nil || start < li.head.coordinate) li\n else findStList(start, li.tail)\n }\n \n @tailrec\n def updateTotal(toTotal: List[Station], total_1: Long, total_2: Long, total_3: Long, marking:Boolean):Unit = {\n if (toTotal == Nil) return\n val st = toTotal.head\n if (st.broken) {\n st.total_1 = -1\n st.total_2 = -1\n st.total_3 = -1\n } else {\n st.total_1 = total_1\n st.total_2 = total_2\n st.total_3 = total_3\n var value = st.ex_value\n if (!marking) {\n value = st.calc_value\n }\n st.typpe match {\n case 1 => st.total_1 += value\n case 2 => st.total_2 += value\n case 3 => st.total_3 += value\n } \n }\n updateTotal(toTotal.tail, st.total_1, st.total_2, st.total_3, marking)\n }\n \n\n }\n}"}, {"source_code": "import java.io._\nimport java.lang.Long\nimport scala.annotation.tailrec\n\n//#322 (Div. 2) E\n//581/problem/E \nobject E_Kojo_And_Furarri {\n \n class Station(val typpe:Int, val coordinate:Long) {\n// var O_type = typpe; \n var O_value = 0l\n// var ex_type = 0;\n var ex_value = 0l\n var broken = false\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n \n \n override def toString(): String = {\n var str = \"\"\n var t = \"A\"\n typpe match {\n case 3 => t = \"A\"\n case 2 => t = \"B\"\n case 1 => t = \"C\"\n }\n str += coordinate + \"_\" + t\n if (broken) {\n str += \"-1\"\n } else {\n str += O_value + \"(\" + ex_value + \")\"\n str += \"[\" + total_1 + \",\" + total_2 + \"]\"\n }\n return str\n }\n }\n\n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var debugMode = false\n\n val line1 = br.readLine().split(\" \")\n val e_total = line1(0).toLong \n val s_tank = line1(1).toLong \n val n_stations = line1(2).toInt \n val m_points = line1(3).toInt \n \n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val s_line = br.readLine().split(\" \")\n stations = new Station(s_line(0).toInt, s_line(1).toLong) :: stations\n }\n val line2 = br.readLine().split(\" \")\n var starts = List[Long]()\n for (i <- 0 until line2.length) {\n starts = line2(i).toLong :: starts\n }\n starts = starts.reverse\n\n //test inp\n // val e_total = 8l \n // val s_tank = 4l \n // val n_stations = 1 \n // val m_points = 1 \n // var stations = List[Station](new Station(2, 4)).reverse\n // var starts = List[Long](0)\n //\n // debugMode = true\n // val e_total = 9l \n // val s_tank = 3l \n // val n_stations = 2 \n // val m_points = 3 \n // var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n // var starts = List[Long](-1, 0, 1)\n\n // val e_total = 20l \n // val s_tank = 9l \n // val n_stations = 2 \n // val m_points = 4 \n // var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse\n // var starts = List[Long](-1, 0, 1, 2) \n // \n // val e_total = 10l \n // val s_tank = 3l \n // val n_stations = 4 \n // val m_points = 1 \n // var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),\n // new Station(2, 8)).reverse\n // var starts = List[Long](1,0)\n\n// val e_total = 9l\n// val s_tank = 3l\n// val n_stations = 2\n// val m_points = 3\n// var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n// var starts = List[Long](-1, 0, 1) \n\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n\n def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {\n var rest = restTotal\n for (next <- toRedis) {\n if (rest == 0 || next.typpe > st.typpe) return restTotal - rest\n val toReduce = Math.min(rest, next.ex_value)\n next.ex_value = next.ex_value - toReduce\n rest = rest - toReduce\n }\n return restTotal - rest\n }\n \n def mark(toMark: List[Station], end: Long): List[Station] = {\n var result = List[Station]()\n var prevCoord = end\n var broken = false\n for (st <- toMark) {\n val diff = prevCoord - st.coordinate\n prevCoord = st.coordinate\n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n st.ex_value = -1\n } else {\n st.O_value = diff\n st.ex_value = diff\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist(result, st, rest)\n st.O_value = st.O_value + redisted\n }\n }\n result = st :: result\n printMarks(result)\n }\n result\n }\n \n def printMarks(marks: List[Station]) {\n if (!debugMode) return\n var str = \"\"\n for(st <- marks) {\n str += st.toString() + \" -> \"\n }\n println(str)\n }\n \n def debug(str: String) {\n if (debugMode)\n println(str)\n }\n \n //mark\n val marked = mark(stations, e_total)\n debug(\"------- MARKED -------\")\n\n //update total\n for (st <- stations) {\n updateTotal(st)\n }\n printMarks(marked)\n debug(\"------- TOTALLED -------\")\n \n //calc starts\n for (point <- starts) {\n calcPoint(point)\n }\n \n def calcPoint(point: Long) {\n val finalStart = point + s_tank\n if (finalStart >= e_total) {\n printRes(0,0)\n return\n }\n val li = findStList(point, marked)\n if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {\n printRes(-1,-1)\n return\n }\n val spli = split(li, point + s_tank)\n val left = new Station(3, point) :: spli._1\n var right1 = 0l\n var right2 = 0l\n if (spli._2 != null) {\n right1 = spli._2.total_1\n right2 = spli._2.total_2\n }\n if (spli._1 == Nil) {\n printRes(right1, right2)\n return\n }\n val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}\n \n val leftRev = left.reverse\n val subMarked = mark(leftRev, subMax)\n total_1 = 0\n total_2 = 0\n total_3 = 0\n for (st <- leftRev) {\n updateTotal(st) \n }\n// println(\"SUB MARKET TOTALLED\")\n// printMarks(subMarked)\n var left1 = 0l\n var left2 = 0l\n if (subMarked != Nil) {\n left1 = subMarked.head.total_1\n left2 = subMarked.head.total_2\n }\n printRes(left1+right1, left2+right2)\n }\n \n def printRes(t92:Long, t95:Long) {\n println(t92 +\" \" + t95)\n }\n \n def split(li: List[Station], max: Long): (List[Station], Station) = {\n var result = List[Station]()\n for(st <- li) {\n if (st.coordinate >= max) {\n return (result, st)\n } else {\n result = new Station(st.typpe, st.coordinate) :: result\n }\n }\n return (result.reverse, null)\n }\n \n @tailrec\n def findStList(start: Long, li: List[Station]): List[Station] = {\n if (li == Nil || start < li.head.coordinate) li\n else findStList(start, li.tail)\n }\n \n def updateTotal(st:Station) = {\n if (st.broken) {\n total_1 = -1\n total_2 = -1\n total_3 = -1\n } else {\n st.typpe match {\n case 1 => total_1 += st.ex_value\n case 2 => total_2 += st.ex_value\n case 3 => total_3 += st.ex_value\n }\n }\n st.total_1 = total_1\n st.total_2 = total_2\n st.total_3 = total_3\n }\n \n\n }\n}"}, {"source_code": "\nimport java.io._\nimport java.lang.Long\nimport scala.annotation.tailrec\n\n//#322 (Div. 2) E\n//581/problem/E \nobject E_Kojo_And_Furarri {\n \n class Station(val typpe:Int, val coordinate:Long) {\n var O_value = 0l\n var ex_value = 0l\n var broken = false\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n \n override def toString(): String = {\n var str = \"\"\n var t = \"A\"\n typpe match {\n case 3 => t = \"A\"\n case 2 => t = \"B\"\n case 1 => t = \"C\"\n }\n str += coordinate + \"_\" + t\n if (broken) {\n str += \"-1\"\n } else {\n str += O_value + \"(\" + ex_value + \")\"\n str += \"[\" + total_1 + \",\" + total_2 + \"]\"\n }\n return str\n }\n }\n\n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var debugMode = false\n\n val line1 = br.readLine().split(\" \")\n val e_total = line1(0).toLong\n val s_tank = line1(1).toLong\n val n_stations = line1(2).toInt\n val m_points = line1(3).toInt\n\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val s_line = br.readLine().split(\" \")\n val s_coo = s_line(1).toLong\n if (s_coo < e_total) {\n stations = new Station(s_line(0).toInt, s_coo) :: stations\n }\n }\n stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}\n val line2 = br.readLine().split(\" \")\n var starts = List[Long]()\n for (i <- 0 until line2.length) {\n starts = line2(i).toLong :: starts\n }\n starts = starts.reverse\n\n //test inp\n // val e_total = 8l \n // val s_tank = 4l \n // val n_stations = 1 \n // val m_points = 1 \n // var stations = List[Station](new Station(2, 4)).reverse\n // var starts = List[Long](0)\n //\n // debugMode = true\n // val e_total = 9l \n // val s_tank = 3l \n // val n_stations = 2 \n // val m_points = 3 \n // var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n // var starts = List[Long](-1, 0, 1)\n\n // val e_total = 20l \n // val s_tank = 9l \n // val n_stations = 2 \n // val m_points = 4 \n // var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse\n // var starts = List[Long](-1, 0, 1, 2) \n // \n // val e_total = 10l \n // val s_tank = 3l \n // val n_stations = 4 \n // val m_points = 1 \n // var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),\n // new Station(2, 8)).reverse\n // var starts = List[Long](1,0)\n\n // val e_total = 9l\n // val s_tank = 3l\n // val n_stations = 2\n // val m_points = 3\n // var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n // var starts = List[Long](-1, 0, 1)\n \n// debugMode = true\n// val e_total = 18l\n// val s_tank = 9l\n// val n_stations = 2\n// val m_points = 1\n// var stations = List[Station](new Station(2, 9), new Station(1, 12)).reverse\n// var starts = List[Long](0)\n \n// debugMode = true\n// val e_total = 67l\n// val s_tank = 10l\n// val n_stations = 9\n// val m_points = 10\n// var stations = List[Station](new Station(3, -1), new Station(1, 59),\n// new Station(1, 39), new Station(1, -11), new Station(2, 29), new Station(1, 9)\n// , new Station(1, 19), new Station(1, 49), new Station(3, 77))\n// stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}\n// var starts = List[Long](27, 14, 21, 36, 0, 13, 57, 41, 20, 28)\n \n\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n\n def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {\n var rest = restTotal\n for (next <- toRedis) {\n if (rest == 0 || next.typpe > st.typpe) return restTotal - rest\n val toReduce = Math.min(rest, next.ex_value)\n next.ex_value = next.ex_value - toReduce\n rest = rest - toReduce\n }\n return restTotal - rest\n }\n \n def mark(toMark: List[Station], end: Long): List[Station] = {\n var result = List[Station]()\n var prevCoord = end\n var broken = false\n for (st <- toMark) {\n val diff = prevCoord - st.coordinate\n prevCoord = st.coordinate\n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n st.ex_value = -1\n } else {\n st.O_value = diff\n st.ex_value = st.O_value\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist(result, st, rest)\n st.O_value = st.O_value + redisted\n st.ex_value = st.O_value\n }\n }\n result = st :: result\n printMarks(result)\n }\n result\n }\n \n def printMarks(marks: List[Station]) {\n if (!debugMode) return\n var str = \"\"\n for(st <- marks) {\n str += st.toString() + \" -> \"\n }\n println(str)\n }\n \n def debug(str: String) {\n if (debugMode)\n println(str)\n }\n \n //mark\n val marked = mark(stations, e_total)\n debug(\"------- MARKED -------\")\n\n //update total\n for (st <- stations) {\n updateTotal(st)\n }\n printMarks(marked)\n debug(\"------- TOTALLED -------\")\n \n //calc starts\n for (point <- starts) {\n calcPoint(point)\n }\n \n def calcPoint(point: Long) {\n val finalStart = point + s_tank\n if (finalStart >= e_total) {\n printRes(0,0)\n return\n }\n val li = findStList(point, marked)\n if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {\n printRes(-1,-1)\n return\n }\n val spli = split(li, point + s_tank)\n val left = new Station(3, point) :: spli._1\n var right1 = 0l\n var right2 = 0l\n if (spli._2 != null) {\n right1 = spli._2.total_1\n right2 = spli._2.total_2\n }\n if (spli._1 == Nil) {\n printRes(right1, right2)\n return\n }\n val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}\n \n val leftRev = left.reverse\n val subMarked = mark(leftRev, subMax)\n total_1 = 0\n total_2 = 0\n total_3 = 0\n for (st <- leftRev) {\n updateTotal(st) \n }\n// println(\"SUB MARKET TOTALLED\")\n// printMarks(subMarked)\n var left1 = 0l\n var left2 = 0l\n if (subMarked != Nil) {\n left1 = subMarked.head.total_1\n left2 = subMarked.head.total_2\n }\n printRes(left1+right1, left2+right2)\n }\n \n def printRes(t92:Long, t95:Long) {\n println(t92 +\" \" + t95)\n }\n \n def split(li: List[Station], max: Long): (List[Station], Station) = {\n var result = List[Station]()\n for(st <- li) {\n if (st.coordinate >= max) {\n return (result, st)\n } else {\n result = new Station(st.typpe, st.coordinate) :: result\n }\n }\n return (result.reverse, null)\n }\n \n @tailrec\n def findStList(start: Long, li: List[Station]): List[Station] = {\n if (li == Nil || start < li.head.coordinate) li\n else findStList(start, li.tail)\n }\n \n def updateTotal(st:Station) = {\n if (st.broken) {\n total_1 = -1\n total_2 = -1\n total_3 = -1\n } else {\n st.typpe match {\n case 1 => total_1 += st.ex_value\n case 2 => total_2 += st.ex_value\n case 3 => total_3 += st.ex_value\n }\n }\n st.total_1 = total_1\n st.total_2 = total_2\n st.total_3 = total_3\n }\n \n\n }\n}"}, {"source_code": "import java.io._\nimport java.lang.Long\nimport scala.annotation.tailrec\n\n//581 E\nobject E_Kojo_And_Furarri {\n \n class Station(val typpe:Int, val coordinate:Long) {\n// var O_type = typpe; \n var O_value = 0l\n// var ex_type = 0;\n var ex_value = 0l\n var broken = false\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n \n \n override def toString(): String = {\n var str = \"\"\n var t = \"A\"\n typpe match {\n case 3 => t = \"A\"\n case 2 => t = \"B\"\n case 1 => t = \"C\"\n }\n str += coordinate + \"_\" + t\n if (broken) {\n str += \"-1\"\n } else {\n str += O_value + \"(\" + ex_value + \")\"\n str += \"[\" + total_1 + \",\" + total_2 + \"]\"\n }\n return str\n }\n }\n\n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var debugMode = false\n \n val line1 = br.readLine().split(\" \")\n val e_total = line1(0).toLong \n val s_tank = line1(1).toLong \n val n_stations = line1(2).toInt \n val m_points = line1(3).toInt \n\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val s_line = br.readLine().split(\" \")\n stations = new Station(s_line(0).toInt, s_line(1).toLong) :: stations\n }\n val line2 = br.readLine().split(\" \")\n var starts = List[Long]()\n for (i <- 0 until line2.length) {\n starts = line2(i).toLong :: starts\n }\n \n //test inp\n// val e_total = 8l \n// val s_tank = 4l \n// val n_stations = 1 \n// val m_points = 1 \n// var stations = List[Station](new Station(2, 4)).reverse\n// var starts = List[Long](0)\n//\n// debugMode = true\n// val e_total = 9l \n// val s_tank = 3l \n// val n_stations = 2 \n// val m_points = 3 \n// var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n// var starts = List[Long](-1, 0, 1)\n \n// val e_total = 20l \n// val s_tank = 9l \n// val n_stations = 2 \n// val m_points = 4 \n// var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse\n// var starts = List[Long](-1, 0, 1, 2) \n// \n// val e_total = 10l \n// val s_tank = 3l \n// val n_stations = 4 \n// val m_points = 1 \n// var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),\n// new Station(2, 8)).reverse\n// var starts = List[Long](1,0)\n\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n\n def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {\n var rest = restTotal\n for (next <- toRedis) {\n if (rest == 0 || next.typpe > st.typpe) return restTotal - rest\n val toReduce = Math.min(rest, next.ex_value)\n next.ex_value = next.ex_value - toReduce\n rest = rest - toReduce\n }\n return restTotal - rest\n }\n \n def mark(toMark: List[Station], end: Long): List[Station] = {\n var result = List[Station]()\n var prevCoord = end\n var broken = false\n for (st <- toMark) {\n val diff = prevCoord - st.coordinate\n prevCoord = st.coordinate\n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n st.ex_value = -1\n } else {\n st.O_value = diff\n st.ex_value = diff\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist(result, st, rest)\n st.O_value = st.O_value + redisted\n }\n }\n result = st :: result\n printMarks(result)\n }\n result\n }\n \n def printMarks(marks: List[Station]) {\n if (!debugMode) return\n var str = \"\"\n for(st <- marks) {\n str += st.toString() + \" -> \"\n }\n println(str)\n }\n \n def debug(str: String) {\n if (debugMode)\n println(str)\n }\n \n //mark\n val marked = mark(stations, e_total)\n debug(\"------- MARKED -------\")\n\n //update total\n for (st <- stations) {\n updateTotal(st)\n }\n printMarks(marked)\n debug(\"------- TOTALLED -------\")\n \n //calc starts\n for (point <- starts) {\n calcPoint(point)\n }\n \n def calcPoint(point: Long) {\n val finalStart = point + s_tank\n if (finalStart >= e_total) {\n printRes(0,0)\n return\n }\n val li = findStList(point, marked)\n if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {\n printRes(-1,-1)\n return\n }\n val spli = split(li, point + s_tank)\n val left = new Station(3, point) :: spli._1\n var right1 = 0l\n var right2 = 0l\n if (spli._2 != null) {\n right1 = spli._2.total_1\n right2 = spli._2.total_2\n }\n if (spli._1 == Nil) {\n printRes(right1, right2)\n return\n }\n val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}\n \n val leftRev = left.reverse\n val subMarked = mark(leftRev, subMax)\n total_1 = 0\n total_2 = 0\n total_3 = 0\n for (st <- leftRev) {\n updateTotal(st) \n }\n// println(\"SUB MARKET TOTALLED\")\n// printMarks(subMarked)\n var left1 = 0l\n var left2 = 0l\n if (subMarked != Nil) {\n left1 = subMarked.head.total_1\n left2 = subMarked.head.total_2\n }\n printRes(left1+right1, left2+right2)\n }\n \n def printRes(t92:Long, t95:Long) {\n println(t92 +\" \" + t95)\n }\n \n def split(li: List[Station], max: Long): (List[Station], Station) = {\n var result = List[Station]()\n for(st <- li) {\n if (st.coordinate >= max) {\n return (result, st)\n } else {\n result = new Station(st.typpe, st.coordinate) :: result\n }\n }\n return (result.reverse, null)\n }\n \n @tailrec\n def findStList(start: Long, li: List[Station]): List[Station] = {\n if (li == Nil || start < li.head.coordinate) li\n else findStList(start, li.tail)\n }\n \n def updateTotal(st:Station) = {\n if (st.broken) {\n total_1 = -1\n total_2 = -1\n total_3 = -1\n } else {\n st.typpe match {\n case 1 => total_1 += st.ex_value\n case 2 => total_2 += st.ex_value\n case 3 => total_3 += st.ex_value\n }\n }\n st.total_1 = total_1\n st.total_2 = total_2\n st.total_3 = total_3\n }\n \n\n }\n}"}, {"source_code": "\nimport java.io._\nimport java.util.ArrayList\n\nobject E_Kojo_And_Furarri_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 class Station(val typpe:Int, val coord:Long) {\n var used = 0l\n var total1 = 0l\n var total2 = 0l\n var total3 = 0l\n var broken = false\n var start = false\n var startInd = 0l\n override def toString(): String = {\n var str = coord + \"_\" + typeStr(typpe) + used + \"[\" + total1 + \",\" + total2 + \"]\"\n if (start) str = \"s\" + str\n return str\n }\n def setupTotal(next:Station) = {\n if (next != null) {\n total1 = next.total1\n total2 = next.total2\n total3 = next.total3\n }\n typpe match {\n case 3 => total3 += used\n case 2 => total2 += used\n case 1 => total1 += used\n }\n }\n def incrTotal(value:Long) = {\n typpe match {\n case 3 => total3 += value\n case 2 => total2 += value\n case 1 => total1 += value\n }\n }\n \n \n def decrTotal(v1:Long, v2:Long) = {\n total1 -= v1\n total2 -= v2\n }\n }\n def typeStr(typpe:Int) = {\n typpe match {\n case 3 => \"A\"\n case 2 => \"B\"\n case 1 => \"C\"\n }\n }\n \n// val is = System.in\n \n //COMMENT ME !\n val is = new ByteArrayInputStream(s9.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 e_total = line1(0).toLong\n val s_tank = line1(1).toLong\n val n_stations = line1(2).toInt\n val m_points = line1(3).toInt\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val line = br.readLine().trim().split(\" \")\n stations ::= new Station(line(0).toInt, line(1).toInt)\n }\n stations = stations.filter(_.coord < e_total)\n db(stations.mkString(\" -> \"))\n db(\"AFTER STATIONS LOADED\")\n var starts = List[Station]()\n val line2 = br.readLine().split(\" \")\n for (i <- 0 until line2.length) {\n val start = new Station(3, line2(i).toLong)\n start.start = true;\n start.startInd = i\n stations ::= start\n starts ::= start\n }\n stations = stations.sortWith { (a,b) => a.coord > b.coord}\n db(stations.mkString(\" -> \"))\n db(\"AFTER STARTS LOADED\")\n //---------------------------- parameters reading end --------------------------------\n \n var resSize = 0\n var prevCoord = e_total\n var next:Station = null\n var broken = false\n var processed = List[Station]()\n var toProcess = stations\n while (resSize < m_points) {\n val st = toProcess.head\n if (st.coord == 100) {\n db(\"here\")\n }\n val diff = prevCoord - st.coord \n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n } else { \n st.used = diff\n st.setupTotal(next)\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist(processed, st, rest)\n st.used = st.used + redisted._1\n st.incrTotal(redisted._1)\n st.decrTotal(redisted._2, redisted._3)\n }\n }\n \n if (st.start) {\n resSize += 1\n db(st.coord + \": \" + stations.mkString(\" -> \"))\n } else {\n next = st\n prevCoord = st.coord\n processed ::= st\n }\n toProcess = toProcess.tail\n }\n \n starts = starts.sortWith{(a,b) => a.startInd < b.startInd }\n \n for(st <- starts) {\n if (debugV) print(st.coord + \": \")\n if (st.broken) {\n println(\"-1 -1\") \n } else {\n println(st.total1 + \" \" + st.total2)\n }\n }\n \n def redist(li: List[Station], st:Station, rest:Long):(Long,Long,Long) = {\n if (li == Nil || rest == 0) { return (0,0,0) }\n var result = 0l\n var result1 = 0l\n var result2 = 0l\n val next = li.head\n var toReduce = 0l\n if (next.typpe < st.typpe) {\n toReduce = Math.min(rest, next.used)\n if (!st.start) { //save only for real station\n next.used = next.used- toReduce\n }\n if (next.typpe == 1) {\n result1 = toReduce\n } else if (next.typpe == 2) {\n result2 = toReduce\n }\n val left = rest - toReduce\n result = toReduce\n val other = redist(li.tail, st, left)\n result += other._1\n result1 += other._2\n result2 += other._3\n }\n return (result, result1, result2)\n }\n \n\n }\n \n//========================= samples ======================== \nval sa1 = \"\"\"\n8 4 1 1\n2 4\n0\n\"\"\"\n\nval sa2 = \"\"\"\n9 3 2 3\n2 3\n1 6\n-1 0 1\n\"\"\"\n\nval sa3 = \"\"\"\n20 9 2 4\n1 5\n2 10\n-1 0 1 2\n\"\"\"\n\nval s7 = \"\"\"\n67 10 9 10\n3 -1\n1 59\n1 39\n1 -11\n2 29\n1 9\n1 19\n1 49\n3 77\n27 14 21 36 0 13 57 41 20 28\n\"\"\"\n\nval s8 = \"\"\"\n216 15 19 10\n2 -31\n2 100\n3 230\n1 57\n3 42\n1 157\n2 186\n1 113\n2 -16\n3 245\n2 142\n1 86\n2 -3\n3 201\n3 128\n3 12\n3 171\n2 27\n2 72\n98 197 114 0 155 35 36 11 146 27\n\"\"\"\n\nval s9 = \"\"\"\n386 20 29 30\n1 349\n2 482\n1 112\n1 93\n2 189\n1 207\n2 35\n2 -5\n1 422\n1 442\n1 402\n2 238\n3 258\n3 54\n2 369\n2 290\n2 329\n3 74\n3 -62\n2 170\n1 462\n2 15\n2 222\n1 309\n3 150\n1 -25\n3 130\n1 271\n1 -43\n351 250 91 102 0 286 123 93 100 205 328 269 188 83 73 35 188 223 73 215 199 64 47 379 61 298 295 65 158 211\n\"\"\"\n//========================= samples end ==================== \n}"}, {"source_code": "import java.io._\nimport java.lang.Long\nimport scala.annotation.tailrec\n\n//#322 (Div. 2) E\n//581/problem/E \nobject E_Kojo_And_Furarri {\n \n class Station(val typpe:Int, val coordinate:Long) {\n var O_value = 0l\n var ex_value = 0l\n var broken = false\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n \n override def toString(): String = {\n var str = \"\"\n var t = \"A\"\n typpe match {\n case 3 => t = \"A\"\n case 2 => t = \"B\"\n case 1 => t = \"C\"\n }\n str += coordinate + \"_\" + t\n if (broken) {\n str += \"-1\"\n } else {\n str += O_value + \"(\" + ex_value + \")\"\n str += \"[\" + total_1 + \",\" + total_2 + \"]\"\n }\n return str\n }\n }\n\n def main(args: Array[String]): Unit = {\n val bis = new BufferedInputStream(System.in);\n val br = new BufferedReader(new InputStreamReader(bis));\n var debugMode = false\n\n val line1 = br.readLine().split(\" \")\n val e_total = line1(0).toLong\n val s_tank = line1(1).toLong\n val n_stations = line1(2).toInt\n val m_points = line1(3).toInt\n\n var stations = List[Station]()\n for (i <- 0 until n_stations) {\n val s_line = br.readLine().split(\" \")\n stations = new Station(s_line(0).toInt, s_line(1).toLong) :: stations\n }\n val line2 = br.readLine().split(\" \")\n var starts = List[Long]()\n for (i <- 0 until line2.length) {\n starts = line2(i).toLong :: starts\n }\n starts = starts.reverse\n\n //test inp\n // val e_total = 8l \n // val s_tank = 4l \n // val n_stations = 1 \n // val m_points = 1 \n // var stations = List[Station](new Station(2, 4)).reverse\n // var starts = List[Long](0)\n //\n // debugMode = true\n // val e_total = 9l \n // val s_tank = 3l \n // val n_stations = 2 \n // val m_points = 3 \n // var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n // var starts = List[Long](-1, 0, 1)\n\n // val e_total = 20l \n // val s_tank = 9l \n // val n_stations = 2 \n // val m_points = 4 \n // var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse\n // var starts = List[Long](-1, 0, 1, 2) \n // \n // val e_total = 10l \n // val s_tank = 3l \n // val n_stations = 4 \n // val m_points = 1 \n // var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),\n // new Station(2, 8)).reverse\n // var starts = List[Long](1,0)\n\n // val e_total = 9l\n // val s_tank = 3l\n // val n_stations = 2\n // val m_points = 3\n // var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse\n // var starts = List[Long](-1, 0, 1)\n \n// debugMode = true\n// val e_total = 18l\n// val s_tank = 9l\n// val n_stations = 2\n// val m_points = 1\n// var stations = List[Station](new Station(2, 9), new Station(1, 12)).reverse\n// var starts = List[Long](0) \n\n var total_1 = 0l\n var total_2 = 0l\n var total_3 = 0l\n\n def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {\n var rest = restTotal\n for (next <- toRedis) {\n if (rest == 0 || next.typpe > st.typpe) return restTotal - rest\n val toReduce = Math.min(rest, next.ex_value)\n next.ex_value = next.ex_value - toReduce\n rest = rest - toReduce\n }\n return restTotal - rest\n }\n \n def mark(toMark: List[Station], end: Long): List[Station] = {\n var result = List[Station]()\n var prevCoord = end\n var broken = false\n for (st <- toMark) {\n val diff = prevCoord - st.coordinate\n prevCoord = st.coordinate\n if (broken || diff > s_tank) {\n broken = true\n st.broken = broken\n st.ex_value = -1\n } else {\n st.O_value = diff\n st.ex_value = st.O_value\n val rest = s_tank - diff\n if (st.typpe > 1 && rest > 0) {\n val redisted = redist(result, st, rest)\n st.O_value = st.O_value + redisted\n st.ex_value = st.O_value\n }\n }\n result = st :: result\n printMarks(result)\n }\n result\n }\n \n def printMarks(marks: List[Station]) {\n if (!debugMode) return\n var str = \"\"\n for(st <- marks) {\n str += st.toString() + \" -> \"\n }\n println(str)\n }\n \n def debug(str: String) {\n if (debugMode)\n println(str)\n }\n \n //mark\n val marked = mark(stations, e_total)\n debug(\"------- MARKED -------\")\n\n //update total\n for (st <- stations) {\n updateTotal(st)\n }\n printMarks(marked)\n debug(\"------- TOTALLED -------\")\n \n //calc starts\n for (point <- starts) {\n calcPoint(point)\n }\n \n def calcPoint(point: Long) {\n val finalStart = point + s_tank\n if (finalStart >= e_total) {\n printRes(0,0)\n return\n }\n val li = findStList(point, marked)\n if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {\n printRes(-1,-1)\n return\n }\n val spli = split(li, point + s_tank)\n val left = new Station(3, point) :: spli._1\n var right1 = 0l\n var right2 = 0l\n if (spli._2 != null) {\n right1 = spli._2.total_1\n right2 = spli._2.total_2\n }\n if (spli._1 == Nil) {\n printRes(right1, right2)\n return\n }\n val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}\n \n val leftRev = left.reverse\n val subMarked = mark(leftRev, subMax)\n total_1 = 0\n total_2 = 0\n total_3 = 0\n for (st <- leftRev) {\n updateTotal(st) \n }\n// println(\"SUB MARKET TOTALLED\")\n// printMarks(subMarked)\n var left1 = 0l\n var left2 = 0l\n if (subMarked != Nil) {\n left1 = subMarked.head.total_1\n left2 = subMarked.head.total_2\n }\n printRes(left1+right1, left2+right2)\n }\n \n def printRes(t92:Long, t95:Long) {\n println(t92 +\" \" + t95)\n }\n \n def split(li: List[Station], max: Long): (List[Station], Station) = {\n var result = List[Station]()\n for(st <- li) {\n if (st.coordinate >= max) {\n return (result, st)\n } else {\n result = new Station(st.typpe, st.coordinate) :: result\n }\n }\n return (result.reverse, null)\n }\n \n @tailrec\n def findStList(start: Long, li: List[Station]): List[Station] = {\n if (li == Nil || start < li.head.coordinate) li\n else findStList(start, li.tail)\n }\n \n def updateTotal(st:Station) = {\n if (st.broken) {\n total_1 = -1\n total_2 = -1\n total_3 = -1\n } else {\n st.typpe match {\n case 1 => total_1 += st.ex_value\n case 2 => total_2 += st.ex_value\n case 3 => total_3 += st.ex_value\n }\n }\n st.total_1 = total_1\n st.total_2 = total_2\n st.total_3 = total_3\n }\n \n\n }\n}"}], "src_uid": "c3f4dde88504b829f2b18439ebe32305"} {"nl": {"description": "Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.", "output_spec": "Print the total minimum number of moves.", "sample_inputs": ["6\n1 6 2 5 3 7"], "sample_outputs": ["12"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Your company was appointed to lay new asphalt on the highway of length $$$n$$$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $$$g$$$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $$$b$$$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $$$g$$$ good days, $$$b$$$ bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days $$$1, 2, \\dots, g$$$ are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $$$n = 5$$$ then at least $$$3$$$ units of the highway should have high quality; if $$$n = 4$$$ then at least $$$2$$$ units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 10^4$$$) \u2014 the number of test cases. Next $$$T$$$ lines contain test cases \u2014 one per line. Each line contains three integers $$$n$$$, $$$g$$$ and $$$b$$$ ($$$1 \\le n, g, b \\le 10^9$$$) \u2014 the length of the highway and the number of good and bad days respectively.", "output_spec": "Print $$$T$$$ integers \u2014 one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.", "sample_inputs": ["3\n5 1 1\n8 10 10\n1000000 1 1000000"], "sample_outputs": ["5\n8\n499999500000"], "notes": "NoteIn the first test case, you can just lay new asphalt each day, since days $$$1, 3, 5$$$ are good.In the second test case, you can also lay new asphalt each day, since days $$$1$$$-$$$8$$$ are good."}, "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 var Array(n,g,b) = readArrayInt().map(_.toLong)\n val ng = n / 2 + n % 2\n\n val minTotal = n / (g + b)*(g + b) + n % (g + b)\n val minG = ng / g * g + ng % g + (ng / g - (if (ng % g == 0) 1 else 0))* b\n\n println(math.max(minTotal, minG))\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}\n"}], "negative_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 var Array(n,g,b) = readArrayInt().map(_.toLong)\n val ng = n / 2 + n % 2\n\n val minTotal = n / (g + b)*(g + b) + n % (g + b)\n val minG = ng / g * g + ng % g + (ng / g - 1)* b\n\n println(math.max(minTotal, minG))\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}\n"}], "src_uid": "be9138aca8e1b8a5d722f99fcd70b685"} {"nl": {"description": "Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u,\u2009v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .", "input_spec": "The first line of input contains an integer n\u00a0\u2014 the number of nodes in the tree (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next n\u2009-\u20091 lines contain integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, u\u2009\u2260\u2009v)\u00a0\u2014 the description of the edges of the tree. It's guaranteed that the given graph is a tree. ", "output_spec": "Output one integer\u00a0\u2014 the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.", "sample_inputs": ["3\n1 2\n1 3", "5\n1 2\n2 3\n3 4\n4 5"], "sample_outputs": ["0", "2"], "notes": "NoteTree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)Bipartite graph definition: https://en.wikipedia.org/wiki/Bipartite_graphIn the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2,\u20093), but adding this edge will make the graph non-bipartite so the answer is 0.In the second test case Mahmoud and Ehab can add edges (1,\u20094) and (2,\u20095). "}, "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 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}"}, {"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"} {"nl": {"description": "Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life \u00abinteresting graph and apples\u00bb. An undirected graph is called interesting, if each of its vertices belongs to one cycle only \u2014 a funny ring \u2014 and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1,\u2009y1),\u2009(x2,\u2009y2),\u2009...,\u2009(xn,\u2009yn), where xi\u2009\u2264\u2009yi, is lexicographically smaller than the set (u1,\u2009v1),\u2009(u2,\u2009v2),\u2009...,\u2009(un,\u2009vn), where ui\u2009\u2264\u2009vi, provided that the sequence of integers x1,\u2009y1,\u2009x2,\u2009y2,\u2009...,\u2009xn,\u2009yn is lexicographically smaller than the sequence u1,\u2009v1,\u2009u2,\u2009v2,\u2009...,\u2009un,\u2009vn. If you do not cope, Hexadecimal will eat you. ...eat you alive.", "input_spec": "The first line of the input data contains a pair of integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200950, 0\u2009\u2264\u2009m\u2009\u2264\u20092500) \u2014 the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1\u2009\u2264\u2009xi, yi\u2009\u2264\u2009n) \u2014 the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.", "output_spec": "In the first line output \u00abYES\u00bb or \u00abNO\u00bb: if it is possible or not to construct an interesting graph. If the answer is \u00abYES\u00bb, in the second line output k \u2014 the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.", "sample_inputs": ["3 2\n1 2\n2 3"], "sample_outputs": ["YES\n1\n1 3"], "notes": null}, "positive_code": [{"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject IntersetRing extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n var loop = false\n\n val vis = Array.ofDim[Boolean](n)\n\n val graph = Array.ofDim[Int](n, n)\n val deg = Array.ofDim[Int](n)\n\n val result = ArrayBuffer.empty[(Int, Int)]\n\n (0 until m).foreach { _ =>\n val (a, b) = (s.nextInt(), s.nextInt())\n connect(a - 1, b - 1)\n }\n\n def connect(a: Int, b: Int): Unit = {\n if (a == b) {\n loop = true\n }\n graph(a)(b) += 1\n graph(b)(a) += 1\n deg(a) += 1\n deg(b) += 1\n }\n\n if (n < m || deg.exists(_ > 2) || (loop && n > 1)) {\n println(\"NO\")\n } else if (n == m && connected()) {\n println(\"YES\")\n println(\"0\")\n } else {\n for {\n i <- 0 until n\n j <- 0 until n\n } {\n if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {\n connect(i, j)\n result.append((i, j))\n }\n }\n val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted\n if (rest.size > 1) {\n println(\"YES\")\n result.append((rest(0), rest(1)))\n println(result.size)\n result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + \" \" + x._2))\n } else if (n == 1 && m == 0) {\n println(\"YES\")\n println(\"1\")\n println(\"1 1\")\n } else {\n println(\"NO\")\n }\n\n }\n\n\n def reachable(a: Int, b: Int): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(a)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) == 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r(b)\n }\n\n def connected(): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(0)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) >= 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r.forall(x => x)\n }\n\n}\n"}], "negative_code": [{"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject IntersetRing extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n var loop = false\n\n val vis = Array.ofDim[Boolean](n)\n\n val graph = Array.ofDim[Int](n, n)\n val deg = Array.ofDim[Int](n)\n\n val result = ArrayBuffer.empty[(Int, Int)]\n\n (0 until m).foreach { _ =>\n val (a, b) = (s.nextInt(), s.nextInt())\n connect(a - 1, b - 1)\n }\n\n def connect(a: Int, b: Int): Unit = {\n if (a == b) {\n loop = true\n }\n graph(a)(b) += 1\n graph(b)(a) += 1\n deg(a) += 1\n deg(b) += 1\n }\n\n if (n < m || deg.exists(_ > 2) || (loop && n > 1) || graph.exists(_.exists(x => x > 1))) {\n println(\"NO\")\n } else if (n == m && connected()) {\n println(\"YES\")\n println(\"0\")\n } else {\n println(\"YES\")\n for {\n i <- 0 until n\n j <- 0 until n\n } {\n if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {\n connect(i, j)\n result.append((i, j))\n }\n }\n val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted\n result.append((rest(0), rest(1)))\n println(result.size)\n result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + \" \" + x._2))\n }\n\n\n def reachable(a: Int, b: Int): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(a)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) == 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r(b)\n }\n\n def connected(): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(0)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) >= 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r.forall(x => x)\n }\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject IntersetRing extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n var loop = false\n\n val vis = Array.ofDim[Boolean](n)\n\n val graph = Array.ofDim[Int](n, n)\n val deg = Array.ofDim[Int](n)\n\n val result = ArrayBuffer.empty[(Int, Int)]\n\n (0 until m).foreach { _ =>\n val (a, b) = (s.nextInt(), s.nextInt())\n connect(a - 1, b - 1)\n }\n\n def connect(a: Int, b: Int): Unit = {\n if (a == b) {\n loop = true\n }\n graph(a)(b) += 1\n graph(b)(a) += 1\n deg(a) += 1\n deg(b) += 1\n }\n\n if (n < m || deg.exists(_ > 2) || (graph.exists(_.exists(x => x > 1)) && n > 1)) {\n println(\"NO\")\n } else if (n == m && connected()) {\n println(\"YES\")\n println(\"0\")\n } else {\n println(\"YES\")\n for {\n i <- 0 until n\n j <- 0 until n\n } {\n if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {\n connect(i, j)\n result.append((i, j))\n }\n }\n val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted\n result.append((rest(0), rest(1)))\n println(result.size)\n result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + \" \" + x._2))\n }\n\n\n def reachable(a: Int, b: Int): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(a)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) == 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r(b)\n }\n\n def connected(): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(0)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) >= 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r.forall(x => x)\n }\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject IntersetRing extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n var loop = false\n\n val vis = Array.ofDim[Boolean](n)\n\n val graph = Array.ofDim[Int](n, n)\n val deg = Array.ofDim[Int](n)\n\n val result = ArrayBuffer.empty[(Int, Int)]\n\n (0 until m).foreach { _ =>\n val (a, b) = (s.nextInt(), s.nextInt())\n connect(a - 1, b - 1)\n }\n\n def connect(a: Int, b: Int): Unit = {\n if (a == b) {\n loop = true\n }\n graph(a)(b) += 1\n graph(b)(a) += 1\n deg(a) += 1\n deg(b) += 1\n }\n\n if (n < m || deg.exists(_ > 2) || (loop && n > 1)) {\n println(\"NO\")\n } else if (n == m && connected()) {\n println(\"YES\")\n println(\"0\")\n } else {\n for {\n i <- 0 until n\n j <- 0 until n\n } {\n if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {\n connect(i, j)\n result.append((i, j))\n }\n }\n val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted\n if (rest.size > 2) {\n println(\"YES\")\n result.append((rest(0), rest(1)))\n println(result.size)\n result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + \" \" + x._2))\n } else {\n println(\"NO\")\n }\n\n }\n\n\n def reachable(a: Int, b: Int): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(a)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) == 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r(b)\n }\n\n def connected(): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(0)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) >= 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r.forall(x => x)\n }\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject IntersetRing extends App {\n\n val s = new Scanner(System.in)\n\n val n = s.nextInt()\n val m = s.nextInt()\n\n var loop = false\n\n val vis = Array.ofDim[Boolean](n)\n\n val graph = Array.ofDim[Int](n, n)\n val deg = Array.ofDim[Int](n)\n\n val result = ArrayBuffer.empty[(Int, Int)]\n\n (0 until m).foreach { _ =>\n val (a, b) = (s.nextInt(), s.nextInt())\n connect(a - 1, b - 1)\n }\n\n def connect(a: Int, b: Int): Unit = {\n if (a == b) {\n loop = true\n }\n graph(a)(b) += 1\n graph(b)(a) += 1\n deg(a) += 1\n deg(b) += 1\n }\n\n if (n < m || deg.exists(_ > 2) || (loop && n > 1)) {\n println(\"NO\")\n } else if (n == m && connected()) {\n println(\"YES\")\n println(\"0\")\n } else {\n for {\n i <- 0 until n\n j <- 0 until n\n } {\n if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {\n connect(i, j)\n result.append((i, j))\n }\n }\n val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted\n if (rest.size > 1) {\n println(\"YES\")\n result.append((rest(0), rest(1)))\n println(result.size)\n result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + \" \" + x._2))\n } else {\n println(\"NO\")\n }\n\n }\n\n\n def reachable(a: Int, b: Int): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(a)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) == 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r(b)\n }\n\n def connected(): Boolean = {\n val r = Array.ofDim[Boolean](n)\n val x = new java.util.LinkedList[Int]()\n var i = 0\n x.add(0)\n while (!x.isEmpty) {\n val cur = x.poll()\n r(cur) = true\n (0 until n).foreach { i =>\n if (graph(cur)(i) >= 1 && !r(i)) x.add(i)\n }\n i += 1\n }\n r.forall(x => x)\n }\n\n}\n"}], "src_uid": "bbcb051b08fa3d19a7cf285242d50451"} {"nl": {"description": "Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \\ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \\ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. ", "input_spec": "The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\leq u_i, v_i \\leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.", "output_spec": "Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \\ldots, a_n$$$ Bob can record.", "sample_inputs": ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"], "sample_outputs": ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"], "notes": "NoteIn the first sample, Bob's optimal wandering path could be $$$1 \\rightarrow 2 \\rightarrow 1 \\rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\\{1, 2, 3\\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \\rightarrow 4 \\rightarrow 3 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4 \\rightarrow 1 \\rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\\{1, 4, 3, 2, 5\\}$$$, which is the lexicographically smallest one."}, "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\n val (from, to) = na2(M, -1)\n val g = packUGraph(N, from, to)\n\n val visited = Array.ofDim[Boolean](N)\n val ans = ArrayBuffer[Int]()\n type Visit = Int\n val queue = new java.util.PriorityQueue[Visit]()\n queue.add(0)\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (!visited(v)) {\n visited(v) = true\n ans += v + 1\n\n REP(g(v).length) { i =>\n val e = g(v)(i)\n if (!visited(e)) {\n queue.add(e)\n }\n }\n }\n }\n\n out.println(ans.mkString(\" \"))\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 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": "157630371c4f6c3bcc6355d96c86a626"} {"nl": {"description": "You are given an array $$$A$$$, consisting of $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$, and an array $$$B$$$, consisting of $$$m$$$ positive integers $$$b_1, b_2, \\dots, b_m$$$. Choose some element $$$a$$$ of $$$A$$$ and some element $$$b$$$ of $$$B$$$ such that $$$a+b$$$ doesn't belong to $$$A$$$ and doesn't belong to $$$B$$$. For example, if $$$A = [2, 1, 7]$$$ and $$$B = [1, 3, 4]$$$, we can choose $$$1$$$ from $$$A$$$ and $$$4$$$ from $$$B$$$, as number $$$5 = 1 + 4$$$ doesn't belong to $$$A$$$ and doesn't belong to $$$B$$$. However, we can't choose $$$2$$$ from $$$A$$$ and $$$1$$$ from $$$B$$$, as $$$3 = 2 + 1$$$ belongs to $$$B$$$.It can be shown that such a pair exists. If there are multiple answers, print any.Choose and print any such two numbers.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1\\le n \\le 100$$$)\u00a0\u2014 the number of elements of $$$A$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 200$$$)\u00a0\u2014 the elements of $$$A$$$. The third line contains one integer $$$m$$$ ($$$1\\le m \\le 100$$$)\u00a0\u2014 the number of elements of $$$B$$$. The fourth line contains $$$m$$$ different integers $$$b_1, b_2, \\dots, b_m$$$ ($$$1 \\le b_i \\le 200$$$)\u00a0\u2014 the elements of $$$B$$$. It can be shown that the answer always exists.", "output_spec": "Output two numbers $$$a$$$ and $$$b$$$ such that $$$a$$$ belongs to $$$A$$$, $$$b$$$ belongs to $$$B$$$, but $$$a+b$$$ doesn't belong to nor $$$A$$$ neither $$$B$$$. If there are multiple answers, print any.", "sample_inputs": ["1\n20\n2\n10 20", "3\n3 2 2\n5\n1 5 7 7 9", "4\n1 3 5 7\n4\n7 5 3 1"], "sample_outputs": ["20 20", "3 1", "1 1"], "notes": "NoteIn the first example, we can choose $$$20$$$ from array $$$[20]$$$ and $$$20$$$ from array $$$[10, 20]$$$. Number $$$40 = 20 + 20$$$ doesn't belong to any of those arrays. However, it is possible to choose $$$10$$$ from the second array too.In the second example, we can choose $$$3$$$ from array $$$[3, 2, 2]$$$ and $$$1$$$ from array $$$[1, 5, 7, 7, 9]$$$. Number $$$4 = 3 + 1$$$ doesn't belong to any of those arrays.In the third example, we can choose $$$1$$$ from array $$$[1, 3, 5, 7]$$$ and $$$1$$$ from array $$$[7, 5, 3, 1]$$$. Number $$$2 = 1 + 1$$$ doesn't belong to any of those arrays."}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject A_1206 extends App {\n val n = readInt()\n val A = readLine().split(\" \").map(_.toInt)\n val m = readInt()\n val B = readLine().split(\" \").map(_.toInt)\n\n val AA = A.toSet\n val BB = B.toSet\n\n def find(): (Int, Int) = {\n for {\n i <- 0 until n\n j <- 0 until m\n } {\n val x = A(i) + B(j)\n if (!AA.contains(x) && !BB.contains(x)) {\n return (A(i), B(j))\n }\n }\n\n (0, 0)\n }\n\n val (a, b) = find()\n println(a + \" \" + b)\n}\n"}], "negative_code": [], "src_uid": "ec09b2df4ed3abbca4c47f48f12010ca"} {"nl": {"description": "Given a sequence $$$a_1, a_2, \\ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2,\\dots,a_n$$$ ($$$1\\leq a_i\\leq10^9$$$) \u2014 elements of the sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer \u2014 the minimum number of elements to remove from the sequence such that the sum of every $$$2$$$ consecutive elements is even.", "sample_inputs": ["2\n\n5\n\n2 4 3 6 8\n\n6\n\n3 5 9 7 1 3"], "sample_outputs": ["1\n0"], "notes": "NoteIn the first test case, after removing $$$3$$$, the sequence becomes $$$[2,4,6,8]$$$. The pairs of consecutive elements are $$$\\{[2, 4], [4, 6], [6, 8]\\}$$$. Each consecutive pair has an even sum now. Hence, we only need to remove $$$1$$$ element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai\u00a0\u2014 pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of gifts. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the pleasantness of the gifts. The next (n\u2009-\u20091) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi)\u00a0\u2014 the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.", "output_spec": "If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer\u00a0\u2014 the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.", "sample_inputs": ["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"], "sample_outputs": ["25", "2", "Impossible"], "notes": null}, "positive_code": [{"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 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"}, {"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\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"} {"nl": {"description": "Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \\times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \\le n, m \\le 1000$$$, $$$1 \\le p \\le 9$$$)\u00a0\u2014 the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \\le s \\le 10^9$$$)\u00a0\u2014 the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \\le x \\le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.", "output_spec": "Print $$$p$$$ integers\u00a0\u2014 the number of cells controlled by each player after the game ends.", "sample_inputs": ["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"], "sample_outputs": ["6 3", "1 4 3 3"], "notes": "NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is \"blocked\" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left."}, "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.util\n val N, M, P = ni()\n val S = na(P)\n val g = nm_c(N, M)\n\n val CHARS = \"123456789\"\n\n def pos(n: Int, m: Int) = n * M + m\n val q = Array.fill[mutable.Set[Int]](P)(mutable.Set())\n\n REP(N) { i =>\n REP(M) { j =>\n if (g(i)(j) != '.' && g(i)(j) != '#') {\n q(g(i)(j) - '1').add(pos(i, j))\n }\n }\n }\n\n def canMove(n: Int, m: Int): Boolean = {\n n >= 0 && n < N && m >= 0 && m < M && g(n)(m) == '.'\n }\n\n val X = Array(-1, 1, 0, 0)\n val Y = Array(0, 0, -1, 1)\n\n /**\n * q(p)\u304b\u3089\u306f\u3058\u3081\u3066\u3001S(p)\u56de\u79fb\u52d5\u3057\u3066'.'\u3092\u901a\u3063\u3066\u3044\u3051\u308b\u5834\u6240\u5168\u90e8\n * \u901a\u3063\u305f\u3068\u3053\u308d\u306fp+1\u3067\u5857\u308a\u3064\u3076\u3059\n */\n def bfs(p: Int) {\n var s = S(p)\n\n while(s > 0 && q(p).nonEmpty) {\n val next = mutable.Set[Int]()\n q(p).foreach { x =>\n val n = x / M\n val m = x % M\n\n REP(4) { i =>\n val nn = n + X(i)\n val mm = m + Y(i)\n if (canMove(nn, mm)) {\n g(nn)(mm) = CHARS(p)\n next += pos(nn, mm)\n }\n }\n\n }\n q(p) = next\n s -= 1\n }\n }\n\n while (!q.forall(_.isEmpty)) {\n REP(P) { p =>\n bfs(p)\n }\n }\n\n// REP(N) { i =>\n// debug(g(i).mkString)\n// }\n\n val ans = Array.ofDim[Int](P)\n REP(N) { i =>\n REP(M) { j =>\n if (g(i)(j) != '.' && g(i)(j) != '#') {\n ans(g(i)(j) - '1') += 1\n }\n }\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}"}], "negative_code": [], "src_uid": "015d7871f6560b90d9efe3375f91cce7"} {"nl": {"description": "Allen is hosting a formal dinner party. $$$2n$$$ people come to the event in $$$n$$$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $$$2n$$$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$), the number of pairs of people. The second line contains $$$2n$$$ integers $$$a_1, a_2, \\dots, a_{2n}$$$. For each $$$i$$$ with $$$1 \\le i \\le n$$$, $$$i$$$ appears exactly twice. If $$$a_j = a_k = i$$$, that means that the $$$j$$$-th and $$$k$$$-th people in the line form a couple.", "output_spec": "Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.", "sample_inputs": ["4\n1 1 2 3 3 2 4 4", "3\n1 1 2 2 3 3", "3\n3 1 2 3 1 2"], "sample_outputs": ["2", "0", "3"], "notes": "NoteIn the first sample case, we can transform $$$1 1 2 3 3 2 4 4 \\rightarrow 1 1 2 3 2 3 4 4 \\rightarrow 1 1 2 2 3 3 4 4$$$ in two steps. Note that the sequence $$$1 1 2 3 3 2 4 4 \\rightarrow 1 1 3 2 3 2 4 4 \\rightarrow 1 1 3 3 2 2 4 4$$$ also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need $$$0$$$ swaps."}, "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.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}"}, {"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"} {"nl": {"description": "Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application. In one secret game developed deep in the ZeptoLab company, the game universe consists of n levels, located in a circle. You can get from level i to levels i\u2009-\u20091 and i\u2009+\u20091, also you can get from level 1 to level n and vice versa. The map of the i-th level description size is ai bytes.In order to reduce the transmitted traffic, the game gets levels as follows. All the levels on the server are divided into m groups and each time a player finds himself on one of the levels of a certain group for the first time, the server sends all levels of the group to the game client as a single packet. Thus, when a player travels inside the levels of a single group, the application doesn't need any new information. Due to the technical limitations the packet can contain an arbitrary number of levels but their total size mustn't exceed b bytes, where b is some positive integer constant.Usual situation is that players finish levels one by one, that's why a decision was made to split n levels into m groups so that each group was a continuous segment containing multiple neighboring levels (also, the group can have two adjacent levels, n and 1). Specifically, if the descriptions of all levels have the total weight of at most b bytes, then they can all be united into one group to be sent in a single packet.Determine, what minimum number of groups do you need to make in order to organize the levels of the game observing the conditions above?As developing a game is a long process and technology never stagnates, it is yet impossible to predict exactly what value will take constant value b limiting the packet size when the game is out. That's why the developers ask you to find the answer for multiple values of b.", "input_spec": "The first line contains two integers n, q (2\u2009\u2264\u2009n\u2009\u2264\u2009106, 1\u2009\u2264\u2009q\u2009\u2264\u200950) \u2014 the number of levels in the game universe and the number of distinct values of b that you need to process. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the sizes of the levels in bytes. The next q lines contain integers bj (), determining the values of constant b, for which you need to determine the answer.", "output_spec": "For each value of kj from the input print on a single line integer mj (1\u2009\u2264\u2009mj\u2009\u2264\u2009n), determining the minimum number of groups to divide game levels into for transmission via network observing the given conditions. ", "sample_inputs": ["6 3\n2 4 2 1 3 2\n7\n4\n6"], "sample_outputs": ["2\n4\n3"], "notes": "NoteIn the test from the statement you can do in the following manner. at b\u2009=\u20097 you can divide into two segments: 2|421|32 (note that one of the segments contains the fifth, sixth and first levels); at b\u2009=\u20094 you can divide into four segments: 2|4|21|3|2; at b\u2009=\u20096 you can divide into three segments: 24|21|32|. "}, "positive_code": [{"source_code": "object 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\n val Array(n, q) = readInts(2)\n val as = readLongs(n)\n val rs = Array.ofDim[Int](n)\n val levels, last = Array.ofDim[Int](n + 1)\n levels(n) = 0\n last(n) = n\n\n for (p <- 0 until q) {\n\n val Array(b) = readLongs(1)\n\n var l, r = 0\n var lrSum = 0L\n while (r < n) {\n if (lrSum + as(r) <= b) {\n lrSum += as(r)\n r += 1\n } else {\n rs(l) = r\n lrSum -= as(l)\n l += 1\n }\n }\n\n while (l < n) {\n rs(l) = n\n l += 1\n }\n \n for (i <- n - 1 to 0 by -1) {\n if (rs(i) == n) {\n levels(i) = 0\n last(i) = i//n - 1\n } else {\n levels(i) = levels(rs(i)) + 1\n last(i) = if (levels(i) == 1) rs(i) else last(rs(i)) \n }\n }\n\n l = 0\n var firstSum = 0L\n while (l < n && firstSum + as(l) <= b) {\n firstSum += as(l)\n l += 1\n }\n\n r = n - 1\n while (r > l && firstSum + as(r) <= b) {\n firstSum += as(r)\n r -= 1\n }\n r += 1\n\n var minLevelCount = Int.MaxValue\n\n while (l > 0) {\n\n var levelCount = levels(l) + 1\n if (last(l) < r) levelCount += 1\n\n if (levelCount < minLevelCount) minLevelCount = levelCount\n\n l -= 1\n if (l >= 0) {\n firstSum -= as(l)\n\n while (r - 1 > l && firstSum + as(r - 1) <= b) {\n r -= 1\n firstSum += as(r)\n }\n }\n }\n\n println(minLevelCount)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection._\nimport java.util.Arrays\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, q) = readInts(2)\n val as = readLongs(n)\n val pSums = as.scan(0L)(_ + _)\n val total = pSums.last\n\n for (p <- 0 until q) {\n \n val Array(b) = readLongs(1)\n var bestStartSum = -1L\n var bestStart = 0\n var bestEnd = 0\n var start = 1\n \n while (start <= n && pSums(start) <= b) {\n val remain = b - pSums(start)\n val forEnd = total - remain\n val end0 = Arrays.binarySearch(pSums, forEnd)\n val end1 = if (end0 >= 0) end0 else -end0 - 1\n val end = end1 max start\n val startSum = pSums(start) + (total - pSums(end))\n if (startSum > bestStartSum) {\n bestStartSum = startSum\n bestStart = start\n bestEnd = end\n //println((bestStartSum, bestStart, bestEnd))\n }\n start += 1\n }\n \n var segments = 1\n var i = bestStart\n //println((bestStart, bestEnd))\n var currentSum = 0L\n while (i < bestEnd) {\n if (currentSum + as(i) > b) {\n segments += 1\n //println(i)\n if (i + 1 < bestEnd) {\n currentSum = as(i)\n i += 1\n } else currentSum = 0\n } else {\n currentSum += as(i)\n i += 1\n }\n }\n if (currentSum > 0L) segments += 1\n \n println(segments)\n }\n}\n"}, {"source_code": "import scala.collection._\nimport java.util.Arrays\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, q) = readInts(2)\n val as = readLongs(n)\n val pSums = as.scan(0L)(_ + _)\n val total = pSums.last\n\n for (p <- 0 until q) {\n \n val Array(b) = readLongs(1)\n var bestStartSum = -1L\n var bestStart = 0\n var bestEnd = 0\n var start = 1\n \n while (start <= n && pSums(start) <= b) {\n val remain = b - pSums(start)\n val forEnd = total - remain\n val end0 = Arrays.binarySearch(pSums, forEnd)\n val end1 = if (end0 >= 0) end0 else -end0 - 1\n val end = end1 max (start + 1)\n val startSum = pSums(start) + (total - pSums(end))\n if (startSum > bestStartSum) {\n bestStartSum = startSum\n bestStart = start\n bestEnd = end\n }\n start += 1\n }\n \n var segments = 1\n var i = bestStart\n //println((bestStart, bestEnd))\n var currentSum = 0L\n while (i < bestEnd) {\n if (currentSum + as(i) > b) {\n segments += 1\n //println(i)\n if (i + 1 < bestEnd) {\n currentSum = as(i)\n i += 1\n } else currentSum = 0\n } else {\n currentSum += as(i)\n i += 1\n }\n }\n if (currentSum > 0) segments += 1\n \n println(segments)\n }\n}\n"}, {"source_code": "object 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\n val Array(n, q) = readInts(2)\n val as = readLongs(n)\n val rs = Array.ofDim[Int](n)\n val levels, last = Array.ofDim[Int](n + 1)\n levels(n) = 0\n last(n) = n\n\n for (p <- 0 until q) {\n\n val Array(b) = readLongs(1)\n\n var l, r = 0\n var lrSum = 0L\n while (r < n) {\n if (lrSum + as(r) <= b) {\n lrSum += as(r)\n r += 1\n } else {\n rs(l) = r\n lrSum -= as(l)\n l += 1\n }\n }\n\n while (l < n) {\n rs(l) = n\n l += 1\n }\n \n for (i <- n - 1 to 0 by -1) {\n if (rs(i) == n) {\n levels(i) = 0\n last(i) = n\n } else {\n levels(i) = levels(rs(i)) + 1\n last(i) = if (levels(i) == 1) rs(i) else last(rs(i)) \n }\n }\n\n l = 0\n var firstSum = 0L\n while (l < n && firstSum + as(l) <= b) {\n firstSum += as(l)\n l += 1\n }\n\n r = n - 1\n while (r > l && firstSum + as(r) <= b) {\n firstSum += as(r)\n r -= 1\n }\n r += 1\n\n var minLevelCount = Int.MaxValue\n\n while (l >= 0) {\n\n var levelCount = levels(l) + 1\n if (last(l) < r) levelCount += 1\n\n if (levelCount < minLevelCount) minLevelCount = levelCount\n\n l -= 1\n if (l >= 0) {\n firstSum -= as(l)\n\n while (r - 1 > l && firstSum + as(r - 1) <= b) {\n r -= 1\n firstSum += as(r)\n }\n }\n }\n\n println(minLevelCount)\n }\n}\n"}, {"source_code": "import scala.collection._\nimport java.util.Arrays\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, q) = readInts(2)\n val as = readLongs(n)\n val pSums = as.scan(0L)(_ + _)\n val total = pSums.last\n\n for (p <- 0 until q) {\n \n val Array(b) = readInts(1)\n var bestStartSum = -1L\n var bestStart = 0\n var bestEnd = 0\n var start = 1\n \n while (start <= n && pSums(start) <= b) {\n val remain = b - pSums(start)\n val forEnd = total - remain\n val end0 = Arrays.binarySearch(pSums, forEnd)\n val end1 = if (end0 >= 0) end0 else -end0 - 1\n val end = end1 max (start + 1)\n val startSum = pSums(start) + (total - pSums(end))\n if (startSum > bestStartSum) {\n bestStartSum = startSum\n bestStart = start\n bestEnd = end\n }\n start += 1\n }\n \n var segments = 1\n var i = bestStart\n //println((bestStart, bestEnd))\n var currentSum = 0L\n while (i < bestEnd) {\n if (currentSum + as(i) > b) {\n segments += 1\n //println(i)\n if (i + 1 < bestEnd) {\n currentSum = as(i)\n i += 1\n } else currentSum = 0\n } else {\n currentSum += as(i)\n i += 1\n }\n }\n if (currentSum > 0) segments += 1\n \n println(segments)\n }\n}\n"}], "src_uid": "9d1e04867a37dd94cbc97279cd9b9c2b"} {"nl": {"description": "The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left.Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two \"put a coin\" instructions in a row.Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009300) \u2014 the number of wallets. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009300). It is guaranteed that at least one ai is positive.", "output_spec": "Print the sequence that consists of k (1\u2009\u2264\u2009k\u2009\u2264\u2009106) characters, each of them equals: \"L\", \"R\" or \"P\". Each character of the sequence is an instruction to the robot. Character \"L\" orders to move to the left, character \"R\" orders to move to the right, character \"P\" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions \"L\" if the robot is at wallet 1, or \"R\" at wallet n. As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.", "sample_inputs": ["2\n1 2", "4\n0 2 0 2"], "sample_outputs": ["PRPLRP", "RPRRPLLPLRRRP"], "notes": null}, "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": "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}"}, {"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"} {"nl": {"description": "You are given a sequence of positive integers x1,\u2009x2,\u2009...,\u2009xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves: subtract 1 from the current a; subtract a mod xi (1\u2009\u2264\u2009i\u2009\u2264\u2009n) from the current a. Operation a mod xi means taking the remainder after division of number a by number xi.Now you want to know the minimum number of moves needed to transform a into b.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers x1,\u2009x2,\u2009...,\u2009xn (2\u2009\u2264\u2009\u2009xi\u2009\u2264\u2009109). The third line contains two integers a and b (0\u2009\u2009\u2264\u2009b\u2009\u2264\u2009\u2009a\u2009\u2264\u2009109, a\u2009-\u2009b\u2009\u2264\u2009106).", "output_spec": "Print a single integer \u2014 the required minimum number of moves needed to transform number a into number b.", "sample_inputs": ["3\n3 4 5\n30 17", "3\n5 6 7\n1000 200"], "sample_outputs": ["6", "206"], "notes": null}, "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 n = readString.toInt\n val xs = readInts(n).distinct.sorted.reverse\n var Array(a, b) = readInts(2)\n\n var steps = 0\n \n if (xs.head > a && b == 0 && a > b) {\n steps = 1\n a = 0\n }\n \n var start = 0\n \n while (a > b) {\n var maxMod = 1\n while (start < xs.size && a - a % xs(start) < b) start += 1\n var i = start\n while (i < xs.size && xs(i) > maxMod) {\n val mod = a % xs(i)\n if (mod > maxMod && a - mod >= b) maxMod = mod\n i += 1\n }\n a -= maxMod\n steps += 1\n }\n \n println(steps)\n}"}], "negative_code": [], "src_uid": "b4c96c9c0fa10612a06cfd2a6a5cc417"} {"nl": {"description": "We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t \u0422-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is \u0422-prime or not.", "input_spec": "The first line contains a single positive integer, n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1\u2009\u2264\u2009xi\u2009\u2264\u20091012). Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is advised to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print n lines: the i-th line should contain \"YES\" (without the quotes), if number xi is \u0422-prime, and \"NO\" (without the quotes), if it isn't.", "sample_inputs": ["3\n4 5 6"], "sample_outputs": ["YES\nNO\nNO"], "notes": "NoteThe given test has three numbers. The first number 4 has exactly three divisors \u2014 1, 2 and 4, thus the answer for this number is \"YES\". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is \"NO\"."}, "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": "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}"}, {"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"} {"nl": {"description": "Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly $$$n$$$ flowers.Vladimir went to a flower shop, and he was amazed to see that there are $$$m$$$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $$$i$$$-th type happiness of his wife increases by $$$a_i$$$ and after receiving each consecutive flower of this type her happiness increases by $$$b_i$$$. That is, if among the chosen flowers there are $$$x_i > 0$$$ flowers of type $$$i$$$, his wife gets $$$a_i + (x_i - 1) \\cdot b_i$$$ additional happiness (and if there are no flowers of type $$$i$$$, she gets nothing for this particular type).Please help Vladimir to choose exactly $$$n$$$ flowers to maximize the total happiness of his wife.", "input_spec": "The first line contains the only integer $$$t$$$ ($$$1 \\leq t \\leq 10\\,000$$$), the number of test cases. It is followed by $$$t$$$ descriptions of the test cases. Each test case description starts with two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^9$$$, $$$1 \\le m \\le 100\\,000$$$), the number of flowers Vladimir needs to choose and the number of types of available flowers. The following $$$m$$$ lines describe the types of flowers: each line contains integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \\le a_i, b_i \\le 10^9$$$) for $$$i$$$-th available type of flowers. The test cases are separated by a blank line. It is guaranteed that the sum of values $$$m$$$ among all test cases does not exceed $$$100\\,000$$$.", "output_spec": "For each test case output a single integer: the maximum total happiness of Vladimir's wife after choosing exactly $$$n$$$ flowers optimally.", "sample_inputs": ["2\n4 3\n5 0\n1 4\n2 2\n\n5 3\n5 2\n4 2\n3 1"], "sample_outputs": ["14\n16"], "notes": "NoteIn the first example case Vladimir can pick 1 flower of the first type and 3 flowers of the second type, in this case the total happiness equals $$$5 + (1 + 2 \\cdot 4) = 14$$$.In the second example Vladimir can pick 2 flowers of the first type, 2 flowers of the second type, and 1 flower of the third type, in this case the total happiness equals $$$(5 + 1 \\cdot 2) + (4 + 1 \\cdot 2) + 3 = 16$$$."}, "positive_code": [{"source_code": "object C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, ab.b))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a <= ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1) min n\n val onPosA = if (pos > 0) abs(pos - 1).a else Int.MaxValue\n val x = if (ab.a < onPosA) prefixSums(pos min (n - 1)) + ab.a + ab.b * (n - pos - 1)\n else prefixSums(pos) + ab.b * (n - pos)\n\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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 C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, ab.b))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a < ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1)\n val onPos = if (pos > 0) abs(pos-1) else ab\n val x = if (pos < i) if (ab.a <= onPos.a) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0\n else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0\n\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val as, bs = Array.ofDim[Long](m)\n for (i <- 0 until m) {\n as(i) = nextInt\n bs(i) = nextInt\n }\n\n val bestB = (0 until m).maxBy {\n i => bs(i) * Int.MaxValue + as(i)\n }\n\n val maxB = bs(bestB)\n val betterAs = as.zipWithIndex.collect {\n case (a, i) if a > maxB && i != bestB =>\n a\n }.take(n)\n val takeBs = Math.max(0, n - betterAs.length)\n val res = if (takeBs == 0) betterAs.sum\n else if (takeBs == 1) {\n as.zipWithIndex.collect {\n case (a, i) if a > maxB =>\n a\n }.take(n).sum\n } else betterAs.sum + as(bestB) + maxB * (takeBs - 1)\n//println(bestB, betterAs.mkString(\" \"), takeBs)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\ncase class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, -ab.b))\n\n val maxAB = abs.maxBy(ab => (ab.b, ab.a))\n\n var res1 = abs.take(n).map(_.a).sum\n var aSum = 0L\n var maxB = 0L\n var count = 0\n var passedAB = false\n\n for (ab <- abs) {\n if (ab.a > maxAB.b) {\n count += 1\n aSum += ab.a\n if (ab.b > maxB) {\n maxB = ab.b\n }\n }\n if (ab == maxAB) passedAB = true\n val x = if (count <= n) aSum + maxB * (n - count) else 0L\n val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n val z = if (!passedAB && ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L\n// println(count, aSum, x, y, z)\n val xy = x max y max z\n if (xy > res1) res1 = xy\n }\n\n out.println(res1)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val as, bs = Array.ofDim[Long](m)\n for (i <- 0 until m) {\n as(i) = nextInt\n bs(i) = nextInt\n }\n\n val bestB = (0 until m).maxBy {\n i => bs(i) * Int.MaxValue + as(i)\n }\n\n val maxB = bs(bestB)\n val betterAs = as.zipWithIndex.collect {\n case (a, i) if a > maxB && i != bestB =>\n a\n }.take(n)\n val takeBs = Math.max(0, n - betterAs.length)\n val res = if (takeBs == 0) betterAs.sum\n else if (takeBs == 1) {\n val res = as.zipWithIndex.collect {\n case (a, i) if a > maxB =>\n a\n }.take(n).sum\n } else betterAs.sum + as(bestB) + maxB * (takeBs - 1)\n//println(bestB, betterAs.mkString(\" \"), takeBs)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\ncase class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, -ab.b))\n\n val maxAB = abs.maxBy(ab => (ab.b, ab.a))\n\n var res1 = 0L\n var aSum = 0L\n var maxB = 0L\n var count = 0\n var passedAB = false\n\n for (ab <- abs) {\n count += 1\n aSum += ab.a\n if (ab.b > maxB) {\n maxB = ab.b\n }\n if (ab == maxAB) passedAB = true\n val x = if (count <= n) aSum + maxB * (n - count) else 0L\n val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n //println(count, aSum, x, y)\n val xy = x max y\n if (xy > res1) res1 = xy\n }\n\n out.println(res1)\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 C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, ab.b))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a <= ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1)\n// println(pos, ab, i)\n val x = if (pos < i) if (pos < n) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0\n else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0\n\n // if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {\n // count += 1\n // aSum += ab.a\n // if (ab.b > maxB) {\n // maxB = ab.b\n // }\n // }\n // if (ab == maxAB) passedAB = true\n // val x = if (count <= n) aSum + maxB * (n - count) else 0L\n // val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n // val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L\n //// println(count, aSum, x, y, z)\n // val xy = x max y max z\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val as, bs = Array.ofDim[Long](m)\n for (i <- 0 until m) {\n as(i) = nextInt\n bs(i) = nextInt\n }\n\n val bestB = (0 until m).maxBy {\n i => bs(i) * Int.MaxValue + as(i)\n }\n\n val maxB = bs(bestB)\n val betterAs = as.zipWithIndex.collect {\n case (a, i) if a > maxB && i != bestB =>\n a\n }.take(n)\n val takeBs = Math.max(0, n - betterAs.length)\n\n val res1 = if (takeBs == 0) betterAs.sum\n else if (takeBs == 1) {\n as.zipWithIndex.collect {\n case (a, i) if a > maxB =>\n a\n }.take(n).sum\n } else (betterAs.sum + as(bestB) + maxB * (takeBs - 1))\n//println(bestB, betterAs.mkString(\" \"), takeBs)\n\n val res2 = as.sorted.reverse.take(n).sum\n val res = res1 max res2\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\ncase class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, -ab.b))\n\n val maxAB = abs.maxBy(ab => (ab.b, ab.a))\n\n var res1 = abs.take(n).map(_.a).sum\n var aSum = 0L\n var maxB = 0L\n var count = 0\n var passedAB = false\n\n for (ab <- abs) {\n if (ab.a > maxAB.b) {\n count += 1\n aSum += ab.a\n if (ab.b > maxB) {\n maxB = ab.b\n }\n }\n if (ab == maxAB) passedAB = true\n val x = if (count <= n) aSum + maxB * (n - count) else 0L\n val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L\n// println(count, aSum, x, y, z)\n val xy = x max y max z\n if (xy > res1) res1 = xy\n }\n\n out.println(res1)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\ncase class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, -ab.b))\n\n val maxAB = abs.maxBy(ab => (ab.b, ab.a))\n\n var res1 = abs.take(n).map(_.a).sum\n var aSum = 0L\n var maxB = 0L\n var count = 0\n var passedAB = false\n\n for (ab <- abs) {\n if (ab.a > maxAB.b) {\n count += 1\n aSum += ab.a\n if (ab.b > maxB) {\n maxB = ab.b\n }\n }\n if (ab == maxAB) passedAB = true\n val x = if (count <= n) aSum + maxB * (n - count) else 0L\n val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n //println(count, aSum, x, y)\n val xy = x max y\n if (xy > res1) res1 = xy\n }\n\n out.println(res1)\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 C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, ab.b))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a <= ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1)\n// println(pos, ab, i)\n val onPos = if (pos > 0) abs(pos-1) else ab\n val x = if (pos < i) if (ab.a <= onPos.a) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0\n else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0\n\n // if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {\n // count += 1\n // aSum += ab.a\n // if (ab.b > maxB) {\n // maxB = ab.b\n // }\n // }\n // if (ab == maxAB) passedAB = true\n // val x = if (count <= n) aSum + maxB * (n - count) else 0L\n // val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n // val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L\n //// println(count, aSum, x, y, z)\n // val xy = x max y max z\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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 C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, ab.b))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a < ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1)\n val x = if (pos < i) if (pos < n) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0\n else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0\n\n // if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {\n // count += 1\n // aSum += ab.a\n // if (ab.b > maxB) {\n // maxB = ab.b\n // }\n // }\n // if (ab == maxAB) passedAB = true\n // val x = if (count <= n) aSum + maxB * (n - count) else 0L\n // val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n // val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L\n //// println(count, aSum, x, y, z)\n // val xy = x max y max z\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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 C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, -ab.b))\n\n val maxAB = abs.maxBy(ab => (ab.b, ab.a))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a < ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1)\n val x = if (pos < i) if (pos < n) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0\n else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0\n\n // if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {\n // count += 1\n // aSum += ab.a\n // if (ab.b > maxB) {\n // maxB = ab.b\n // }\n // }\n // if (ab == maxAB) passedAB = true\n // val x = if (count <= n) aSum + maxB * (n - count) else 0L\n // val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L\n // val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L\n //// println(count, aSum, x, y, z)\n // val xy = x max y max z\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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 C {\n\n import InOut._\n\n def main(args: Array[String]): Unit = {\n case class AB(a: Long, b: Long)\n for (_ <- 1 to nextInt) {\n val n, m = nextInt\n val abs = Array.fill(m) {\n AB(nextInt, nextInt)\n }.sortBy(ab => (-ab.a, ab.b))\n\n var res1 = abs.take(n).map(_.a).sum\n val prefixSums = abs.map(_.a).scan(0L)(_ + _)\n\n for (i <- abs.indices) {\n val ab = abs(i)\n\n @annotation.tailrec\n def binSearch(low: Int, hi: Int): Int = {\n if (hi < low) low\n else {\n val mid = (low + hi) / 2\n if (abs(mid).a < ab.b) binSearch(low, mid - 1)\n else binSearch(mid + 1, hi)\n }\n }\n\n val pos = binSearch(0, m - 1)\n val onPos = if (pos > 0) abs(pos - 1) else ab\n val x = if (pos < i) if (ab.a < onPos.a) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0\n else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0\n\n if (x > res1) res1 = x\n }\n\n out.println(res1)\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"}], "src_uid": "fcfcb69edb84eeecfa735c3cf80c978b"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose some index $$$i$$$ ($$$1 \\le i \\le n - 2$$$) and shift the segment $$$[a_i, a_{i + 1}, a_{i + 2}]$$$ cyclically to the right (i.e. replace the segment $$$[a_i, a_{i + 1}, a_{i + 2}]$$$ with $$$[a_{i + 2}, a_i, a_{i + 1}]$$$). Your task is to sort the initial array by no more than $$$n^2$$$ such operations or say that it is impossible to do that.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \\le n \\le 500$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 500$$$), where $$$a_i$$$ is the $$$i$$$-th element $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$500$$$.", "output_spec": "For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations $$$ans$$$ on the first line and $$$ans$$$ integers $$$idx_1, idx_2, \\dots, idx_{ans}$$$ ($$$1 \\le idx_i \\le n - 2$$$), where $$$idx_i$$$ is the index of left border of the segment for the $$$i$$$-th operation. You should print indices in order of performing operations.", "sample_inputs": ["5\n5\n1 2 3 4 5\n5\n5 4 3 2 1\n8\n8 4 5 2 3 6 7 3\n7\n5 2 1 6 4 7 3\n6\n1 2 3 3 6 4"], "sample_outputs": ["0\n\n6\n3 1 3 2 2 3 \n13\n2 1 1 6 4 2 4 3 3 4 4 6 6 \n-1\n4\n3 3 4 4"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contests._1374\n\nobject CyclicShiftsSorting {\n\n def countInversions(arr: Array[Int]): Int = {\n arr.indices.foldLeft(0)((accI, i) =>\n accI + (i + 1 until arr.length).foldLeft(0)((accJ, j) =>\n accJ + (if (arr(i) > arr(j)) 1 else 0)))\n }\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 seq = io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val originalZipped = seq.zipWithIndex\n val sortedSeq = originalZipped.sortBy(_._1).toList\n\n def rotateRight(i: Int): Unit = {\n val a = originalZipped(i)\n val b = originalZipped(i + 1)\n val c = originalZipped(i + 2)\n\n originalZipped(i) = c\n originalZipped(i + 1) = a\n originalZipped(i + 2) = b\n }\n\n @scala.annotation.tailrec\n def loop(pos: Int, turn: List[(Int, Int)], stillOdd: Boolean, result: List[Int]): List[Int] = {\n turn match {\n case Nil if !stillOdd => result\n case Nil if stillOdd => Nil\n case f :: s :: tail if stillOdd && f._1 == s._1 =>\n val idS = originalZipped.indexOf(s)\n val tempR = (idS - 2 to pos by -2).foldLeft(result) { (acc, i) => rotateRight(i); (i + 1) :: acc }\n\n val newR = if (pos + 1 < n && originalZipped(pos + 1) == s) {\n rotateRight(pos)\n rotateRight(pos)\n pos + 1 :: pos + 1 :: tempR\n } else tempR\n loop(pos + 1, f :: tail, stillOdd = false, newR)\n\n case h :: tail =>\n val idV = originalZipped.indexOf(h)\n val tempR = (idV - 2 to pos by -2).foldLeft(result) { (acc, i) => rotateRight(i); (i + 1) :: acc }\n\n val newR = if (pos + 1 < n && originalZipped(pos + 1) == h) {\n rotateRight(pos)\n rotateRight(pos)\n pos + 1 :: pos + 1 :: tempR\n } else tempR\n loop(pos + 1, tail, stillOdd, newR)\n }\n }\n\n val areInversionsOdd = countInversions(seq) % 2 == 1\n val allDistinct = seq.distinct.length == n\n\n if (areInversionsOdd && allDistinct) \"-1\" else {\n val result = loop(0, sortedSeq, areInversionsOdd, Nil)\n s\"${result.length}\\n${result.reverse.mkString(\" \")}\"\n }\n }\n }.mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [], "src_uid": "ea9f72c830d938d36135a75a418c094c"} {"nl": {"description": "Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: Its elements are in increasing order. That is an inequality ai\u2009<\u2009aj holds for any two indices i,\u2009j (i\u2009<\u2009j). For any two indices i and j (i\u2009<\u2009j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.", "input_spec": "The input contains a single integer: n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "Output a line that contains n space-separated integers a1 a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1. If there are multiple solutions you can output any one.", "sample_inputs": ["3", "5"], "sample_outputs": ["2 9 15", "11 14 20 27 31"], "notes": null}, "positive_code": [{"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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Acacius is studying strings theory. Today he came with the following problem.You are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string \"abacaba\" occurs as a substring in a resulting string exactly once?Each question mark should be replaced with exactly one lowercase English letter. For example, string \"a?b?c\" can be transformed into strings \"aabbc\" and \"azbzc\", but can't be transformed into strings \"aabc\", \"a?bbc\" and \"babbc\".Occurrence of a string $$$t$$$ of length $$$m$$$ in the string $$$s$$$ of length $$$n$$$ as a substring is a index $$$i$$$ ($$$1 \\leq i \\leq n - m + 1$$$) such that string $$$s[i..i+m-1]$$$ consisting of $$$m$$$ consecutive symbols of $$$s$$$ starting from $$$i$$$-th equals to string $$$t$$$. For example string \"ababa\" has two occurrences of a string \"aba\" as a substring with $$$i = 1$$$ and $$$i = 3$$$, but there are no occurrences of a string \"aba\" in the string \"acba\" as a substring.Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string \"abacaba\" occurs as a substring in a resulting string exactly once.", "input_spec": "First line of input contains an integer $$$T$$$ ($$$1 \\leq T \\leq 5000$$$), number of test cases. $$$T$$$ pairs of lines with test case descriptions follow. The first line of a test case description contains a single integer $$$n$$$ ($$$7 \\leq n \\leq 50$$$), length of a string $$$s$$$. The second line of a test case description contains string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks.", "output_spec": "For each test case output an answer for it. In case if there is no way to replace question marks in string $$$s$$$ with a lowercase English letters in such a way that there is exactly one occurrence of a string \"abacaba\" in the resulting string as a substring output \"No\". Otherwise output \"Yes\" and in the next line output a resulting string consisting of $$$n$$$ lowercase English letters. If there are multiple possible strings, output any. You may print every letter in \"Yes\" and \"No\" in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).", "sample_inputs": ["6\n7\nabacaba\n7\n???????\n11\naba?abacaba\n11\nabacaba?aba\n15\nasdf???f???qwer\n11\nabacabacaba"], "sample_outputs": ["Yes\nabacaba\nYes\nabacaba\nYes\nabadabacaba\nYes\nabacabadaba\nNo\nNo"], "notes": "NoteIn first example there is exactly one occurrence of a string \"abacaba\" in the string \"abacaba\" as a substring.In second example seven question marks can be replaced with any seven lowercase English letters and with \"abacaba\" in particular.In sixth example there are two occurrences of a string \"abacaba\" as a substring."}, "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 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"}, {"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"} {"nl": {"description": "Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009r and the xor of the numbers ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj is equal to k.", "input_spec": "The first line of the input contains integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100\u2009000, 0\u2009\u2264\u2009k\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the length of the array, the number of queries and Bob's favorite number respectively. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 Bob's array. Then m lines follow. The i-th line contains integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n)\u00a0\u2014 the parameters of the i-th query.", "output_spec": "Print m lines, answer the queries in the order they appear in the input. ", "sample_inputs": ["6 2 3\n1 2 1 1 0 3\n1 6\n3 5", "5 3 1\n1 1 1 1 1\n1 5\n2 4\n1 3"], "sample_outputs": ["7\n0", "9\n4\n4"], "notes": "NoteIn the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query.In the second sample xor equals 1 for all subarrays of an odd length."}, "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"}, {"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"}], "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"} {"nl": {"description": "Musicians of a popular band \"Flayer\" have announced that they are going to \"make their exit\" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by \"Flayer\", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j\u2009\u2260\u2009i).Formally, for every you have to calculate , where d(i,\u2009j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i,\u2009j) to be infinitely large.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105). Then m lines follow, i-th contains three integers vi, ui and wi (1\u2009\u2264\u2009vi,\u2009ui\u2009\u2264\u2009n,\u2009vi\u2009\u2260\u2009ui, 1\u2009\u2264\u2009wi\u2009\u2264\u20091012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v,\u2009u) neither extra (v,\u2009u) nor (u,\u2009v) present in input. The next line contains n integers a1,\u2009a2,\u2009... ak (1\u2009\u2264\u2009ai\u2009\u2264\u20091012) \u2014 price to attend the concert in i-th city.", "output_spec": "Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j\u2009\u2260\u2009i).", "sample_inputs": ["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"], "sample_outputs": ["6 14 1 25", "12 10 12"], "notes": null}, "positive_code": [{"source_code": "import java.util\n\nimport D.as\n\nimport 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, m) = readInts(2)\n\n case class Route(u: Int, v: Int, w: Long)\n\n val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }\n val wBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofLong }\n\n for (i <- 0 until m) {\n val Array(_u, _v, w) = readLongs(3)\n val u = _u.toInt - 1\n val v = _v.toInt - 1\n adjBuilders(u) += v\n wBuilders(u) += w\n adjBuilders(v) += u\n wBuilders(v) += w\n }\n\n val adjs = adjBuilders.map(_.result())\n val ws = wBuilders.map(_.result())\n\n val as = readLongs(n)\n\n val changed = new util.ArrayDeque[Int]\n for (u <- (0 until n).sortBy(as)) changed.add(u)\n val inChanged = Array.fill(n){ true }\n\n while (!changed.isEmpty) {\n val u = changed.poll()\n inChanged(u) = false\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n val w = ws(u)(i)\n val c = as(u) + 2 * w\n if (c < as(v)) {\n as(v) = c\n if (!inChanged(v)) {\n changed.add(v)\n inChanged(v) = true\n }\n }\n i += 1\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(as.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "f41be1fcb6164181c49b37ed9313696e"} {"nl": {"description": "Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.A substring of a string is a nonempty sequence of consecutive characters.For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The only line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20093\u00b7105). The string s contains only digits from 0 to 9.", "output_spec": "Print integer a \u2014 the number of substrings of the string s that are divisible by 4. Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.", "sample_inputs": ["124", "04", "5810438174"], "sample_outputs": ["4", "3", "9"], "notes": null}, "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 singleChar = str.count(i => i == '4' || i == '8' || i == '0')\n val otherSubstrings =\n if (str.length == 1) 0\n else {\n str.indices.tail.foldLeft(0l) {\n case (acc, i) =>\n val number = str(i - 1).asDigit * 10 + str(i).asDigit\n if (number % 4 == 0)\n acc + i\n else acc\n }\n }\n println(singleChar + otherSubstrings)\n}\n"}], "negative_code": [], "src_uid": "c7d48d2c23ff33890a262447af5be660"} {"nl": {"description": "Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!", "input_spec": "The first line of the input contains one integer number $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$.", "output_spec": "Print one string of length $$$2n-2$$$ \u2014 the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any.", "sample_inputs": ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"], "sample_outputs": ["SPPSPSPS", "PPSS", "PS"], "notes": "NoteThe only string which Ivan can guess in the first example is \"ababa\".The only string which Ivan can guess in the second example is \"aaa\". Answers \"SPSP\", \"SSPP\" and \"PSPS\" are also acceptable.In the third example Ivan can guess the string \"ac\" or the string \"ca\". The answer \"SP\" is also acceptable."}, "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 // \u3053\u306e\u5272\u308a\u632f\u308a\u306f\u9593\u9055\u3063\u3066\u3044\u305f\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}"}, {"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}"}], "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"} {"nl": {"description": "Amugae has a hotel consisting of $$$10$$$ rooms. The rooms are numbered from $$$0$$$ to $$$9$$$ from left to right.The hotel has two entrances \u2014 one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.", "input_spec": "The first line consists of an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the number of events in Amugae's memory. The second line consists of a string of length $$$n$$$ describing the events in chronological order. Each character represents: 'L': A customer arrives from the left entrance. 'R': A customer arrives from the right entrance. '0', '1', ..., '9': The customer in room $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$ respectively) leaves. It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $$$x$$$ when $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$) is given. Also, all the rooms are initially empty.", "output_spec": "In the only line, output the hotel room's assignment status, from room $$$0$$$ to room $$$9$$$. Represent an empty room as '0', and an occupied room as '1', without spaces.", "sample_inputs": ["8\nLLRL1RL1", "9\nL0L0LLRR9"], "sample_outputs": ["1010000011", "1100000010"], "notes": "NoteIn the first example, hotel room's assignment status after each action is as follows. First of all, all rooms are empty. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. L: one more customer from the left entrance. Assignment status is 1110000001. 1: the customer in room $$$1$$$ leaves. Assignment status is 1010000001. R: one more customer from the right entrance. Assignment status is 1010000011. L: one more customer from the left entrance. Assignment status is 1110000011. 1: the customer in room $$$1$$$ leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011.In the second example, hotel room's assignment status after each action is as follows. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. 0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again. 0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. R: one more customer from the right entrance. Assignment status is 1100000011. 9: the customer in room $$$9$$$ leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "a6cbf01d72d607ca95fe16df4fb16693"} {"nl": {"description": "Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t\u2009=\u2009\"nastya\" and a\u2009=\u2009[4,\u20091,\u20095,\u20093,\u20092,\u20096] then removals make the following sequence of words \"nastya\" \"nastya\" \"nastya\" \"nastya\" \"nastya\" \"nastya\" \"nastya\".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.", "input_spec": "The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1\u2009\u2264\u2009|p|\u2009<\u2009|t|\u2009\u2264\u2009200\u2009000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1,\u2009a2,\u2009...,\u2009a|t| of letter indices that specifies the order in which Nastya removes letters of t (1\u2009\u2264\u2009ai\u2009\u2264\u2009|t|, all ai are distinct).", "output_spec": "Print a single integer number, the maximum number of letters that Nastya can remove.", "sample_inputs": ["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"], "sample_outputs": ["3", "4"], "notes": "NoteIn the first sample test sequence of removing made by Nastya looks like this:\"ababcba\" \"ababcba\" \"ababcba\" \"ababcba\" Nastya can not continue, because it is impossible to get word \"abb\" from word \"ababcba\".So, Nastya will remove only three letters."}, "positive_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) / 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}"}, {"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": "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": "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}"}, {"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"}], "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"} {"nl": {"description": "Maksim has $$$n$$$ objects and $$$m$$$ boxes, each box has size exactly $$$k$$$. Objects are numbered from $$$1$$$ to $$$n$$$ in order from left to right, the size of the $$$i$$$-th object is $$$a_i$$$.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $$$i$$$-th object fits in the current box (the remaining size of the box is greater than or equal to $$$a_i$$$), he puts it in the box, and the remaining size of the box decreases by $$$a_i$$$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le 10^9$$$) \u2014 the number of objects, the number of boxes and the size of each box. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le k$$$), where $$$a_i$$$ is the size of the $$$i$$$-th object.", "output_spec": "Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.", "sample_inputs": ["5 2 6\n5 2 1 4 2", "5 1 4\n4 2 3 4 1", "5 3 3\n1 2 3 1 1"], "sample_outputs": ["4", "1", "5"], "notes": "NoteIn the first example Maksim can pack only $$$4$$$ objects. Firstly, he tries to pack all the $$$5$$$ objects. Distribution of objects will be $$$[5], [2, 1]$$$. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be $$$[2, 1], [4, 2]$$$. So the answer is $$$4$$$.In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is $$$[4]$$$), but he can pack the last object ($$$[1]$$$).In the third example Maksim can pack all the objects he has. The distribution will be $$$[1, 2], [3], [1, 1]$$$."}, "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 A = na(N).reverse\n\n def count: Int = {\n var cnt = 0\n var box = M\n var i = 0\n while(box > 0 && i < N) {\n if (cnt + A(i) > K) {\n cnt = A(i)\n box -= 1\n } else {\n cnt += A(i)\n }\n if (box == 0) return i\n i += 1\n }\n i\n }\n\n out.println(count)\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": "869f8763211a7771ecd73d56b5c34479"} {"nl": {"description": "Yelisey has an array $$$a$$$ of $$$n$$$ integers.If $$$a$$$ has length strictly greater than $$$1$$$, then Yelisei can apply an operation called minimum extraction to it: First, Yelisei finds the minimal number $$$m$$$ in the array. If there are several identical minima, Yelisey can choose any of them. Then the selected minimal element is removed from the array. After that, $$$m$$$ is subtracted from each remaining element. Thus, after each operation, the length of the array is reduced by $$$1$$$.For example, if $$$a = [1, 6, -4, -2, -4]$$$, then the minimum element in it is $$$a_3 = -4$$$, which means that after this operation the array will be equal to $$$a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0]$$$.Since Yelisey likes big numbers, he wants the numbers in the array $$$a$$$ to be as big as possible.Formally speaking, he wants to make the minimum of the numbers in array $$$a$$$ to be maximal possible (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length $$$1$$$.Help him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the original length of the array $$$a$$$. The second line of the description lists $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ lines, each of them containing the answer to the corresponding test case. The answer to the test case is a single integer\u00a0\u2014 the maximal possible minimum in $$$a$$$, which can be obtained by several applications of the described operation to it.", "sample_inputs": ["8\n1\n10\n2\n0 0\n3\n-1 2 0\n4\n2 10 1 7\n2\n2 3\n5\n3 2 -4 -2 0\n2\n-1 1\n1\n-2"], "sample_outputs": ["10\n0\n2\n5\n2\n2\n2\n-2"], "notes": "NoteIn the first example test case, the original length of the array $$$n = 1$$$. Therefore minimum extraction cannot be applied to it. Thus, the array remains unchanged and the answer is $$$a_1 = 10$$$.In the second set of input data, the array will always consist only of zeros.In the third set, the array will be changing as follows: $$$[\\color{blue}{-1}, 2, 0] \\to [3, \\color{blue}{1}] \\to [\\color{blue}{2}]$$$. The minimum elements are highlighted with $$$\\color{blue}{\\text{blue}}$$$. The maximal one is $$$2$$$.In the fourth set, the array will be modified as $$$[2, 10, \\color{blue}{1}, 7] \\to [\\color{blue}{1}, 9, 6] \\to [8, \\color{blue}{5}] \\to [\\color{blue}{3}]$$$. Similarly, the maximum of the minimum elements is $$$5$$$."}, "positive_code": [{"source_code": "object _1607C 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 arr = io.read[Vector[Int]].sorted\r\n\r\n var ans = Int.MinValue\r\n var delta = 0\r\n\r\n for {a <- arr} {\r\n val actual = a + delta\r\n ans = ans max actual\r\n delta -= actual\r\n }\r\n\r\n io.write(ans)\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": "4bd7ef5f6b3696bb44e22aea87981d9a"} {"nl": {"description": "In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i\u2009>\u20091) is situated at the top of branch, which bottom is pi-th inflorescence and pi\u2009<\u2009i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.", "input_spec": "First line of input contains single integer number n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u00a0\u2014 number of inflorescences. Second line of input contains sequence of n\u2009-\u20091 integer numbers p2,\u2009p3,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009<\u2009i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.", "output_spec": "Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.", "sample_inputs": ["3\n1 1", "5\n1 2 2 2", "18\n1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4"], "sample_outputs": ["1", "3", "4"], "notes": "NoteIn first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it."}, "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) = readInts(1)\n val ps = readInts(n - 1)\n\n val childBuilders = Array.fill(n + 1){ new mutable.ArrayBuilder.ofInt }\n for (i <- ps.indices) {\n childBuilders(ps(i)) += i + 2\n }\n\n val children = childBuilders.map(_.result())\n val counts = Array.fill(n + 1){ 0 }\n\n def dfs(u: Int, depth: Int): Unit = {\n var i = 0\n counts(depth) += 1\n while (i < children(u).length) {\n dfs(children(u)(i), depth + 1)\n i += 1\n }\n }\n\n dfs(1, 0)\n\n println(counts.map(_ % 2).sum)\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "a4563e6aea9126e20e7a33df664e3171"} {"nl": {"description": "You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.More precisely, you want to spam the emote triangle of size $$$k$$$. It consists of $$$2k-1$$$ messages. The first message consists of one emote, the second one \u2014 of two emotes, ..., the $$$k$$$-th one \u2014 of $$$k$$$ emotes, the $$$k+1$$$-th one \u2014 of $$$k-1$$$ emotes, ..., and the last one \u2014 of one emote.For example, the emote triangle for $$$k=3$$$ consists of $$$5$$$ messages: Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $$$x$$$ emotes in succession (you can assume you are the only user in the chat). Now you are interested \u2014 how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $$$2k-1$$$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains integers $$$k$$$ and $$$x$$$ ($$$1 \\le k \\le 10^9; 1 \\le x \\le 10^{18}$$$).", "output_spec": "For each test case, print the number of messages you will write before getting banned for the corresponding values $$$k$$$ and $$$x$$$.", "sample_inputs": ["7\n4 6\n4 7\n1 2\n3 7\n2 5\n100 1\n1000000000 923456789987654321"], "sample_outputs": ["3\n4\n1\n4\n3\n1\n1608737403"], "notes": "NoteLet's analyze the test cases of the example. In the first test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$3$$$ emotes respectively, and since $$$1 + 2 + 3 \\ge 6$$$, you get banned after that. In the second test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$4$$$ emotes respectively, and since $$$1 + 2 + 3 + 4 \\ge 7$$$, you get banned after that. In the third test case, you write one message containing exactly $$$1$$$ emote. It doesn't get you banned, since $$$1 < 2$$$, but you have already finished posting your emote triangle. So you wrote one message successfully. In the fourth test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$2$$$ emotes respectively, and since $$$1 + 2 + 3 + 2 \\ge 7$$$, you get banned after that. In the fifth test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$1$$$ emote respectively. It doesn't get you banned, since $$$1 + 2 + 1 < 5$$$, but you have already finished posting your emote triangle. So you wrote three messages successfully. In the sixth test case, since $$$x = 1$$$, you get banned as soon as you send your first message. The seventh test case is too large to analyze, so we'll skip it. "}, "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 maxn = 10010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readLong()\n val m = readLong()\n def cnt (inp: Long): Long = {\n var k = inp\n var ans = 0L\n if (k <= n) {\n ans = k * k\n ans -= k\n ans /= 2\n ans += k\n return ans\n } else {\n ans = n * n\n k -= n\n var tmp = (n-k-1L)*(n-k-1L)\n tmp -= (n-k-1L)\n tmp /= 2\n tmp += (n-k-1L)\n ans -= tmp\n return ans\n }\n }\n def bs(st: Long, en: Long): Long = {\n if (en - st <= 1L) {\n if (cnt(st) >= m)\n return st\n else\n return en\n }\n val mid = (st + en) / 2\n if (cnt(mid) < m)\n return bs(mid, en)\n else\n return bs(st, mid)\n }\n writer.println(bs(1L, 2L*n-1L))\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "bf21c4809cd10904f05d531dd7af4ab5"} {"nl": {"description": "You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.You need to permute the array elements so that value became minimal possible. In particular, it is allowed not to change order of elements at all.", "input_spec": "The first line contains two integers n,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105, 1\u2009\u2264\u2009k\u2009\u2264\u2009min(5000,\u2009n\u2009-\u20091)). The second line contains n integers A[1],\u2009A[2],\u2009...,\u2009A[n] (\u2009-\u2009109\u2009\u2264\u2009A[i]\u2009\u2264\u2009109), separate by spaces \u2014 elements of the array A.", "output_spec": "Print the minimum possible value of the sum described in the statement.", "sample_inputs": ["3 2\n1 2 4", "5 2\n3 -5 3 -5 3", "6 3\n4 3 4 3 2 5"], "sample_outputs": ["1", "0", "3"], "notes": "NoteIn the first test one of the optimal permutations is 1\u00a04\u00a02. In the second test the initial order is optimal. In the third test one of the optimal permutations is 2\u00a03\u00a04\u00a04\u00a03\u00a05."}, "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, k) = readInts(2)\n val as = readInts(n).sorted\n\n val delta = Array.ofDim[Long](n - 1)\n for (i <- 1 until n) delta(i - 1) = Math.abs(as(i - 1) - as(i))\n val ds = delta.scan(0L)(_ + _)\n val memo = Array.fill(k - n % k + 1, n % k + 1)(-1L)\n\n def solve(from: Int, depthS: Int, depthL: Int): Long = {\n if (from >= n || depthL > n % k || depthS > k - n % k) {\n if (from == n && depthS + depthL == k) 0L\n else Long.MaxValue / 2\n } else if (memo(depthS)(depthL) == -1) {\n var res = Long.MaxValue / 2\n val to1 = from + n / k\n val x = ds(to1 - 1) - ds(from) + solve(to1, depthS + 1, depthL)\n if (x < res) {\n res = x\n memo(depthS)(depthL) = res\n }\n if (to1 < n) {\n val to2 = to1 + 1\n val x = ds(to2 - 1) - ds(from) + solve(to2, depthS, depthL + 1)\n if (x < res) {\n res = x\n memo(depthS)(depthL) = res\n }\n }\n res\n } else memo(depthS)(depthL)\n }\n\n println(solve(0, 0, 0))\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, k) = readInts(2)\n val as = readInts(n).sorted\n val bs = Array.ofDim[Int](n)\n\n var res = Long.MaxValue\n\n for (d <- 0 to n % k) {\n var offset = d\n var j = d\n var sum = 0L\n var i = 0\n while (i < n) {\n bs(j) = as(i)\n j += k\n if (j >= n) {\n offset += 1\n if (offset >= k) offset -= k\n j = offset\n }\n i += 1\n }\n i = 0\n while (i < n - k) {\n sum += Math.abs(bs(i) - bs(i + k))\n i += 1\n }\n if (sum < res) res = sum\n }\n\n println(res)\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, k) = readInts(2)\n val as = readInts(n).sorted\n\n val delta = Array.ofDim[Long](n - 1)\n for (i <- 1 until n) delta(i - 1) = Math.abs(as(i - 1) - as(i))\n val ds = delta.scan(0L)(_ + _)\n val memo = Array.fill(n)(-1L)\n\n def solve(from: Int, depth: Int): Long = {\n if (from >= n) {\n if (from == n && depth == k) 0L\n else Long.MaxValue / 2\n } else if (memo(from) == -1) {\n var res = Long.MaxValue / 2\n for (_to <- n / k to n / k + 1) {\n val to = from + _to \n if (to <= n) {\n val x = ds(to - 1) - ds(from) + solve(to, depth + 1)\n if (x < res) {\n res = x\n memo(from) = res\n }\n }\n }\n res\n } else memo(from)\n }\n\n println(solve(0, 0))\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, k) = readInts(2)\n val as = readInts(n).sorted\n val bs = Array.ofDim[Int](n)\n\n var res = Long.MaxValue\n\n for (d <- 0 to k) {\n var offset = d\n var j = d\n var sum = 0L\n var i = 0\n while (i < n) {\n bs(j) = as(i)\n j += k\n if (j >= n) {\n offset += 1\n if (offset >= k) offset -= k\n j = offset\n }\n i += 1\n }\n i = 0\n while (i < n - k) {\n sum += Math.abs(bs(i) - bs(i + k))\n i += 1\n }\n //println(d, sum)\n //println(bs.mkString(\" \"))\n if (sum < res) {\n res = sum\n }\n }\n\n println(res)\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, k) = readInts(2)\n val as = readInts(n).sorted\n val bs = Array.ofDim[Int](n)\n\n var res = Long.MaxValue\n\n for (d <- 0 until n) {\n var offset = 0\n var j = 0\n var sum = 0L\n var i = 0\n while (i < n) {\n var ii = i + d\n if (ii >= n) ii -= n\n bs(j) = as(ii)\n j += k\n if (j >= n) {\n offset += 1\n if (offset >= k) offset -= k\n j = offset\n }\n i += 1\n }\n i = 0\n while (i < n - k) {\n sum += Math.abs(bs(i) - bs(i + k))\n i += 1\n }\n //println(d, sum)\n //println(bs.mkString(\" \"))\n if (sum < res) {\n res = sum\n }\n }\n\n println(res)\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, k) = readInts(2)\n val as = readInts(n).sorted\n val bs = Array.ofDim[Int](n)\n\n var res = Long.MaxValue\n\n for (d <- 0 until Math.min(n, 2 * k)) {\n var offset = 0\n var j = 0\n var sum = 0L\n var i = 0\n while (i < n) {\n var ii = i + d\n if (ii >= n) ii -= n\n bs(j) = as(ii)\n j += k\n if (j >= n) {\n offset += 1\n if (offset >= k) offset -= k\n j = offset\n }\n i += 1\n }\n i = 0\n while (i < n - k) {\n sum += Math.abs(bs(i) - bs(i + k))\n i += 1\n }\n //println(d, sum)\n //println(bs.mkString(\" \"))\n if (sum < res) {\n res = sum\n }\n }\n\n println(res)\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, k) = readInts(2)\n val as = readInts(n).sorted\n val bs = Array.ofDim[Int](n)\n\n var res = Long.MaxValue\n\n for (d <- 0 to k) {\n var offset = 0\n var j = 0\n var sum = 0L\n var i = 0\n while (i < n) {\n var ii = i + d\n if (ii >= n) ii -= n\n bs(j) = as(ii)\n j += k\n if (j >= n) {\n offset += 1\n if (offset >= k) offset -= k\n j = offset\n }\n i += 1\n }\n i = 0\n while (i < n - k) {\n sum += Math.abs(bs(i) - bs(i + k))\n i += 1\n }\n //println(d, sum)\n //println(bs.mkString(\" \"))\n if (sum < res) {\n res = sum\n }\n }\n\n println(res)\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, k) = readInts(2)\n val as = readInts(n).sorted\n val bs = Array.ofDim[Int](n)\n\n var res = Long.MaxValue\n\n for (d <- 0 until Math.min(n, 2 * k)) {\n var offset = d\n var j = d\n var sum = 0L\n var i = 0\n while (i < n) {\n bs(j) = as(i)\n j += k\n if (j >= n) {\n offset += 1\n if (offset >= k) offset -= k\n j = offset\n }\n i += 1\n }\n i = 0\n while (i < n - k) {\n sum += Math.abs(bs(i) - bs(i + k))\n i += 1\n }\n //println(d, sum)\n //println(bs.mkString(\" \"))\n if (sum < res) {\n res = sum\n }\n }\n\n println(res)\n}\n"}], "src_uid": "271ebec6b9ec990300f545743a16281b"} {"nl": {"description": "Polycarpus just has been out of luck lately! As soon as he found a job in the \"Binary Cat\" cafe, the club got burgled. All ice-cream was stolen.On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character \"+\" in his notes. Similarly, each time a visitor left the club, Polycarpus put character \"-\" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.", "input_spec": "The only line of the input contains a sequence of characters \"+\" and \"-\", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.", "output_spec": "Print the sought minimum number of people", "sample_inputs": ["+-+-+", "---"], "sample_outputs": ["1", "3"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Recently, Petya learned about a new game \"Slay the Dragon\". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $$$n$$$ heroes, the strength of the $$$i$$$-th hero is equal to $$$a_i$$$.According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to $$$x$$$, then you have to send a hero with a strength of at least $$$x$$$ to kill it. If the dragon's attack power is $$$y$$$, then the total strength of the heroes defending the castle should be at least $$$y$$$.The player can increase the strength of any hero by $$$1$$$ for one gold coin. This operation can be done any number of times.There are $$$m$$$ dragons in the game, the $$$i$$$-th of them has defense equal to $$$x_i$$$ and attack power equal to $$$y_i$$$. Petya was wondering what is the minimum number of coins he needs to spend to defeat the $$$i$$$-th dragon.Note that the task is solved independently for each dragon (improvements are not saved).", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^{12}$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th hero. The third line contains a single integer $$$m$$$ ($$$1 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of dragons. The next $$$m$$$ lines contain two integers each, $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i \\le 10^{12}; 1 \\le y_i \\le 10^{18}$$$)\u00a0\u2014 defense and attack power of the $$$i$$$-th dragon.", "output_spec": "Print $$$m$$$ lines, $$$i$$$-th of which contains a single integer\u00a0\u2014 the minimum number of coins that should be spent to defeat the $$$i$$$-th dragon.", "sample_inputs": ["4\n3 6 2 3\n5\n3 12\n7 9\n4 14\n1 10\n8 7"], "sample_outputs": ["1\n2\n4\n0\n2"], "notes": "NoteTo defeat the first dragon, you can increase the strength of the third hero by $$$1$$$, then the strength of the heroes will be equal to $$$[3, 6, 3, 3]$$$. To kill the dragon, you can choose the first hero.To defeat the second dragon, you can increase the forces of the second and third heroes by $$$1$$$, then the strength of the heroes will be equal to $$$[3, 7, 3, 3]$$$. To kill the dragon, you can choose a second hero.To defeat the third dragon, you can increase the strength of all the heroes by $$$1$$$, then the strength of the heroes will be equal to $$$[4, 7, 3, 4]$$$. To kill the dragon, you can choose a fourth hero.To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon.To defeat the fifth dragon, you can increase the strength of the second hero by $$$2$$$, then the strength of the heroes will be equal to $$$[3, 8, 2, 3]$$$. To kill the dragon, you can choose a second hero."}, "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": "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"}, {"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"} {"nl": {"description": "Ehab loves number theory, but for some reason he hates the number $$$x$$$. Given an array $$$a$$$, find the length of its longest subarray such that the sum of its elements isn't divisible by $$$x$$$, or determine that such subarray doesn't exist.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.", "input_spec": "The first line contains an integer $$$t$$$ $$$(1 \\le t \\le 5)$$$\u00a0\u2014 the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le x \\le 10^4$$$)\u00a0\u2014 the number of elements in the array $$$a$$$ and the number that Ehab hates. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{n}$$$ ($$$0 \\le a_i \\le 10^4$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "For each testcase, print the length of the longest subarray whose sum isn't divisible by $$$x$$$. If there's no such subarray, print $$$-1$$$.", "sample_inputs": ["3\n3 3\n1 2 3\n3 4\n1 2 3\n2 2\n0 6"], "sample_outputs": ["2\n3\n-1"], "notes": "NoteIn the first test case, the subarray $$$[2,3]$$$ has sum of elements $$$5$$$, which isn't divisible by $$$3$$$.In the second test case, the sum of elements of the whole array is $$$6$$$, which isn't divisible by $$$4$$$.In the third test case, all subarrays have an even sum, so the answer is $$$-1$$$."}, "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 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"}, {"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"} {"nl": {"description": " William has array of $$$n$$$ numbers $$$a_1, a_2, \\dots, a_n$$$. He can perform the following sequence of operations any number of times: Pick any two items from array $$$a_i$$$ and $$$a_j$$$, where $$$a_i$$$ must be a multiple of $$$2$$$ $$$a_i = \\frac{a_i}{2}$$$ $$$a_j = a_j \\cdot 2$$$ Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \\le n \\le 15)$$$, the number of elements in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i < 16)$$$, the contents of William's array.", "output_spec": "For each test case output the maximal sum of array elements after performing an optimal sequence of operations.", "sample_inputs": ["5\n3\n6 4 2\n5\n1 2 3 4 5\n1\n10\n3\n2 3 4\n15\n8 8 8 8 8 8 8 8 8 8 8 8 8 8 8"], "sample_outputs": ["50\n46\n10\n26\n35184372088846"], "notes": "NoteIn the first example test case the optimal sequence would be: Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \\frac{4}{2} = 2$$$ and $$$a_1 = 6 \\cdot 2 = 12$$$, making the array look as: [12, 2, 2]. Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \\frac{2}{2} = 1$$$ and $$$a_1 = 12 \\cdot 2 = 24$$$, making the array look as: [24, 1, 2]. Pick $$$i = 3$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_3 = \\frac{2}{2} = 1$$$ and $$$a_1 = 24 \\cdot 2 = 48$$$, making the array look as: [48, 1, 1]. The final answer $$$48 + 1 + 1 = 50$$$.In the third example test case there is no way to change the sum of elements, so the answer is $$$10$$$."}, "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 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"}, {"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"} {"nl": {"description": "Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1\u2009\u2264\u2009x\u2009\u2264\u2009n the maximum strength among all groups of size x.", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u2009\u00d7\u2009105), the number of bears. The second line contains n integers separated by space, a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), heights of bears.", "output_spec": "Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.", "sample_inputs": ["10\n1 2 3 4 5 4 3 2 1 6"], "sample_outputs": ["6 4 4 3 3 2 2 1 1 1"], "notes": null}, "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 val as = readInts(n)\n \n val leftSmaller, rightSmaller = Array.ofDim[Int](n)\n \n for (i <- 0 until n) {\n var j = i - 1\n while (j >= 0 && as(j) >= as(i)) {\n j = leftSmaller(j)\n }\n leftSmaller(i) = j\n }\n\n for (i <- n - 1 to 0 by -1) {\n var j = i + 1\n while (j < n && as(j) >= as(i)) {\n j = rightSmaller(j)\n }\n rightSmaller(i) = j\n }\n\n val res = Array.fill(n){ 0 }\n \n for (i <- 0 until n) {\n val span = rightSmaller(i) - leftSmaller(i) - 2\n if (res(span) < as(i)) res(span) = as(i)\n }\n \n for (i <- n - 2 to 0 by -1) {\n if (res(i) < res(i + 1)) res(i) = res(i + 1)\n }\n \n println(res.mkString(\" \"))\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) = readInts(1)\n val as = readInts(n)\n \n val leftSmaller, rightSmaller = Array.ofDim[Int](n)\n \n for (i <- 0 until n) {\n var j = i - 1\n while (j >= 0 && as(j) >= as(i)) {\n j = leftSmaller(j)\n }\n leftSmaller(i) = j\n }\n\n for (i <- n - 1 to 0 by -1) {\n var j = i + 1\n while (j < n && as(j) >= as(i)) {\n j = rightSmaller(j)\n }\n rightSmaller(i) = j\n }\n\n val res = Array.fill(n){ 0 }\n \n for (i <- 0 until n) {\n val span = rightSmaller(i) - leftSmaller(i) - 2\n if (res(span) < as(i)) res(span) = as(i)\n }\n \n for (i <- n - 2 to 0 by -1) {\n if (res(i) == 0) res(i) = res(i + 1)\n }\n \n println(res.mkString(\" \"))\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 val as = readInts(n)\n \n val leftSmaller, rightSmaller = Array.ofDim[Int](n)\n \n for (i <- 0 until n) {\n var j = i - 1\n while (j >= 0 && as(j) >= as(i)) {\n j = leftSmaller(j)\n }\n leftSmaller(i) = j\n }\n\n for (i <- n - 1 to 0 by -1) {\n var j = i + 1\n while (j < n && as(j) >= as(i)) {\n j = rightSmaller(j)\n }\n rightSmaller(i) = j\n }\n\n val res = Array.fill(n){ 0 }\n \n for (i <- 0 until n) {\n val span = rightSmaller(i) - leftSmaller(i) - 2\n if (res(span) < as(i)) res(span) = as(i)\n }\n \n for (i <- n - 2 to 0 by -1) {\n if (res(i) == 0) res(i) = res(i + 1)\n }\n \n println(res.mkString(\" \"))\n}\n"}], "src_uid": "5cf25cd4a02ce8020258115639c0ee64"} {"nl": {"description": "You are given a grid with $$$n$$$ rows and $$$m$$$ columns. We denote the square on the $$$i$$$-th ($$$1\\le i\\le n$$$) row and $$$j$$$-th ($$$1\\le j\\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$. All numbers are equal to $$$1$$$ or to $$$-1$$$. You start from the square $$$(1, 1)$$$ and can move one square down or one square to the right at a time. In the end, you want to end up at the square $$$(n, m)$$$.Is it possible to move in such a way so that the sum of the values written in all the visited cells (including $$$a_{11}$$$ and $$$a_{nm}$$$) is $$$0$$$?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$) \u00a0\u2014 the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$a_{ij} = 1$$$ or $$$-1$$$) \u00a0\u2014 the element in the cell $$$(i, j)$$$. It is guaranteed that the sum of $$$n\\cdot m$$$ over all test cases does not exceed $$$10^6$$$.", "output_spec": "For each test case, print \"YES\" if there exists a path from the top left to the bottom right that adds up to $$$0$$$, and \"NO\" otherwise. You can output each letter in any case.", "sample_inputs": ["5\n\n1 1\n\n1\n\n1 2\n\n1 -1\n\n1 4\n\n1 -1 1 -1\n\n3 4\n\n1 -1 -1 -1\n\n-1 1 1 -1\n\n1 1 1 -1\n\n3 4\n\n1 -1 1 1\n\n-1 1 -1 1\n\n1 -1 1 1"], "sample_outputs": ["NO\nYES\nYES\nYES\nNO"], "notes": "NoteOne possible path for the fourth test case is given in the picture in the statement."}, "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[Array[Int]](n)\r\n val B = new Array[Array[Int]](n)\r\n for (i <- 0 until n) {\r\n A(i) = new Array[Int](m)\r\n B(i) = new Array[Int](m)\r\n }\r\n for (i <- 0 until n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (j <- 0 until m) {\r\n val a = tokenizer.nextToken().toInt\r\n if (j == 0) {\r\n if (i == 0) {\r\n A(i)(j) = a\r\n B(i)(j) = a\r\n }\r\n else {\r\n A(i)(j) = a + A(i-1)(j)\r\n B(i)(j) = a + B(i-1)(j)\r\n }\r\n }\r\n else if (i == 0) {\r\n A(i)(j) = a + A(i)(j-1)\r\n B(i)(j) = a + B(i)(j-1)\r\n }\r\n else {\r\n A(i)(j) = a + min((A(i))(j-1),A(i-1)(j))\r\n B(i)(j) = a + max((B(i))(j-1),B(i-1)(j))\r\n }\r\n }\r\n }\r\n if ((A.last.last * B.last.last > 0) || ((n+m)% 2 == 0)) {\r\n output.println(\"no\")\r\n }\r\n else {\r\n output.println(\"yes\")}\r\n }\r\n }\r\n}"}], "negative_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[Array[Int]](n)\r\n val B = new Array[Array[Int]](n)\r\n for (i <- 0 until n) {\r\n A(i) = new Array[Int](m)\r\n B(i) = new Array[Int](m)\r\n }\r\n for (i <- 0 until n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (j <- 0 until m) {\r\n val a = tokenizer.nextToken().toInt\r\n if (j == 0) {\r\n if (i == 0) {\r\n A(i)(j) = a\r\n B(i)(j) = a\r\n }\r\n else {\r\n A(i)(j) = a + A(i-1)(j)\r\n B(i)(j) = a + B(i-1)(j)\r\n }\r\n }\r\n else if (i == 0) {\r\n A(i)(j) = a + A(i)(j-1)\r\n B(i)(j) = a + B(i)(j-1)\r\n }\r\n else {\r\n A(i)(j) = a + min((A(i))(j-1),A(i-1)(j))\r\n B(i)(j) = a + max((B(i))(j-1),B(i-1)(j))\r\n }\r\n }\r\n }\r\n if ((A.last.last * B.last.last > 0) || ((n+m)% 2 == 0)) {\r\n output.println(\"no\")\r\n }\r\n else {\r\n output.println(\"yes\")}\r\n println(A.toList.map(_.toList),B.toList.map(_.toList))\r\n }\r\n }\r\n}"}, {"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[Array[Int]](n)\r\n val B = new Array[Array[Int]](n)\r\n for (i <- 0 until n) {\r\n A(i) = new Array[Int](m)\r\n B(i) = new Array[Int](m)\r\n }\r\n for (i <- 0 until n) {\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (j <- 0 until m) {\r\n val a = tokenizer.nextToken().toInt\r\n if (j == 0) {\r\n if (i == 0) {\r\n A(i)(j) = a\r\n B(i)(j) = a\r\n }\r\n else {\r\n A(i)(j) = a + A(i-1)(j)\r\n B(i)(j) = a + B(i-1)(j)\r\n }\r\n }\r\n else if (i == 0) {\r\n A(i)(j) = a + A(i)(j-1)\r\n B(i)(j) = a + B(i)(j-1)\r\n }\r\n else {\r\n A(i)(j) = a + min((A(i))(j-1),A(i-1)(j))\r\n B(i)(j) = a + max((B(i))(j-1),B(i-1)(j))\r\n }\r\n }\r\n }\r\n if (A.last.last * B.last.last > 0) {\r\n output.println(\"no\")\r\n }\r\n else {\r\n output.println(\"yes\")}\r\n }\r\n }\r\n}"}], "src_uid": "7d6d1c5af6e3faefe67f585a5130d6bd"} {"nl": {"description": "Constanze is the smartest girl in her village but she has bad eyesight.One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe \"code\" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe \"uu\" instead of \"w\", and if you pronounce 'm', it will inscribe \"nn\" instead of \"m\"! Since Constanze had bad eyesight, she was not able to realize what Akko did.The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.But since this number can be quite large, tell me instead its remainder when divided by $$$10^9+7$$$.If there are no strings that Constanze's machine would've turned into the message I got, then print $$$0$$$.", "input_spec": "Input consists of a single line containing a string $$$s$$$ ($$$1 \\leq |s| \\leq 10^5$$$) \u2014 the received message. $$$s$$$ contains only lowercase Latin letters.", "output_spec": "Print a single integer \u2014 the number of strings that Constanze's machine would've turned into the message $$$s$$$, modulo $$$10^9+7$$$.", "sample_inputs": ["ouuokarinn", "banana", "nnn", "amanda"], "sample_outputs": ["4", "1", "3", "0"], "notes": "NoteFor the first example, the candidate strings are the following: \"ouuokarinn\", \"ouuokarim\", \"owokarim\", and \"owokarinn\".For the second example, there is only one: \"banana\".For the third example, the candidate strings are the following: \"nm\", \"mn\" and \"nnn\".For the last example, there are no candidate strings that the machine can turn into \"amanda\", since the machine won't inscribe 'm'."}, "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 \u3092\u6c42\u3081\u308b\u3002\u4e0b\u6e96\u5099\u3067\u968e\u4e57F\u3068\u2261MOD\u3067\u306e\u968e\u4e57\u306e\u9006\u5143I\u3092\u4f5c\u308b\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!) \u2261 (x-1)!I((x-1)!)\n // I((x-1)!) \u2261 I(x!) * x MOD\u304c\u3067\u304b\u3044\u306e\u3067(x-1)!\u306fMOD\u3068\u7d20\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\u306e\u30b0\u30eb\u30fc\u30d7\u304b\u3089k\u56de\u91cd\u8907\u3042\u308a\u3067\u9078\u3076\u7d44\u307f\u5408\u308f\u305b\u6570\n * n - 1\u306e\u3057\u304d\u308a\u3068k\u306e\u25cb\u3067\u8003\u3048\u308b\n */\n def H(n: Int, k: Int): Long = {\n comb(n + k - 1, k)\n }\n\n /**\n * private[this]\u3092\u3064\u304b\u3063\u3066\u308b\u306e\u3067getter\u304c\u5fc5\u8981\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "negative_code": [], "src_uid": "12c223c903544899638e47bcab88999a"} {"nl": {"description": "Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred through the network: if an archive consists of k files of sizes l1,\u2009l2,\u2009...,\u2009lk bytes, then the i-th file is split to one or more blocks bi,\u20091,\u2009bi,\u20092,\u2009...,\u2009bi,\u2009mi (here the total length of the blocks bi,\u20091\u2009+\u2009bi,\u20092\u2009+\u2009...\u2009+\u2009bi,\u2009mi is equal to the length of the file li), and after that all blocks are transferred through the network, maintaining the order of files in the archive.Zhorik thinks that the two messages contain the same archive, because their total lengths are equal. However, each file can be split in blocks in different ways in the two messages.You are given the lengths of blocks in each of the two messages. Help Zhorik to determine what is the maximum number of files could be in the archive, if the Zhorik's assumption is correct.", "input_spec": "The first line contains two integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of blocks in the first and in the second messages. The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009106) \u2014 the length of the blocks that form the first message. The third line contains m integers y1,\u2009y2,\u2009...,\u2009ym (1\u2009\u2264\u2009yi\u2009\u2264\u2009106) \u2014 the length of the blocks that form the second message. It is guaranteed that x1\u2009+\u2009...\u2009+\u2009xn\u2009=\u2009y1\u2009+\u2009...\u2009+\u2009ym. Also, it is guaranteed that x1\u2009+\u2009...\u2009+\u2009xn\u2009\u2264\u2009106.", "output_spec": "Print the maximum number of files the intercepted array could consist of.", "sample_inputs": ["7 6\n2 5 3 1 11 4 4\n7 8 2 4 1 8", "3 3\n1 10 100\n1 100 10", "1 4\n4\n1 1 1 1"], "sample_outputs": ["3", "2", "1"], "notes": "NoteIn the first example the maximum number of files in the archive is 3. For example, it is possible that in the archive are three files of sizes 2\u2009+\u20095\u2009=\u20097, 15\u2009=\u20093\u2009+\u20091\u2009+\u200911\u2009=\u20098\u2009+\u20092\u2009+\u20094\u2009+\u20091 and 4\u2009+\u20094\u2009=\u20098.In the second example it is possible that the archive contains two files of sizes 1 and 110\u2009=\u200910\u2009+\u2009100\u2009=\u2009100\u2009+\u200910. Note that the order of files is kept while transferring archives through the network, so we can't say that there are three files of sizes 1, 10 and 100.In the third example the only possibility is that the archive contains a single file of size 4."}, "positive_code": [{"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}"}, {"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": "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"}], "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"} {"nl": {"description": "There are $$$n$$$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $$$1$$$ to $$$n$$$.It is known that, from the capital (the city with the number $$$1$$$), you can reach any other city by moving along the roads.The President of Berland plans to improve the country's road network. The budget is enough to repair exactly $$$n-1$$$ roads. The President plans to choose a set of $$$n-1$$$ roads such that: it is possible to travel from the capital to any other city along the $$$n-1$$$ chosen roads, if $$$d_i$$$ is the number of roads needed to travel from the capital to city $$$i$$$, moving only along the $$$n-1$$$ chosen roads, then $$$d_1 + d_2 + \\dots + d_n$$$ is minimized (i.e. as minimal as possible). In other words, the set of $$$n-1$$$ roads should preserve the connectivity of the country, and the sum of distances from city $$$1$$$ to all cities should be minimized (where you can only use the $$$n-1$$$ chosen roads).The president instructed the ministry to prepare $$$k$$$ possible options to choose $$$n-1$$$ roads so that both conditions above are met.Write a program that will find $$$k$$$ possible ways to choose roads for repair. If there are fewer than $$$k$$$ ways, then the program should output all possible valid ways to choose roads.", "input_spec": "The first line of the input contains integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 2\\cdot10^5, n-1 \\le m \\le 2\\cdot10^5, 1 \\le k \\le 2\\cdot10^5$$$), where $$$n$$$ is the number of cities in the country, $$$m$$$ is the number of roads and $$$k$$$ is the number of options to choose a set of roads for repair. It is guaranteed that $$$m \\cdot k \\le 10^6$$$. The following $$$m$$$ lines describe the roads, one road per line. Each line contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$, $$$a_i \\ne b_i$$$) \u2014 the numbers of the cities that the $$$i$$$-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.", "output_spec": "Print $$$t$$$ ($$$1 \\le t \\le k$$$) \u2014 the number of ways to choose a set of roads for repair. Recall that you need to find $$$k$$$ different options; if there are fewer than $$$k$$$ of them, then you need to find all possible different valid options. In the following $$$t$$$ lines, print the options, one per line. Print an option as a string of $$$m$$$ characters where the $$$j$$$-th character is equal to '1' if the $$$j$$$-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the $$$t$$$ lines should be different. Since it is guaranteed that $$$m \\cdot k \\le 10^6$$$, the total length of all the $$$t$$$ lines will not exceed $$$10^6$$$. If there are several answers, output any of them.", "sample_inputs": ["4 4 3\n1 2\n2 3\n1 4\n4 3", "4 6 3\n1 2\n2 3\n1 4\n4 3\n2 4\n1 3", "5 6 2\n1 2\n1 3\n2 4\n2 5\n3 4\n3 5"], "sample_outputs": ["2\n1110\n1011", "1\n101001", "2\n111100\n110110"], "notes": null}, "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 Edge(to: Int, pos: Int)\n type WUGraph = Array[Array[Edge]]\n\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n REP(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), i)\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), i)\n }\n g\n }\n\n def solve(): Unit = {\n val N, M, K = ni()\n val (from, to) = na2(M, -1)\n val g = packWUGraph(N, from, to)\n val edges = traceBfs(g)\n\n val roads = Array.ofDim[Int](M)\n val digits = Array.ofDim[Int](N)\n\n def mkRoads(): Unit = {\n import java.util\n util.Arrays.fill(roads, 0)\n REP(N - 1, 1) { i =>\n val e = edges(i)(digits(i))\n roads(e.pos) = 1\n }\n }\n\n def incrDigits(k: Int): Unit = {\n if (digits(k) == edges(k).length - 1) {\n digits(k) = 0\n incrDigits(k - 1)\n } else {\n digits(k) += 1\n }\n }\n\n val ans = ArrayBuffer[String]()\n var i = 0\n while(i < K && digits(0) == 0) {\n mkRoads()\n ans += roads.mkString\n incrDigits(N - 1)\n i += 1\n }\n\n out.println(i)\n ans.foreach(out.println)\n }\n\n /**\n * @return (depth, parent, queue)\n */\n def traceBfs(g: WUGraph, rt: Int = 0) = {\n val n = g.length\n val INF = 1e9.toInt + 10\n val q, p = Array.ofDim[Int](n)\n\n val edges = Array.fill[ArrayBuffer[Edge]](n)(ArrayBuffer())\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 e = g(v)(i)\n val u = e.to\n\n // \u8ddd\u96e2\u304c\u540c\u3058\u306a\u3089\u307e\u305f\u8a2a\u308c\u308b\n if (d(u) == INF) {\n d(u) = d(v) + 1\n p(u) = v\n q(last) = u\n last += 1\n edges(u) += e\n\n // \u8ddd\u96e2\u304c\u540c\u3058\u306a\u3089\u30a8\u30c3\u30b8\u3092\u8ffd\u52a0\n } else if (d(u) == d(v) + 1) {\n edges(u) += e\n }\n }\n cur += 1\n }\n\n edges\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}"}], "negative_code": [], "src_uid": "a8cc83b982c1d017b68a61adcb38d1a7"} {"nl": {"description": "David was given a red checkered rectangle of size $$$n \\times m$$$. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.As a result, he will get a set of rectangles. Rectangles $$$1 \\times 1$$$ are forbidden.David also knows how to paint the cells blue. He wants each rectangle from the resulting set of pieces to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.What is the minimum number of cells David will have to paint?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \\leq n, m \\leq 3 \\cdot 10^4$$$, $$$n \\cdot m \\geq 2$$$).", "output_spec": "For each test case print a single integer \u2014 the minimum number of cells David will have to paint blue.", "sample_inputs": ["4\n1 3\n2 2\n2 5\n3 5"], "sample_outputs": ["1\n2\n4\n5"], "notes": "NoteThe following pictures show how the initial rectangle can be split and cells colored blue.In the first test case: In the second test case: In the third test case: In the fourth test case: "}, "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 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"}, {"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"} {"nl": {"description": "An army of n droids is lined up in one row. Each droid is described by m integers a1,\u2009a2,\u2009...,\u2009am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it). A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?", "input_spec": "The first line contains three integers n,\u2009m,\u2009k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u20095, 0\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of droids, the number of detail types and the number of available shots, respectively. Next n lines follow describing the droids. Each line contains m integers a1,\u2009a2,\u2009...,\u2009am (0\u2009\u2264\u2009ai\u2009\u2264\u2009108), where ai is the number of details of the i-th type for the respective robot.", "output_spec": "Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length. If there are multiple optimal solutions, print any of them. It is not necessary to make exactly k shots, the number of shots can be less.", "sample_inputs": ["5 2 4\n4 0\n1 2\n2 1\n0 2\n1 3", "3 2 4\n1 2\n1 3\n2 2"], "sample_outputs": ["2 2", "1 3"], "notes": "NoteIn the first test the second, third and fourth droids will be destroyed. In the second test the first and second droids will be destroyed."}, "positive_code": [{"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty) {\n all(mm).addFirst(toAdd)\n } else if (toAdd >= all(mm).getFirst) {\n while (!all(mm).isEmpty && toAdd > all(mm).getFirst) {\n all(mm).removeFirst()\n }\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}], "negative_code": [{"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 ) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n // all(mm).add(matrix(e)(mm))\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if ( !all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst)\n all(mm).removeFirst()\n if (all(mm).isEmpty)\n maxes(mm) = 0\n else {\n maxes(mm) = all(mm).getFirst\n }\n\n }\n\n s = s +1\n } else {\n\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (e -s + 1 >= size) {\n size = e-s+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getLast) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n if (all(mm).isEmpty || toAdd > all(mm).getLast)\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getLast) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty) {\n all(mm).addFirst(toAdd)\n } else if (toAdd > all(mm).getFirst) {\n while (!all(mm).isEmpty && toAdd > all(mm).getFirst) {\n all(mm).removeFirst()\n }\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n var s, e = 0\n while ( s <= n-1 ) {\n\n val prev = maxes.clone()\n (0 until m).foreach{ mm =>\n if (matrix(e)(mm) > maxes(mm))\n maxes(mm) = matrix(e)(mm)\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n if (total > bullets || e == n-1) {\n if (e-s >= size) {\n size = e - s\n if ( e == n -1 ) {\n ansMax = maxes.clone()\n } else {\n ansMax = prev\n }\n }\n\n (0 until m).foreach{ mm =>\n maxes(mm) = 0\n }\n\n s = s + 1\n e = s\n } else {\n if (e < n-1)\n e = e + 1\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 ) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n // all(mm).add(matrix(e)(mm))\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if ( !all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst)\n all(mm).removeFirst()\n if (all(mm).isEmpty)\n maxes(mm) = 0\n else {\n maxes(mm) = all(mm).getFirst\n }\n\n }\n\n s = s +1\n } else {\n\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (e -s + 1 > size) {\n size = e-s+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n var s, e = 0\n var loop = true\n while ( s <= n-1 && loop ) {\n\n val prev = maxes.clone()\n (0 until m).foreach{ mm =>\n if (matrix(e)(mm) > maxes(mm))\n maxes(mm) = matrix(e)(mm)\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n if (total > bullets || e == n-1) {\n if (e-s >= size) {\n size = e - s\n if (e == n -1 && total <=bullets ) {\n ansMax = maxes.clone()\n loop = false\n } else {\n ansMax = prev\n }\n }\n\n (0 until m).foreach{ mm =>\n maxes(mm) = 0\n }\n\n s = e+1\n e = s\n } else {\n if (e < n-1)\n e = e + 1\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n var s, e = 0\n while ( s <= n-1 ) {\n\n val prev = maxes.clone()\n (0 until m).foreach{ mm =>\n if (matrix(e)(mm) > maxes(mm))\n maxes(mm) = matrix(e)(mm)\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n if (total > bullets || e == n-1) {\n if (e-s >= size) {\n size = e - s\n if (e == n -1 && total <=bullets ) {\n ansMax = maxes.clone()\n } else {\n ansMax = prev\n }\n }\n\n (0 until m).foreach{ mm =>\n maxes(mm) = 0\n }\n\n s = e+1\n e = s\n } else {\n if (e < n-1)\n e = e + 1\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && s < e) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n // all(mm).add(matrix(e)(mm))\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if ( !all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst)\n all(mm).removeFirst()\n if (all(mm).isEmpty)\n maxes(mm) = 0\n else {\n maxes(mm) = all(mm).getFirst\n }\n\n }\n\n s = s +1\n } else {\n\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (e -s + 1 >= size) {\n size = e-s+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util.Scanner\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n var s, e = 0\n while (e <= n-1) {\n\n val prev = maxes.clone()\n (0 until m).foreach{ mm =>\n if (matrix(e)(mm) > maxes(mm))\n maxes(mm) = matrix(e)(mm)\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n if (total > bullets) {\n if (e-s > size) {\n size = e - s\n ansMax = prev\n }\n\n (0 until m).foreach{ mm =>\n maxes(mm) = 0\n }\n\n s = s + 1\n e = s\n } else {\n e += 1\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getLast) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty) {\n all(mm).addFirst(toAdd)\n } else if (toAdd > all(mm).getFirst) {\n all(mm).removeFirst()\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (all(mm).size > 1 && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getLast) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty) {\n all(mm).addFirst(toAdd)\n } else if (toAdd >= all(mm).getFirst) {\n while (!all(mm).isEmpty && toAdd > all(mm).getFirst) {\n all(mm).removeFirst()\n }\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty ) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "import java.util\nimport java.util.Scanner\nimport java.util.PriorityQueue\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 ) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n // all(mm).add(matrix(e)(mm))\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if (matrix(s)(mm) >= all(mm).getFirst)\n all(mm).removeFirst()\n if (all(mm).isEmpty)\n maxes(mm) = 0\n else {\n maxes(mm) = all(mm).getFirst\n }\n\n }\n s = s +1\n } else {\n\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n }\n\n println(maxes.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n maxes(mm) = matrix(s+1)(mm)\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty) {\n all(mm).addFirst(toAdd)\n } else if (toAdd >= all(mm).getFirst) {\n while (!all(mm).isEmpty && toAdd > all(mm).getFirst) {\n all(mm).removeFirst()\n }\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) == all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n // all(mm).add(matrix(e)(mm))\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if ( !all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst)\n all(mm).removeFirst()\n if (all(mm).isEmpty)\n maxes(mm) = 0\n else {\n maxes(mm) = all(mm).getFirst\n }\n\n }\n\n s = s +1\n } else {\n\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (e -s + 1 >= size) {\n size = e-s+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getLast) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty) {\n all(mm).addFirst(toAdd)\n } else if (toAdd > all(mm).getFirst) {\n all(mm).removeFirst()\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n } else if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getLast) {\n all(mm).removeLast()\n }\n\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 ) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n // all(mm).add(matrix(e)(mm))\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n\n if (total > bullets) {\n\n (0 until m).foreach { mm =>\n if (matrix(s)(mm) >= all(mm).getFirst)\n all(mm).removeFirst()\n if (all(mm).isEmpty)\n maxes(mm) = 0\n else {\n maxes(mm) = all(mm).getFirst\n }\n\n }\n\n\n if (e -s + 1 > size) {\n size = e-s+1\n ansMax = maxes.clone()\n }\n\n s = s +1\n } else {\n\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd >= all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n while (!all(mm).isEmpty && all(mm).getLast <= toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n //if (e -s + 1 > size) {\n //size = e-s+1\n ansMax = maxes.clone()\n //}\n e = e + 1\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}, {"source_code": "\nimport java.util\nimport java.util.Scanner\n\n\n/**\n * Created by dimitar on 2/16/15.\n */\nobject Droids {\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 val bullets = sc.nextLong()\n\n val matrix = Array.ofDim[Long](n,m)\n\n (0 until n) foreach { col =>\n (0 until m) foreach {row =>\n matrix(col)(row) = sc.nextLong()\n }\n }\n\n val maxes = Array.tabulate[Long](m)(_ => 0L)\n var size = 0\n var ansMax = new Array[Long](m)\n\n\n val all = Array.tabulate[util.ArrayDeque[Long]](m)(_ => new util.ArrayDeque[Long])\n\n var s, e = 0\n while ( e <= n-1 && s <= n-1 && e - s >= 0) {\n\n (0 until m).foreach { mm =>\n if (matrix(e)(mm) > maxes(mm)) {\n maxes(mm) = matrix(e)(mm)\n }\n }\n\n val total = maxes.foldLeft(0L)(_ + _)\n val i = s\n val j = e\n\n if (total > bullets && e > s) {\n\n (0 until m).foreach { mm =>\n if (!all(mm).isEmpty && matrix(s)(mm) >= all(mm).getFirst) {\n all(mm).removeFirst()\n }\n if (all(mm).isEmpty) {\n maxes(mm) = 0\n } else {\n maxes(mm) = all(mm).getFirst\n }\n }\n s = s +1\n } else {\n (0 until m).foreach { mm =>\n val toAdd = matrix(e)(mm)\n if (all(mm).isEmpty || toAdd > all(mm).getFirst) {\n all(mm).addFirst(toAdd)\n } else {\n if (!all(mm).isEmpty && all(mm).getLast < toAdd) {\n all(mm).removeLast()\n }\n all(mm).addLast(toAdd)\n }\n }\n e = e + 1\n }\n\n if (j - i + 1 >= size && total <= bullets) {\n size = j-i+1\n ansMax = maxes.clone()\n }\n\n }\n\n println(ansMax.toBuffer.mkString(\" \"))\n }\n\n}\n"}], "src_uid": "15570b36212b2ce2272195d92def258d"} {"nl": {"description": "The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of boys. The second line contains sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009100) \u2014 the number of girls. The fourth line contains sequence b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009100), where bj is the j-th girl's dancing skill.", "output_spec": "Print a single number \u2014 the required maximum possible number of pairs.", "sample_inputs": ["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"], "sample_outputs": ["3", "0", "2"], "notes": null}, "positive_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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k\u2009=\u200920 such ATM can give sums 100\u2009000 burles and 96\u2009000 burles, but it cannot give sums 99\u2009000 and 101\u2009000 burles.Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u20095000, 1\u2009\u2264\u2009k\u2009\u2264\u200920). The next line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009107) \u2014 the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order. The next line contains integer q (1\u2009\u2264\u2009q\u2009\u2264\u200920) \u2014 the number of requests for cash withdrawal that you will make. The next q lines contain numbers xi (1\u2009\u2264\u2009xi\u2009\u2264\u20092\u00b7108) \u2014 the sums of money in burles that you are going to withdraw from the ATM.", "output_spec": "For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print \u2009-\u20091, if it is impossible to get the corresponding sum.", "sample_inputs": ["6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950", "5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15"], "sample_outputs": ["6\n20\n19\n20\n-1\n3\n-1\n-1", "1\n1\n1\n2\n2\n2\n2\n-1"], "notes": null}, "positive_code": [{"source_code": "object VK2015C extends App {\n def readInts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n val a = readInts\n\n val map = scala.collection.mutable.HashMap.empty[Int, Int]\n\n for {\n x <- a\n c <- 0 to k\n xc = x * c\n curc = map.getOrElse(xc, k + 1)\n if c < curc\n } map += xc -> c\n\n val Array(q) = readInts\n for (i <- 1 to q) {\n val ans2 = for {\n z <- readInts\n (xc, c) <- map\n ctot <- map.get(z - xc)\n } yield ctot + c\n val ans = if (ans2.isEmpty) k+1 else ans2.min\n if (ans <= k) println(ans) else println(-1)\n }\n}"}], "negative_code": [{"source_code": "object C extends App {\n def readInts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n val a = readInts\n val Array(q) = readInts\n\n val map = scala.collection.mutable.Map.empty[Int, Int]\n\n for {\n z <- 0 to n-1\n x <- 0 to n-1\n zc <- 0 to k\n xc <- 0 to k\n newc = zc + xc\n if newc <= k\n money = z*zc+x*xc\n curc = map.getOrElse(money, k+1)\n if newc < curc\n } yield map += money -> newc\n for (i <- 1 to q) {\n val Array(money) = readInts\n println(map.getOrElse(money, -1))\n }\n}"}, {"source_code": "object C extends App {\n def readInts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n val a = readInts\n val Array(q) = readInts\n\n val map = scala.collection.mutable.Map.empty[Int, Int]\n\n for {\n z <- 0 to n-1\n x <- 0 to n-1\n zc <- 0 to k\n xc <- 0 to k\n newc = zc + xc\n if newc <= k\n money = z * zc + x * xc\n curc = map.getOrElse(money, k+1)\n if newc < curc\n } map += money -> newc\n for (i <- 1 to q) {\n val Array(money) = readInts\n println(map.getOrElse(money, -1))\n }\n}"}], "src_uid": "5d8521e467cad53cf9403200e4c99b89"} {"nl": {"description": "There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $$$n$$$ packets with inflatable balloons, where $$$i$$$-th of them has exactly $$$a_i$$$ balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold: Do not rip the packets (both Grigory and Andrew should get unbroken packets); Distribute all packets (every packet should be given to someone); Give both Grigory and Andrew at least one packet; To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.", "input_spec": "The first line of input contains a single integer $$$n$$$ ($$$1 \\le n \\le 10$$$)\u00a0\u2014 the number of packets with balloons. The second line contains $$$n$$$ integers: $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$1 \\le a_i \\le 1000$$$)\u00a0\u2014 the number of balloons inside the corresponding packet.", "output_spec": "If it's impossible to divide the balloons satisfying the conditions above, print $$$-1$$$. Otherwise, print an integer $$$k$$$\u00a0\u2014 the number of packets to give to Grigory followed by $$$k$$$ distinct integers from $$$1$$$ to $$$n$$$\u00a0\u2014 the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them.", "sample_inputs": ["3\n1 2 1", "2\n5 5", "1\n10"], "sample_outputs": ["2\n1 2", "-1", "-1"], "notes": "NoteIn the first test Grigory gets $$$3$$$ balloons in total while Andrey gets $$$1$$$.In the second test there's only one way to divide the packets which leads to equal numbers of balloons.In the third test one of the boys won't get a packet at all."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.", "input_spec": "The single line contains three integers r, s and p (1\u2009\u2264\u2009r,\u2009s,\u2009p\u2009\u2264\u2009100)\u00a0\u2014 the original number of individuals in the species of rock, scissors and paper, respectively.", "output_spec": "Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10\u2009-\u20099.", "sample_inputs": ["2 2 2", "2 1 2", "1 1 3"], "sample_outputs": ["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"], "notes": null}, "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": "/**\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"}, {"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"} {"nl": {"description": "This is the hard version of this problem. The only difference is the constraint on $$$k$$$ \u2014 the number of gifts in the offer. In this version: $$$2 \\le k \\le n$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky\u00a0\u2014 today the offer \"$$$k$$$ of goods for the price of one\" is held in store.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$\u00a0\u2014 the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \\ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$). Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \\ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the test. The next lines contain a description of $$$t$$$ test cases. The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le p \\le 2\\cdot10^9$$$, $$$2 \\le k \\le n$$$)\u00a0\u2014 the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^4$$$)\u00a0\u2014 the prices of goods. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case in a separate line print one integer $$$m$$$\u00a0\u2014 the maximum number of goods that Vasya can buy.", "sample_inputs": ["8\n5 6 2\n2 4 3 5 7\n5 11 2\n2 4 3 5 7\n3 2 3\n4 2 6\n5 2 3\n10 1 3 9 2\n2 10000 2\n10000 10000\n2 9999 2\n10000 10000\n4 6 4\n3 2 3 2\n5 5 3\n1 2 2 1 2"], "sample_outputs": ["3\n4\n1\n1\n2\n0\n4\n5"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": " Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.", "input_spec": "In the first string, the number of games n (1\u2009\u2264\u2009n\u2009\u2264\u2009350000) is given. Each game is represented by a pair of scores a, b (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009109)\u00a0\u2013 the results of Slastyona and Pushok, correspondingly.", "output_spec": "For each pair of scores, answer \"Yes\" if it's possible for a game to finish with given score, and \"No\" otherwise. You can output each letter in arbitrary case (upper or lower).", "sample_inputs": ["6\n2 4\n75 45\n8 8\n16 16\n247 994\n1000000000 1000000"], "sample_outputs": ["Yes\nYes\nYes\nNo\nNo\nYes"], "notes": "NoteFirst game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuilder.ofInt\n\nobject C 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 LIMIT = 1003\n val divisors = Array.tabulate(LIMIT)(identity)\n val primeBuilder = new mutable.ArrayBuilder.ofInt\n\n var i = 2\n while (i < LIMIT) {\n if (divisors(i) == i) {\n primeBuilder += i\n var j = i * i\n while (j < LIMIT) {\n divisors(j) = i\n j += i\n }\n }\n i += 1\n }\n val primes = primeBuilder.result\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n\n // Stream.from(2).takeWhile(i => i*i*i < LIMIT).filter(prime(_)).foreach { i =>\n // (i*i until LIMIT by i).foreach(prime(_) = false)\n // }\n\n val Array(n) = readInts(1)\n val res = Array.ofDim[String](n)\n\n for (i <- 0 until n) {\n var ok = true\n val Array(_a, _b) = readInts(2)\n var g = gcd(_a, _b)\n var pi = 0\n var a = _a\n var b = _b\n while (pi < primes.length && g > 1 && ok) {\n val d = primes(pi)\n if (g % d == 0) {\n //println(g, d, a, b)\n var degA, degB = 0\n while (a % d == 0) {\n degA += 1\n a /= d\n }\n while (b % d == 0) {\n degB += 1\n b /= d\n }\n while ((degA > 0 && degB > 1) || (degB > 0 && degA > 1)) {\n if (degA >= degB) {\n degA -= 2\n degB -= 1\n } else {\n degA -= 1\n degB -= 2\n }\n }\n if (degA + degB > 0) ok = false\n while (g % d == 0) g /= d\n }\n pi += 1\n }\n if (a != b.toLong * b && b != a.toLong * a) ok = false\n res(i) = if (ok) \"Yes\" else \"No\"\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\nimport scala.collection.mutable.ArrayBuilder.ofInt\n\nobject C 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 LIMIT = 1003\n val divisors = Array.tabulate(LIMIT)(identity)\n val primeBuilder = new mutable.ArrayBuilder.ofInt\n\n var i = 2\n while (i * i < LIMIT) {\n if (divisors(i) == i) {\n primeBuilder += i\n var j = i * i\n while (j < LIMIT) {\n divisors(j) = i\n j += i\n }\n }\n i += 1\n }\n val primes = primeBuilder.result\n\n def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)\n\n // Stream.from(2).takeWhile(i => i*i*i < LIMIT).filter(prime(_)).foreach { i =>\n // (i*i until LIMIT by i).foreach(prime(_) = false)\n // }\n\n val Array(n) = readInts(1)\n val res = Array.ofDim[String](n)\n\n for (i <- 0 until n) {\n var ok = true\n val Array(_a, _b) = readInts(2)\n var g = gcd(_a, _b)\n var pi = 0\n var a = _a\n var b = _b\n while (pi < primes.length && g > 1) {\n val d = primes(pi)\n if (g % d == 0) {\n //println(g, d, a, b)\n var degA, degB = 0\n while (a % d == 0) {\n degA += 1\n a /= d\n }\n while (b % d == 0) {\n degB += 1\n b /= d\n }\n while ((degA > 0 && degB > 1) || (degB > 0 && degA > 1)) {\n if (degA >= degB) {\n degA -= 2\n degB -= 1\n } else {\n degA -= 1\n degB -= 2\n }\n }\n if (degA + degB > 0) ok = false\n while (g % d == 0) g /= d\n }\n pi += 1\n }\n if (a != b.toLong * b && b != a.toLong * a) ok = false\n res(i) = if (ok) \"Yes\" else \"No\"\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": "933135ef124b35028c1f309d69515e44"} {"nl": {"description": "Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word \"Bulbasaur\" (without quotes) and sticks it on his wall. Bash is very particular about case\u00a0\u2014 the first letter of \"Bulbasaur\" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word \"Bulbasaur\" from the newspaper.Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?Note: uppercase and lowercase letters are considered different.", "input_spec": "Input contains a single line containing a string s (1\u2009\u2009\u2264\u2009\u2009|s|\u2009\u2009\u2264\u2009\u2009105)\u00a0\u2014 the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s. The string s contains lowercase and uppercase English letters, i.e. .", "output_spec": "Output a single integer, the answer to the problem.", "sample_inputs": ["Bulbbasaur", "F", "aBddulbasaurrgndgbualdBdsagaurrgndbb"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first case, you could pick: Bulbbasaur.In the second case, there is no way to pick even a single Bulbasaur.In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words \"Bulbasaur\"."}, "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 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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given three integers $$$a$$$, $$$b$$$, $$$k$$$.Find two binary integers $$$x$$$ and $$$y$$$ ($$$x \\ge y$$$) such that both $$$x$$$ and $$$y$$$ consist of $$$a$$$ zeroes and $$$b$$$ ones; $$$x - y$$$ (also written in binary form) has exactly $$$k$$$ ones. You are not allowed to use leading zeros for $$$x$$$ and $$$y$$$. ", "input_spec": "The only line contains three integers $$$a$$$, $$$b$$$, and $$$k$$$ ($$$0 \\leq a$$$; $$$1 \\leq b$$$; $$$0 \\leq k \\leq a + b \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the number of zeroes, ones, and the number of ones in the result.", "output_spec": "If it's possible to find two suitable integers, print \"Yes\" followed by $$$x$$$ and $$$y$$$ in base-2. Otherwise print \"No\". If there are multiple possible answers, print any of them.", "sample_inputs": ["4 2 3", "3 2 1", "3 2 5"], "sample_outputs": ["Yes\n101000\n100001", "Yes\n10100\n10010", "No"], "notes": "NoteIn the first example, $$$x = 101000_2 = 2^5 + 2^3 = 40_{10}$$$, $$$y = 100001_2 = 2^5 + 2^0 = 33_{10}$$$, $$$40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}$$$. Hence $$$x-y$$$ has $$$3$$$ ones in base-2.In the second example, $$$x = 10100_2 = 2^4 + 2^2 = 20_{10}$$$, $$$y = 10010_2 = 2^4 + 2^1 = 18$$$, $$$x - y = 20 - 18 = 2_{10} = 10_{2}$$$. This is precisely one 1.In the third example, one may show, that it's impossible to find an answer."}, "positive_code": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (b > k - a + 1 && a > 0 && k > a) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - (k - a + 1)) + \"0\" + \"1\" * (k - a) + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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": [{"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (b > k - a + 1 && a > 0) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - (k - a + 1)) + \"0\" + \"1\" * (k - a) + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (a == k - 1 && b > 2) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - 2) + \"01\" + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (b > k - a + 1) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - (k - a + 1)) + \"0\" + \"1\" * (k - a) + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (b > k - a + 1 && a > 1) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - (k - a) - 1) + \"0\" + \"1\" * (k - a) + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (b > k - a + 1) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - (k - a) - 1) + \"0\" + \"1\" * (k - a) + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (a == k - 1 && b > 2) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" * (b - 2) + \"01\" + \"0\" * (a - 1) + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * b + \"0\" * a\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (a == k - 1 && b > 1) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" + \"0\" * a + \"1\" * (b - 1)\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * k + \"0\" * b\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else if (a == k - 1 && b > 1) {\n val s = \"1\" * b + \"0\" * a\n val t = \"1\" + \"0\" * a + \"1\" * (b - 1)\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}, {"source_code": "object D {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val a, b, k = nextInt\n\n if (k == 0) {\n val s = \"1\" * k + \"0\" * b\n out.println(\"Yes\")\n out.println(s)\n out.println(s)\n } else if (a >= k && b > 1) {\n val s = \"1\" * (b - 1) + \"0\" * (a - k) + \"1\" + \"0\" * k\n val t = \"1\" * (b - 1) + \"0\" * a + \"1\"\n out.println(\"Yes\")\n out.println(s)\n out.println(t)\n } else {\n out.println(\"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"}], "src_uid": "ea620a8dbef506567464dcaddcc2b34f"} {"nl": {"description": "ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0\u2009\u2264\u2009ci\u2009\u2264\u2009m, where ci\u2009=\u20090 means that tree i is uncolored.ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci\u2009=\u20090. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi,\u2009j litres of paint.The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2,\u20091,\u20091,\u20091,\u20093,\u20092,\u20092,\u20093,\u20091,\u20093, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2},\u2009{1,\u20091,\u20091},\u2009{3},\u2009{2,\u20092},\u2009{3},\u2009{1},\u2009{3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.Please note that the friends can't color the trees that are already colored.", "input_spec": "The first line contains three integers, n, m and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of trees, number of colors and beauty of the resulting coloring respectively. The second line contains n integers c1,\u2009c2,\u2009...,\u2009cn (0\u2009\u2264\u2009ci\u2009\u2264\u2009m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci. Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi,\u2009j (1\u2009\u2264\u2009pi,\u2009j\u2009\u2264\u2009109)\u00a0\u2014 the amount of litres the friends need to color i-th tree with color j. pi,\u2009j's are specified even for the initially colored trees, but such trees still can't be colored.", "output_spec": "Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print \u2009-\u20091.", "sample_inputs": ["3 2 2\n0 0 0\n1 2\n3 4\n5 6", "3 2 2\n2 1 2\n1 3\n2 4\n3 5", "3 2 2\n2 0 0\n1 3\n2 4\n3 5", "3 2 3\n2 1 2\n1 3\n2 4\n3 5"], "sample_outputs": ["10", "-1", "5", "0"], "notes": "NoteIn the first sample case, coloring the trees with colors 2,\u20091,\u20091 minimizes the amount of paint used, which equals to 2\u2009+\u20093\u2009+\u20095\u2009=\u200910. Note that 1,\u20091,\u20091 would not be valid because the beauty of such coloring equals to 1 ({1,\u20091,\u20091} is a way to group the trees into a single group of the same color).In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is \u2009-\u20091.In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0. "}, "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, m, k) = readInts(3)\n val cs = readInts(n)\n val ps = Array.fill(n) { readInts(m) }\n\n val MAX = Long.MaxValue / 2\n val dp = Array.fill(n, k + 1, m){ MAX }\n\n if (cs(0) == 0) {\n for (color <- 0 until m) dp(0)(1)(color) = ps(0)(color)\n } else {\n dp(0)(1)(cs(0) - 1) = 0\n }\n\n for (tree <- 1 until n) {\n if (cs(tree) == 0) {\n for (groups <- 0 to k) {\n var prevColor = 0\n while (prevColor < m) {\n if (dp(tree - 1)(groups)(prevColor) < MAX) {\n var color = 0\n while (color < m) {\n if (prevColor == color) {\n dp(tree)(groups)(color) = Math.min(dp(tree)(groups)(color), dp(tree - 1)(groups)(prevColor) + ps(tree)(color))\n } else if (groups < k) {\n dp(tree)(groups + 1)(color) = Math.min(dp(tree)(groups + 1)(color), dp(tree - 1)(groups)(prevColor) + ps(tree)(color))\n }\n color += 1\n }\n }\n prevColor += 1\n }\n }\n } else {\n for (groups <- 0 to k) {\n val color = cs(tree) - 1\n var prevColor = 0\n while (prevColor < m) {\n if (dp(tree - 1)(groups)(prevColor) < MAX) {\n if (color == prevColor) {\n dp(tree)(groups)(color) = Math.min(dp(tree)(groups)(color), dp(tree - 1)(groups)(prevColor))\n } else if (groups < k) {\n dp(tree)(groups + 1)(color) = Math.min(dp(tree)(groups + 1)(color), dp(tree - 1)(groups)(prevColor))\n }\n }\n prevColor += 1\n }\n }\n }\n }\n\n val res0 = dp(n - 1)(k).min\n val res = if (res0 >= MAX) -1 else res0\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "f8fa6afc8946289c484503b0bf9d5551"} {"nl": {"description": "You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \\le i, j \\le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \\times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \\times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces \u2014 the correct solution of the sudoku puzzle.", "output_spec": "For each test case, print the answer \u2014 the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.", "sample_inputs": ["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"], "sample_outputs": ["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1,\u2009a2,\u2009...,\u2009an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. \"But why split the money equally?\" \u2014 you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the coins' values. All numbers are separated with spaces.", "output_spec": "In the single line print the single number \u2014 the minimum needed number of coins.", "sample_inputs": ["2\n3 3", "3\n2 1 2"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6,\u20090 correspondingly). If you take 1 coin, you get sums 3,\u20093. If you take 0 coins, you get sums 0,\u20096. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1,\u20092 or 2,\u20092. In any case, the minimum number of coins equals 2. "}, "positive_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 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": "//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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.", "input_spec": "The first line contains four space-separated x1,\u2009y1,\u2009x2,\u2009y2 (\u2009-\u2009100\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.", "output_spec": "If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3,\u2009y3,\u2009x4,\u2009y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them. Note that x3,\u2009y3,\u2009x4,\u2009y4 must be in the range (\u2009-\u20091000\u2009\u2264\u2009x3,\u2009y3,\u2009x4,\u2009y4\u2009\u2264\u20091000).", "sample_inputs": ["0 0 0 1", "0 0 1 1", "0 0 1 2"], "sample_outputs": ["1 0 1 1", "0 1 1 0", "-1"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "An array $$$[b_1, b_2, \\ldots, b_m]$$$ is a palindrome, if $$$b_i = b_{m+1-i}$$$ for each $$$i$$$ from $$$1$$$ to $$$m$$$. Empty array is also a palindrome.An array is called kalindrome, if the following condition holds: It's possible to select some integer $$$x$$$ and delete some of the elements of the array equal to $$$x$$$, so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to $$$x$$$, and you don't have to delete at least one element equal to $$$x$$$.For example : $$$[1, 2, 1]$$$ is kalindrome because you can simply not delete a single element. $$$[3, 1, 2, 3, 1]$$$ is kalindrome because you can choose $$$x = 3$$$ and delete both elements equal to $$$3$$$, obtaining array $$$[1, 2, 1]$$$, which is a palindrome. $$$[1, 2, 3]$$$ is not kalindrome. You are given an array $$$[a_1, a_2, \\ldots, a_n]$$$. Determine if $$$a$$$ is kalindrome or not.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 elements of the array. It's guaranteed that the sum of $$$n$$$ over all test cases won't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print YES if $$$a$$$ is kalindrome and NO otherwise. You can print each letter in any case.", "sample_inputs": ["4\n1\n1\n2\n1 2\n3\n1 2 3\n5\n1 4 4 1 4"], "sample_outputs": ["YES\nYES\nNO\nYES"], "notes": "NoteIn the first test case, array $$$[1]$$$ is already a palindrome, so it's a kalindrome as well.In the second test case, we can choose $$$x = 2$$$, delete the second element, and obtain array $$$[1]$$$, which is a palindrome.In the third test case, it's impossible to obtain a palindrome.In the fourth test case, you can choose $$$x = 4$$$ and delete the fifth element, obtaining $$$[1, 4, 4, 1]$$$. You also can choose $$$x = 1$$$, delete the first and the fourth elements, and obtain $$$[4, 4, 4]$$$."}, "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 Main2 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, c: Double)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (b == that.b)\n return -1 * c.compareTo(that.c)\n else\n return -1 * b.compareTo(that.b)\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 for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n+2)\n for (i <- 1 to n) {\n arr(i) = readInt()\n }\n var pal = false\n var ig1 = arr(0)\n var ig2 = arr(0)\n for (i <- n/2 to n) {\n if (arr(i) != arr(n-i+1)) {\n ig1 = arr(i)\n ig2 = arr(n-i+1)\n }\n }\n def check(ig: Int): Boolean = {\n var l = 1\n var r = n\n while (l <= r) {\n while (l <= n && arr(l) == ig) {\n l += 1\n }\n while (r >= 1 && arr(r) == ig) {\n r -= 1\n }\n if (l > n || r < 1) {\n if (l > n && r < 1)\n return true\n else\n return false\n }\n if (arr(l) != arr(r))\n return false\n l += 1\n r -= 1\n }\n return true\n }\n if (check(ig1) || check(ig2))\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n }\n writer.flush()\n}\n"}], "negative_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 Main2 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, c: Double)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (b == that.b)\n return -1 * c.compareTo(that.c)\n else\n return -1 * b.compareTo(that.b)\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 for (tt <- 1 to t) {\n val n = readInt()\n val arr = new Array[Int](n+2)\n for (i <- 1 to n) {\n arr(i) = readInt()\n }\n var pal = false\n var ig1 = arr(0)\n var ig2 = arr(0)\n for (i <- 1 to n/2) {\n if (arr(i) != arr(n-i+1)) {\n ig1 = arr(i)\n ig2 = arr(n-i+1)\n }\n }\n def check(ig: Int): Boolean = {\n var l = 1\n var r = n\n while (l < r) {\n while (l <= n && arr(l) == ig) {\n l += 1\n }\n while (r >= 1 && arr(r) == ig) {\n r -= 1\n }\n if (l > n || r < 1)\n return true\n if (arr(l) != arr(r))\n return false\n l += 1\n r -= 1\n }\n return true\n }\n if (check(ig1) || check(ig2))\n writer.println(\"YES\")\n else\n writer.println(\"NO\")\n }\n writer.flush()\n}\n"}], "src_uid": "712e6e228e8b7cedd9bf6b85cd35c0b7"} {"nl": {"description": "One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.A contest has just finished. There are n teams, numbered 1 through n. The i-th team has ti balloons and weight wi. It's guaranteed that ti doesn't exceed wi so nobody floats initially.Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.What is the best place Limak can get?", "input_spec": "The first line of the standard input contains one integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009300\u2009000)\u00a0\u2014 the number of teams. The i-th of n following lines contains two integers ti and wi (0\u2009\u2264\u2009ti\u2009\u2264\u2009wi\u2009\u2264\u20091018)\u00a0\u2014 respectively the number of balloons and the weight of the i-th team. Limak is a member of the first team.", "output_spec": "Print one integer denoting the best place Limak can get.", "sample_inputs": ["8\n20 1000\n32 37\n40 1000\n45 50\n16 16\n16 16\n14 1000\n2 1000", "7\n4 4\n4 4\n4 4\n4 4\n4 4\n4 4\n5 5", "7\n14000000003 1000000000000000000\n81000000000 88000000000\n5000000000 7000000000\n15000000000 39000000000\n46000000000 51000000000\n0 1000000000\n0 0"], "sample_outputs": ["3", "2", "2"], "notes": "NoteIn the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is: Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified. Limak gives 1 balloon to each of two teams with 16 balloons initially. Limak has 20\u2009-\u20096\u2009-\u20096\u2009-\u20091\u2009-\u20091\u2009=\u20096 balloons. There are three other teams left and their numbers of balloons are 40, 14 and 2. Limak gets the third place because there are two teams with more balloons. In the second sample, Limak has the second place and he can't improve it.In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81\u2009000\u2009000\u2009000, 5\u2009000\u2009000\u2009000 and 46\u2009000\u2009000\u2009000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7)."}, "positive_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 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"}, {"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"} {"nl": {"description": "During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string $$$c$$$ consisting of lowercase English characters and asterisks (\"*\"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).Katie has a favorite string $$$s$$$ and a not-so-favorite string $$$t$$$ and she would love to recover the mysterious code so that it has as many occurrences of $$$s$$$ as possible and as little occurrences of $$$t$$$ as possible. Formally, let's denote $$$f(x, y)$$$ as the number of occurrences of $$$y$$$ in $$$x$$$ (for example, $$$f(aababa, ab) = 2$$$). Katie wants to recover the code $$$c'$$$ conforming to the original $$$c$$$, such that $$$f(c', s) - f(c', t)$$$ is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.", "input_spec": "The first line contains string $$$c$$$ ($$$1 \\leq |c| \\leq 1000$$$)\u00a0\u2014 the mysterious code . It is guaranteed that $$$c$$$ consists of lowercase English characters and asterisks \"*\" only. The second and third line contain strings $$$s$$$ and $$$t$$$ respectively ($$$1 \\leq |s|, |t| \\leq 50$$$, $$$s \\neq t$$$). It is guaranteed that $$$s$$$ and $$$t$$$ consist of lowercase English characters only.", "output_spec": "Print a single integer\u00a0\u2014 the largest possible value of $$$f(c', s) - f(c', t)$$$ of the recovered code.", "sample_inputs": ["*****\nkatie\nshiro", "caat\ncaat\na", "*a*\nbba\nb", "***\ncc\nz"], "sample_outputs": ["1", "-1", "0", "2"], "notes": "NoteIn the first example, for $$$c'$$$ equal to \"katie\" $$$f(c', s) = 1$$$ and $$$f(c', t) = 0$$$, which makes $$$f(c', s) - f(c', t) = 1$$$ which is the largest possible.In the second example, the only $$$c'$$$ conforming to the given $$$c$$$ is \"caat\". The corresponding $$$f(c', s) - f(c', t) = 1 - 2 = -1$$$.In the third example, there are multiple ways to recover the code such that $$$f(c', s) - f(c', t)$$$ is largest possible, for example \"aaa\", \"aac\", or even \"zaz\". The value of $$$f(c', s) - f(c', t) = 0$$$ for all of these recovered codes.In the fourth example, the optimal recovered code $$$c'$$$ would be \"ccc\". The corresponding $$$f(c', s) - f(c', t) = 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 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val C, S, T = ns()\n\n val dp = Array.fill[Int](C.length + 1, S.length, T.length)(-1e5.toInt)\n dp(0)(0)(0) = 0\n val kmpS = new KMP(S)\n val kmpT = new KMP(T)\n\n def step(i: Int, c: Char): Unit = {\n REP(S.length) { j =>\n REP(T.length) { k =>\n var nextS = kmpS.longestSuffix(j, c)\n var nextT = kmpT.longestSuffix(k, c)\n var diff = 0\n if (nextS == S.length) {\n diff += 1\n nextS = kmpS.kmp.last\n }\n if (nextT == T.length) {\n diff -= 1\n nextT = kmpT.kmp.last\n }\n dp(i + 1)(nextS)(nextT) = max(dp(i + 1)(nextS)(nextT), dp(i)(j)(k) + diff)\n }\n }\n }\n\n REP(C.length) { i =>\n if (C(i) != '*') {\n step(i, C(i))\n } else {\n REP(26) { j =>\n step(i, ('a' + j).toChar)\n }\n }\n debug(s\"DP($i)\")\n debugDim(dp(i + 1))\n }\n\n val ans = dp(C.length).map(_.max).max\n out.println(ans)\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 // kmp(i-1)\u4ee5\u4e0b\u3057\u304b\u53c2\u7167\u3055\u308c\u306a\u3044\u304b\u3089OK\n kmp(i) = longestSuffix(kmp(i - 1), word(i - 1))\n }\n\n def findFirst(text: String): Int = {\n var j = 0\n REP(text.length) { i =>\n j = longestSuffix(j, text(i))\n if (j == word.length) return i - word.length + 1\n }\n -1\n }\n\n def longestSuffix(matched: Int, c: Char): Int = {\n var j = matched\n var continues = true\n while(continues) {\n if (j < word.length && word(j) == c) {\n j += 1\n continues = false\n } else if (j == 0) continues = false\n else j = kmp(j)\n }\n j\n }\n }\n\n}"}], "negative_code": [], "src_uid": "ff0d972460443cc13156ede0d4a16f52"} {"nl": {"description": "Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: \"+ x\"\u00a0\u2014 add integer x to multiset A. \"- x\"\u00a0\u2014 erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. \"? x\"\u00a0\u2014 you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.", "input_spec": "The first line of the input contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A.", "output_spec": "For each query of the type '?' print one integer\u00a0\u2014 the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.", "sample_inputs": ["10\n+ 8\n+ 9\n+ 11\n+ 6\n+ 1\n? 3\n- 8\n? 3\n? 8\n? 11"], "sample_outputs": ["11\n10\n14\n13"], "notes": "NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer \u00a0\u2014 maximum among integers , , , and ."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Multiset extends App {\n\n\n implicit class RichInt(val v: Int) {\n def bits: Seq[Byte] = for (x <- 0 to 30) yield (1 & v >> (30 - x)).toByte\n\n }\n\n\n sealed trait Tree\n\n case class Node(zero: Tree, one: Tree) extends Tree\n\n case object Empty extends Tree\n\n case class Leaf(var count: Int, val num: Int) extends Tree\n\n implicit class TreeOps(t: Tree) {\n def add(v: Int): Tree = {\n def add(t: Tree, bits: Seq[Byte]): Tree = t match {\n case Leaf(x, num) => Leaf(x + 1, num)\n case Empty if bits.isEmpty => Leaf(1, v)\n case Empty => add(Node(Empty, Empty), bits)\n case Node(zero, one) => if (bits.head > 0) Node(zero, add(one, bits.tail))\n else Node(add(zero, bits.tail), one)\n }\n\n add(t, v.bits)\n }\n\n def maxXor(v: Int): Int = {\n def max(t: Tree, bits: Seq[Byte]): Int = t match {\n case Empty => v\n case Leaf(_, num) => v ^ num\n case Node(zero, Empty) => max(zero, bits.tail)\n case Node(Empty, one) => max(one, bits.tail)\n case Node(zero, one) => if (bits.head == 0) max(one, bits.tail) else max(zero, bits.tail)\n }\n\n max(t, v.bits)\n }\n\n def remove(v: Int): Tree = {\n def remove(t: Tree, bits: Seq[Byte]): Tree = t match {\n case Leaf(1, v) => Empty\n case Leaf(n, v) => Leaf(n - 1, v)\n case Empty => Empty\n case Node(zero, one) => {\n val result = if (bits.head > 0) Node(zero, remove(one, bits.tail))\n else Node(remove(zero, bits.tail), one)\n if (result.one == Empty && result.zero == Empty) Empty\n else result\n }\n }\n\n remove(t, v.bits)\n }\n\n }\n\n var t: Tree = Empty.add(0)\n val numOfEntrees = StdIn.readLine().toInt\n val result: ArrayBuffer[String] = ArrayBuffer()\n for (x <- 1 to numOfEntrees) {\n val data = StdIn.readLine().split(\" \")\n val command = data.head\n val value = data.tail.head.toInt\n command match {\n case \"+\" => t = t.add(value)\n case \"-\" => t = t.remove(value)\n case \"?\" => result.append(s\"${t.maxXor(value)}\")\n }\n }\n result.foreach(println)\n}\n\n\n\n\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.collection.mutable.ArrayBuffer\nimport scala.io.StdIn\n\nobject Multiset extends App {\n\n\n implicit class RichInt(val v: Int) {\n def bits: Seq[Byte] = for (x <- 0 to 30) yield (1 & v >> (30 - x)).toByte\n\n }\n\n\n sealed trait Tree\n\n case class Node(zero: Tree, one: Tree) extends Tree\n\n case object Empty extends Tree\n\n case class Leaf(var count: Int, val num: Int) extends Tree\n\n implicit class TreeOps(t: Tree) {\n def add(v: Int): Tree = {\n def add(t: Tree, bits: Seq[Byte]): Tree = t match {\n case Leaf(x, num) => Leaf(x + 1, num)\n case Empty if bits.isEmpty => Leaf(1, v)\n case Empty => add(Node(Empty, Empty), bits)\n case Node(zero, one) => if (bits.head > 0) Node(zero, add(one, bits.tail))\n else Node(add(zero, bits.tail), one)\n }\n\n add(t, v.bits)\n }\n\n def maxXor(v: Int): Int = {\n def max(t: Tree, bits: Seq[Byte]): Int = t match {\n case Empty => v\n case Leaf(_, num) => v ^ num\n case Node(zero, Empty) => max(zero, bits.tail)\n case Node(Empty, one) => max(one, bits.tail)\n case Node(zero, one) => if (bits.head == 0) max(one, bits.tail) else max(zero, bits.tail)\n }\n\n max(t, v.bits)\n }\n\n def remove(v: Int): Tree = {\n def remove(t: Tree, bits: Seq[Byte]): Tree = t match {\n case Leaf(1, v) => Empty\n case Leaf(n, v) => Leaf(n - 1, v)\n case Empty => Empty\n case Node(zero, one) => {\n val result = if (bits.head > 0) Node(zero, remove(one, bits.tail))\n else Node(remove(zero, bits.tail), one)\n if (result.one == Empty && result.zero == Empty) Empty\n else result\n }\n }\n\n remove(t, v.bits)\n }\n\n }\n\n var t: Tree = Empty\n val numOfEntrees = StdIn.readLine().toInt\n val result: ArrayBuffer[String] = ArrayBuffer()\n for (x <- 1 to numOfEntrees) {\n val data = StdIn.readLine().split(\" \")\n val command = data.head\n val value = data.tail.head.toInt\n command match {\n case \"+\" => t = t.add(value)\n case \"-\" => t = t.remove(value)\n case \"?\" => result.append(s\"${t.maxXor(value)}\")\n }\n }\n result.foreach(println)\n}\n\n\n\n\n"}], "src_uid": "add040eecd8322630fbbce0a2a1de45e"} {"nl": {"description": "Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k\u2009\u2265\u20090). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.", "input_spec": "The first line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009106), that is the binary representation of number n without leading zeroes (n\u2009>\u20090).", "output_spec": "Print a single integer \u2014 the minimum amount of beautiful numbers that give a total of n.", "sample_inputs": ["10", "111", "1101101"], "sample_outputs": ["1", "2", "4"], "notes": "NoteIn the first sample n\u2009=\u20092 is a beautiful number.In the second sample n\u2009=\u20097 and Valera can decompose it into sum 23\u2009+\u2009(\u2009-\u200920).In the third sample n\u2009=\u2009109 can be decomposed into the sum of four summands as follows: 27\u2009+\u2009(\u2009-\u200924)\u2009+\u2009(\u2009-\u200922)\u2009+\u200920."}, "positive_code": [{"source_code": "object probE extends App{\n val arr = readLine()\n var ones = 0\n var x = 0\n var oc = 0\n for(i <- arr.length-1 to 0 by -1){\n if(arr(i)=='0'){\n if(oc==1){\n x+=1\n oc=0\n }\n else if(oc>1){\n oc = 1\n x+=1\n }\n }\n else{\n ones+=1\n oc+=1\n }\n }\n var ad = 2\n if(oc==1) ad=1\n println(math.min(x+ad,ones))\n}\n"}], "negative_code": [{"source_code": "object probE extends App{\n val arr = readLine()\n var ones = 0\n var x = 0\n var oc = 0\n for(i <- arr.length-1 to 0 by -1){\n if(arr(i)=='0'){\n if(oc==1){\n x+=1\n oc=0\n }\n else {\n oc = 1\n x+=1\n }\n }\n else{\n ones+=1\n oc+=1\n }\n }\n var ad = 2\n if(oc==1) ad=1\n println(math.min(x+ad,ones))\n}\n"}], "src_uid": "b2bc51df4a2c05c56c211e8f33fe1b45"} {"nl": {"description": "Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $$$n$$$ integers, now it's time to distribute them between his friends rationally...Lee has $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ in his backpack and he has $$$k$$$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $$$i$$$-th friend will get exactly $$$w_i$$$ integers and each integer will be handed over to exactly one friend.Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Next $$$3t$$$ lines contain test cases\u00a0\u2014 one per three lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$1 \\le k \\le n$$$)\u00a0\u2014 the number of integers Lee has and the number of Lee's friends. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$)\u00a0\u2014 the integers Lee has. The third line contains $$$k$$$ integers $$$w_1, w_2, \\ldots, w_k$$$ ($$$1 \\le w_i \\le n$$$; $$$w_1 + w_2 + \\ldots + w_k = n$$$)\u00a0\u2014 the number of integers Lee wants to give to each friend. It's guaranteed that the sum of $$$n$$$ over test cases is less than or equal to $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the maximum sum of happiness Lee can achieve.", "sample_inputs": ["3\n4 2\n1 13 7 17\n1 3\n6 2\n10 10 10 10 11 11\n3 3\n4 4\n1000000000 1000000000 1000000000 1000000000\n1 1 1 1"], "sample_outputs": ["48\n42\n8000000000"], "notes": "NoteIn the first test case, Lee should give the greatest integer to the first friend (his happiness will be $$$17 + 17$$$) and remaining integers to the second friend (his happiness will be $$$13 + 1$$$).In the second test case, Lee should give $$$\\{10, 10, 11\\}$$$ to the first friend and to the second friend, so the total happiness will be equal to $$$(11 + 10) + (11 + 10)$$$In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends."}, "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 k = Scanner.nextInt\n val as = new Array[Int](n)\n for (i <- 0 until n) {\n as(i) = Scanner.nextInt\n }\n val ass = as.sorted\n val ws = new Array[Int](k)\n for (i <- 0 until k) {\n ws(i) = Scanner.nextInt\n }\n val wss = ws.sorted\n var sum = 0L\n var cur = n - k\n for (i <- 0 until k) {\n sum += ass(n - i - 1) + (if (wss(i) == 1) ass(n - i - 1) else ass(cur - wss(i) + 1))\n cur -= wss(i) - 1\n }\n println(sum)\n }\n }\n}"}], "negative_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 k = Scanner.nextInt\n val as = new Array[Int](n)\n for (i <- 0 until n) {\n as(i) = Scanner.nextInt\n }\n val ass = as.sorted\n val ws = new Array[Int](k)\n for (i <- 0 until k) {\n ws(i) = Scanner.nextInt\n }\n val wss = ws.sorted\n var sum = 0L\n var cur = 0\n for (i <- wss) {\n sum += ass(n - cur - 1) + ass(n - cur - i)\n cur += i\n }\n println(sum)\n }\n }\n}"}], "src_uid": "9802646ecc8890bb046d5ec1a4262d70"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \\dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\\sum\\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \\dots 1} = [1], a_{2 \\dots 3} = [2, 0]$$$ and $$$a_{1 \\dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer \u2014 the number of good subarrays of the array $$$a$$$.", "sample_inputs": ["3\n3\n120\n5\n11011\n6\n600005"], "sample_outputs": ["3\n6\n1"], "notes": "NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \\dots 1}$$$, $$$a_{2 \\dots 2}$$$, $$$a_{1 \\dots 2}$$$, $$$a_{4 \\dots 4}$$$, $$$a_{5 \\dots 5}$$$ and $$$a_{4 \\dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \\dots 6}$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that: there wouldn't be a pair of any side-adjacent cards with zeroes in a row; there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.", "input_spec": "The first line contains two integers: n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of cards containing number 0; m (1\u2009\u2264\u2009m\u2009\u2264\u2009106) \u2014 the number of cards containing number 1.", "output_spec": "In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.", "sample_inputs": ["1 2", "4 8", "4 10", "1 5"], "sample_outputs": ["101", "110110110101", "11011011011011", "-1"], "notes": null}, "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.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"}, {"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"} {"nl": {"description": "ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of rows of seats in the bus. Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row. Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details. ", "output_spec": "If it is possible for Chris and ZS to sit at neighbouring empty seats, print \"YES\" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output). If there is no pair of seats for Chris and ZS, print \"NO\" (without quotes) in a single line. If there are multiple solutions, you may print any of them.", "sample_inputs": ["6\nOO|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX", "4\nXO|OX\nXO|XX\nOX|OX\nXX|OX", "5\nXX|XX\nXX|XX\nXO|OX\nXO|OO\nOX|XO"], "sample_outputs": ["YES\n++|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX", "NO", "YES\nXX|XX\nXX|XX\nXO|OX\nXO|++\nOX|XO"], "notes": "NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX"}, "positive_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 }\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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \\dots, a_{2n}$$$ ($$$1 \\le a_i \\le 2$$$) \u2014 $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the answer to it \u2014 the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.", "sample_inputs": ["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"], "sample_outputs": ["6\n0\n6\n2"], "notes": "NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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"} {"nl": {"description": "You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the number of points on the line. The second line contains n integers xi (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109) \u2014 the coordinates of the given n points.", "output_spec": "Print the only integer x \u2014 the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.", "sample_inputs": ["4\n1 2 3 4"], "sample_outputs": ["2"], "notes": null}, "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).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"}, {"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": "/**\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"}], "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"} {"nl": {"description": "A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \\gt a_{i-1}$$$ and $$$a_i \\gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ lines follow, each containing two space-separated integers $$$n$$$ ($$$1 \\leq n \\leq 100$$$) and $$$k$$$ ($$$0 \\leq k \\leq n$$$)\u00a0\u2014 the length of an array and the required number of peaks.", "output_spec": "Output $$$t$$$ lines. For each test case, if there is no permutation with given length and number of peaks, then print $$$-1$$$. Otherwise print a line containing $$$n$$$ space-separated integers which forms a permutation of numbers from $$$1$$$ to $$$n$$$ and contains exactly $$$k$$$ peaks. If there are multiple answers, print any.", "sample_inputs": ["5\n1 0\n5 2\n6 6\n2 1\n6 1"], "sample_outputs": ["1 \n2 4 1 5 3 \n-1\n-1\n1 3 6 5 4 2"], "notes": "NoteIn the second test case of the example, we have array $$$a = [2,4,1,5,3]$$$. Here, indices $$$i=2$$$ and $$$i=4$$$ are the peaks of the array. This is because $$$(a_{2} \\gt a_{1} $$$, $$$a_{2} \\gt a_{3})$$$ and $$$(a_{4} \\gt a_{3}$$$, $$$a_{4} \\gt a_{5})$$$. "}, "positive_code": [{"source_code": "object Pikes {\r\n import java.io.{BufferedReader, PrintStream}\r\n import scala.annotation.tailrec\r\n\r\n def solution(in: BufferedReader, out: PrintStream): Unit = {\r\n for (_ <- 1 to in.readLine().toInt) {\r\n val Array(n, k) = in.readLine().split(\" \").map(_.toInt)\r\n out.println((solve(n, k) match { case Seq() => Seq(-1) case s => s }) mkString(\" \"))\r\n }\r\n }\r\n\r\n def solve(n: Int, k: Int): Seq[Int] = if (n - 1 < 2 * k) Seq.empty else {\r\n @tailrec\r\n def go(x: Int, k: Int, l: List[Int]): List[Int] =\r\n if (x > n) l\r\n else {\r\n if (k > 0) go(x + 2, k - 1, x :: x + 1 :: l)\r\n else go(x + 1, k, x :: l)\r\n }\r\n go(2, k, 1 :: Nil)\r\n }\r\n\r\n def main(args: Array[String]): Unit = solution(Console.in, Console.out)\r\n}\r\n"}], "negative_code": [{"source_code": "\r\nobject Pikes {\r\n import java.io.{BufferedReader, PrintStream}\r\nimport scala.annotation.tailrec\r\n\r\n \r\n def solution(in: BufferedReader, out: PrintStream): Unit = {\r\n for (_ <- 1 to in.readLine().toInt) {\r\n val Array(n, k) = in.readLine().split(\" \").map(_.toInt)\r\n out.println((solve(n, k) match { case Seq() => Seq(-1) case s => s }) mkString(\" \"))\r\n }\r\n }\r\n\r\n def solve(n: Int, k: Int): Seq[Int] = if (n - 1 < 2 * k) Seq.empty else {\r\n @tailrec\r\n def go(x: Int, k: Int, l: List[Int]): List[Int] =\r\n if (x >= n) l\r\n else {\r\n if (k > 0) go(x + 2, k - 1, x :: x + 1 :: l)\r\n else go(x + 1, k, x + 1 :: l)\r\n }\r\n go(2, k, 1 :: Nil)\r\n }\r\n\r\n def main(args: Array[String]): Unit = solution(Console.in, Console.out)\r\n}\r\n"}, {"source_code": "object Pikes {\r\nimport java.io.{BufferedReader, PrintStream}\r\nimport scala.annotation.tailrec\r\n\r\n \r\n def solution(in: BufferedReader, out: PrintStream): Unit = {\r\n for (_ <- 1 to in.readLine().toInt) {\r\n val Array(n, k) = in.readLine().split(\" \").map(_.toInt)\r\n out.println(solve(n, k).mkString(\" \"))\r\n }\r\n }\r\n\r\n def solve(n: Int, k: Int): Seq[Int] = if (n - 1 < 2 * k) Seq.empty else {\r\n @tailrec\r\n def go(x: Int, k: Int, l: List[Int]): List[Int] =\r\n if (x >= n) l\r\n else {\r\n if (k > 0) go(x + 2, k - 1, x :: x + 1 :: l)\r\n else go(x + 1, k, x + 1 :: l)\r\n }\r\n go(2, k, 1 :: Nil)\r\n }\r\n\r\n def main(args: Array[String]): Unit = solution(Console.in, Console.out)\r\n}"}], "src_uid": "b4bb11ea4650ead54026453ea9a76f39"} {"nl": {"description": "For the multiset of positive integers $$$s=\\{s_1,s_2,\\dots,s_k\\}$$$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $$$s$$$ as follow: $$$\\gcd(s)$$$ is the maximum positive integer $$$x$$$, such that all integers in $$$s$$$ are divisible on $$$x$$$. $$$\\textrm{lcm}(s)$$$ is the minimum positive integer $$$x$$$, that divisible on all integers from $$$s$$$.For example, $$$\\gcd(\\{8,12\\})=4,\\gcd(\\{12,18,6\\})=6$$$ and $$$\\textrm{lcm}(\\{4,6\\})=12$$$. Note that for any positive integer $$$x$$$, $$$\\gcd(\\{x\\})=\\textrm{lcm}(\\{x\\})=x$$$.Orac has a sequence $$$a$$$ with length $$$n$$$. He come up with the multiset $$$t=\\{\\textrm{lcm}(\\{a_i,a_j\\})\\ |\\ i<j\\}$$$, and asked you to find the value of $$$\\gcd(t)$$$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.", "input_spec": "The first line contains one integer $$$n\\ (2\\le n\\le 100\\,000)$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 200\\,000$$$).", "output_spec": "Print one integer: $$$\\gcd(\\{\\textrm{lcm}(\\{a_i,a_j\\})\\ |\\ i<j\\})$$$.", "sample_inputs": ["2\n1 1", "4\n10 24 40 80", "10\n540 648 810 648 720 540 594 864 972 648"], "sample_outputs": ["1", "40", "54"], "notes": "NoteFor the first example, $$$t=\\{\\textrm{lcm}(\\{1,1\\})\\}=\\{1\\}$$$, so $$$\\gcd(t)=1$$$.For the second example, $$$t=\\{120,40,80,120,240,80\\}$$$, and it's not hard to see that $$$\\gcd(t)=40$$$."}, "positive_code": [{"source_code": "/**\n * C. Orac and LCM\n * https://codeforces.com/contest/1350/problem/C\n *\n * https://codeforces.com/blog/entry/77284?#comment-620958\n * https://codeforces.com/blog/entry/77284?#comment-621269\n * https://codeforces.com/contest/1349/submission/79820899\n */\nobject C extends App {\n\n private def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)\n\n private def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n\n val n = scala.io.StdIn.readInt()\n val an = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n // gcd of { lcm(a1, a2), ..., lcm(a1, an), ..., lcm(ai, ai+1), ..., lcm(ai, an), ..., lcm(an-1, an) } =\n // gcd of { gcd of { lcm(a1, a2), lcm(a1, a3), ..., lcm(a1, an) }, ..., gcd of { lcm(ai, ai+1), lcm(ai, ai+2), ..., lcm(ai, an) }, ... }\n val ans = an.indices\n .foldLeft((0L, 0L)) {\n case ((ans, g), i) =>\n // gcd of { lcm(ai, ai+1), lcm(ai, ai+2), ..., lcm(ai, an) } =\n // lcm of { ai, gcd of { ai+1, ai+2, ..., an } }\n (gcd(ans, lcm(an(i), g)), gcd(g, an(i)))\n }\n ._1\n\n println(ans)\n}\n"}], "negative_code": [], "src_uid": "3634a3367a1f05d1b3e8e4369e8427fb"} {"nl": {"description": "Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number \u2014 the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers \u2014 they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.", "output_spec": "Print the single number \u2014 the number of amazing performances the coder has had during his whole history of participating in the contests.", "sample_inputs": ["5\n100 50 200 150 200", "10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing."}, "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 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"}, {"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"} {"nl": {"description": "Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1\u2009\u2264\u2009i\u2009\u2264\u2009n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i\u2009-\u20091 if i\u2009>\u20091 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i\u2009=\u2009n, the cursor appears at the beginning of the string).When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.Initially, the text cursor is at position p. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?", "input_spec": "The first line contains two space-separated integers n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) and p (1\u2009\u2264\u2009p\u2009\u2264\u2009n), the length of Nam's string and the initial position of the text cursor. The next line contains n lowercase characters of Nam's string.", "output_spec": "Print the minimum number of presses needed to change string into a palindrome.", "sample_inputs": ["8 3\naeabcaez"], "sample_outputs": ["6"], "notes": "NoteA string is a palindrome if it reads the same forward or reversed.In the sample test, initial Nam's string is: (cursor position is shown bold).In optimal solution, Nam may do 6 following steps:The result, , is now a palindrome."}, "positive_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 - 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}"}, {"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"} {"nl": {"description": "It is a holiday season, and Koala is decorating his house with cool lights! He owns $$$n$$$ lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $$$a_i$$$ and $$$b_i$$$. Light with parameters $$$a_i$$$ and $$$b_i$$$ will toggle (on to off, or off to on) every $$$a_i$$$ seconds starting from the $$$b_i$$$-th second. In other words, it will toggle at the moments $$$b_i$$$, $$$b_i + a_i$$$, $$$b_i + 2 \\cdot a_i$$$ and so on.You know for each light whether it's initially on or off and its corresponding parameters $$$a_i$$$ and $$$b_i$$$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. Here is a graphic for the first example. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$), the number of lights. The next line contains a string $$$s$$$ of $$$n$$$ characters. The $$$i$$$-th character is \"1\", if the $$$i$$$-th lamp is initially on. Otherwise, $$$i$$$-th character is \"0\". The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le 5$$$) \u00a0\u2014 the parameters of the $$$i$$$-th light.", "output_spec": "Print a single integer\u00a0\u2014 the maximum number of lights that will ever be on at the same time.", "sample_inputs": ["3\n101\n3 3\n3 2\n3 1", "4\n1111\n3 4\n5 2\n3 1\n3 2", "6\n011100\n5 3\n5 5\n2 4\n3 5\n4 2\n1 5"], "sample_outputs": ["2", "4", "6"], "notes": "NoteFor first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $$$2$$$ (e.g. at the moment $$$2$$$).In the second example, all lights are initially on. So the answer is $$$4$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val light = ns(N).map(_ == '1')\n val (a, b) = na2(N)\n var ans = light.count(identity)\n val MAX = if(oj) 1e5.toInt else 1000\n REP(MAX, 1) { i =>\n var cnt = 0\n REP(N) { j =>\n if (i - b(j) >= 0 && (i - b(j)) % a(j) == 0) {\n light(j) ^= true\n }\n if (light(j)) cnt += 1\n }\n debug(light)\n ans = max(ans, cnt)\n }\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "2ff789ae0095bb7ff0e747b0d4df59bc"} {"nl": {"description": "This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number\u00a0\u2014 an integer from interval [2,\u2009100]. Your task is to say if the hidden number is prime or composite.Integer x\u2009>\u20091 is called prime if it has exactly two distinct divisors, 1 and x. If integer x\u2009>\u20091 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2,\u2009100]. The system will answer \"yes\" if your integer is a divisor of the hidden number. Otherwise, the answer will be \"no\".For example, if the hidden number is 14 then the system will answer \"yes\" only if you print 2, 7 or 14.When you are done asking queries, print \"prime\" or \"composite\" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2,\u2009100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).", "input_spec": "After each query you should read one string from the input. It will be \"yes\" if the printed integer is a divisor of the hidden number, and \"no\" otherwise.", "output_spec": "Up to 20 times you can ask a query\u00a0\u2014 print an integer from interval [2,\u2009100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer \"prime\" or \"composite\" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. Hacking. To hack someone, as the input you should print the hidden number\u00a0\u2014 one integer from the interval [2,\u2009100]. Of course, his/her solution won't be able to read the hidden number from the input.", "sample_inputs": ["yes\nno\nyes", "no\nyes\nno\nno\nno"], "sample_outputs": ["2\n80\n5\ncomposite", "58\n59\n78\n78\n2\nprime"], "notes": "NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2,\u2009100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries)."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "8cf479fd47050ba96d21f3d8eb43c8f0"} {"nl": {"description": "Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n\u2009\u00d7\u2009n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.", "output_spec": "Print \"YES\" or \"NO\" (without the quotes) depending on the answer to the problem.", "sample_inputs": ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"], "sample_outputs": ["YES", "NO"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Egor has a table of size $$$n \\times m$$$, with lines numbered from $$$1$$$ to $$$n$$$ and columns numbered from $$$1$$$ to $$$m$$$. Each cell has a color that can be presented as an integer from $$$1$$$ to $$$10^5$$$.Let us denote the cell that lies in the intersection of the $$$r$$$-th row and the $$$c$$$-th column as $$$(r, c)$$$. We define the manhattan distance between two cells $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table $$$3 \\times 4$$$ the manhattan distance between $$$(1, 2)$$$ and $$$(3, 3)$$$ is $$$3$$$, one of the shortest paths is the following: $$$(1, 2) \\to (2, 2) \\to (2, 3) \\to (3, 3)$$$. Egor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n \\le m$$$, $$$n \\cdot m \\leq 100\\,000$$$)\u00a0\u2014 number of rows and columns in the table. Each of next $$$n$$$ lines describes a row of the table. The $$$i$$$-th line contains $$$m$$$ integers $$$c_{i1}, c_{i2}, \\ldots, c_{im}$$$ ($$$1 \\le c_{ij} \\le 100\\,000$$$)\u00a0\u2014 colors of cells in the $$$i$$$-th row.", "output_spec": "Print one integer\u00a0\u2014 the the sum of manhattan distances between each pair of cells of the same color.", "sample_inputs": ["2 3\n1 2 3\n3 2 1", "3 4\n1 1 2 2\n2 1 1 2\n2 2 1 1", "4 4\n1 1 2 3\n2 1 1 2\n3 1 2 1\n1 1 2 1"], "sample_outputs": ["7", "76", "129"], "notes": "NoteIn the first sample there are three pairs of cells of same color: in cells $$$(1, 1)$$$ and $$$(2, 3)$$$, in cells $$$(1, 2)$$$ and $$$(2, 2)$$$, in cells $$$(1, 3)$$$ and $$$(2, 1)$$$. The manhattan distances between them are $$$3$$$, $$$1$$$ and $$$3$$$, the sum is $$$7$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n // Qc\n def f(row: Int, col: Int) = {\n\n def sumOf(se: Seq[(Int, (Int, Int))]): Long = {\n val (xs, ys) = se.foldLeft((List.empty[Long], List.empty[Long]))(\n (acc, elem) => {\n val (xl, yl) = acc\n (elem._2._1 :: xl, elem._2._2 :: yl)\n }\n )\n\n val sxs = xs.sorted.toArray\n val sys = ys.sorted.toArray\n val len = se.length\n\n val prefx = sxs.foldLeft(List.empty[Long], 0)(\n (acc, elem) => {\n val (arr, idx) = acc\n val x = if (idx == 0) elem else elem + arr.head\n (x :: arr, idx + 1)\n }\n )._1\n\n val prefy = sys.foldLeft(List.empty[Long], 0)(\n (acc, elem) => {\n val (arr, idx) = acc\n val y = if (idx == 0) elem else elem + arr.head\n (y :: arr, idx + 1)\n }\n )._1\n\n val maxx = prefx.head\n val maxy = prefy.head\n\n prefx.tail.foldLeft(0L, len - 2)(\n (acc, elem) => (acc._1 + (maxx - elem) - (len - acc._2 - 1) * sxs(acc._2), acc._2 - 1)\n )._1 +\n prefy.tail.foldLeft(0L, len - 2)(\n (acc, elem) => (acc._1 + (maxy - elem) - (len - acc._2 - 1) * sys(acc._2), acc._2 - 1)\n )._1\n }\n\n val g = (\n for (\n i <- 0 until row;\n arr = readLine().split(\"\\\\s+\").map(_.toInt)\n ) yield arr\n )\n\n val m = for (\n i <- 0 until row;\n j <- 0 until col\n ) yield (g(i)(j) -> (i, j))\n\n val colors = m.groupBy(_._1).values\n colors.foldLeft(0L)(\n (acc, elem) => acc + sumOf(elem)\n )\n }\n\n def main(args: Array[String]): Unit = {\n val tup = readLine.split(\"\\\\s+\")\n val row = tup(0).toInt\n val col = tup(1).toInt\n println(f(row, col))\n\n }\n\n}\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n // Qc\n def f(row: Int, col: Int) = {\n\n def sumOf(se: Seq[(Long, (Int, Int))]): Long = {\n val (xs, ys) = se.foldLeft((List.empty[Int], List.empty[Int]))(\n (acc, elem) => {\n val (xl, yl) = acc\n (elem._2._1 :: xl, elem._2._2 :: yl)\n }\n )\n\n val sxs = xs.sorted.toArray\n val sys = ys.sorted.toArray\n val len = se.length\n\n val prefx = sxs.foldLeft(List.empty[Int], 0)(\n (acc, elem) => {\n val (arr, idx) = acc\n val x = if (idx == 0) elem else elem + arr.head\n (x :: arr, idx + 1)\n }\n )._1\n\n val prefy = sys.foldLeft(List.empty[Int], 0)(\n (acc, elem) => {\n val (arr, idx) = acc\n val y = if (idx == 0) elem else elem + arr.head\n (y :: arr, idx + 1)\n }\n )._1\n\n val maxx = prefx.head\n val maxy = prefy.head\n\n prefx.tail.foldLeft(0L, len - 2)(\n (acc, elem) => (acc._1 + (maxx - elem) - (len - acc._2 - 1) * sxs(acc._2), acc._2 - 1)\n )._1 +\n prefy.tail.foldLeft(0L, len - 2)(\n (acc, elem) => (acc._1 + (maxy - elem) - (len - acc._2 - 1) * sys(acc._2), acc._2 - 1)\n )._1\n }\n\n val g = (\n for (\n i <- 0 until row;\n arr = readLine().split(\"\\\\s+\").map(_.toLong)\n ) yield arr\n )\n\n val m = for (\n i <- 0 until row;\n j <- 0 until col\n ) yield (g(i)(j) -> (i, j))\n\n val colors = m.groupBy(_._1).values\n colors.foldLeft(0L)(\n (acc, elem) => acc + sumOf(elem)\n )\n }\n\n def main(args: Array[String]): Unit = {\n val tup = readLine.split(\"\\\\s+\")\n val row = tup(0).toInt\n val col = tup(1).toInt\n println(f(row, col))\n\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n // Qc\n def f(row: Int, col: Int) = {\n\n def sumOf(se: Seq[(Int, (Int, Int))]): Long = {\n val (xs, ys) = se.foldLeft((List.empty[Int], List.empty[Int]))(\n (acc, elem) => {\n val (xl, yl) = acc\n (elem._2._1 :: xl, elem._2._2 :: yl)\n }\n )\n val sxs = xs.sorted.toArray\n val sys = ys.sorted.toArray\n val len = se.length\n\n val prefx = sxs.foldLeft(List.empty[Int], 0)(\n (acc, elem) => {\n val (arr, idx) = acc\n val x = if (idx == 0) elem else elem + arr.head\n (x :: arr, idx + 1)\n }\n )._1\n\n val prefy = sys.foldLeft(List.empty[Int], 0)(\n (acc, elem) => {\n val (arr, idx) = acc\n val y = if (idx == 0) elem else elem + arr.head\n (y :: arr, idx + 1)\n }\n )._1\n\n val maxx = prefx.head\n val maxy = prefy.head\n\n prefx.tail.foldLeft(0L, len - 2)(\n (acc, elem) => (acc._1 + (maxx - elem) - (len - acc._2 - 1) * sxs(acc._2), acc._2 - 1)\n )._1 +\n prefy.tail.foldLeft(0L, len - 2)(\n (acc, elem) => (acc._1 + (maxy - elem) - (len - acc._2 - 1) * sys(acc._2), acc._2 - 1)\n )._1\n // (0 until len).foldLeft(0)((acc, elem) => acc + (elem until len).foldLeft(0)((a, e) => a + dist(lst(elem)._2, lst(e)._2)))\n }\n\n def dist(l: (Int, Int), r: (Int, Int)) = {\n Math.abs(l._1 - r._1) + Math.abs(l._2 - r._2)\n }\n\n val g = (\n for (\n i <- 0 until row;\n arr = readLine().split(\"\\\\s+\").map(_.toInt)\n ) yield arr\n )\n\n val m = for (\n i <- 0 until row;\n j <- 0 until col\n ) yield (g(i)(j) -> (i, j))\n\n val colors = m.groupBy(_._1).values\n colors.foldLeft(0L)(\n (acc, elem) => acc + sumOf(elem)\n )\n }\n\n def main(args: Array[String]): Unit = {\n val tup = readLine.split(\"\\\\s+\")\n val row = tup(0).toInt\n val col = tup(1).toInt\n println(f(row, col))\n\n }\n\n}\n"}], "src_uid": "ef0ad7b228351a268c3f6bfac68b1002"} {"nl": {"description": "One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a\u2009-\u2009b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20092000) \u2014 the number of people and the maximal capacity of the elevator. The next line contains n integers: f1,\u2009f2,\u2009...,\u2009fn (2\u2009\u2264\u2009fi\u2009\u2264\u20092000), where fi denotes the target floor of the i-th person.", "output_spec": "Output a single integer \u2014 the minimal time needed to achieve the goal.", "sample_inputs": ["3 2\n2 3 4", "4 2\n50 100 50 100", "10 3\n2 2 2 2 2 2 2 2 2 2"], "sample_outputs": ["8", "296", "8"], "notes": "NoteIn first sample, an optimal solution is: The elevator takes up person #1 and person #2. It goes to the 2nd floor. Both people go out of the elevator. The elevator goes back to the 1st floor. Then the elevator takes up person #3. And it goes to the 2nd floor. It picks up person #2. Then it goes to the 3rd floor. Person #2 goes out. Then it goes to the 4th floor, where person #3 goes out. The elevator goes back to the 1st floor. "}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.Consider two infinite sets of numbers. The first set consists of odd positive numbers ($$$1, 3, 5, 7, \\ldots$$$), and the second set consists of even positive numbers ($$$2, 4, 6, 8, \\ldots$$$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage\u00a0\u2014 the first two numbers from the second set, on the third stage\u00a0\u2014 the next four numbers from the first set, on the fourth\u00a0\u2014 the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: $$$1, 2, 4, 3, 5, 7, 9, 6, 8, 10$$$. Let's number the numbers written, starting with one.The task is to find the sum of numbers with numbers from $$$l$$$ to $$$r$$$ for given integers $$$l$$$ and $$$r$$$. The answer may be big, so you need to find the remainder of the division by $$$1000000007$$$ ($$$10^9+7$$$).Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.", "input_spec": "The first line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\leq l \\leq r \\leq 10^{18}$$$)\u00a0\u2014 the range in which you need to find the sum.", "output_spec": "Print a single integer\u00a0\u2014 the answer modulo $$$1000000007$$$ ($$$10^9+7$$$).", "sample_inputs": ["1 3", "5 14", "88005553535 99999999999"], "sample_outputs": ["7", "105", "761141116"], "notes": "NoteIn the first example, the answer is the sum of the first three numbers written out ($$$1 + 2 + 4 = 7$$$).In the second example, the numbers with numbers from $$$5$$$ to $$$14$$$: $$$5, 7, 9, 6, 8, 10, 12, 14, 16, 18$$$. Their sum is $$$105$$$."}, "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.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 L, R = nl()\n\n def sum(k: Int): Long = {\n if (k < 0) 0\n else {\n (sum(k - 2) + (1L << k)) % MOD\n }\n }\n\n def cnt(x: Long): Long = {\n val k = log2(x)\n\n val cnt = sum(k - 2) + x - (1L << k) + 1\n debug(s\"x:$x k:$k cnt:$cnt\")\n // \u5076\u6570\n if ((k&1) == 1) {\n val a1 = BigInt(cnt) * BigInt(cnt + 1)\n val cnt2 = sum(k - 1)\n\n val a2 = BigInt(cnt2) * BigInt(cnt2 + 1) - cnt2\n debug(s\"cnt2:$cnt2 a1:$a1 a2:$a2\")\n val ans = (a1 + a2) % MOD\n ans.longValue()\n\n // \u5947\u6570\n } else {\n val a1 = BigInt(cnt) * BigInt(cnt + 1) - cnt\n val cnt2 = sum(k - 1)\n\n val a2 = BigInt(cnt2) * BigInt(cnt2 + 1)\n debug(s\"cnt2:$cnt2 a1:$a1 a2:$a2\")\n val ans = (a1 + a2) % MOD\n ans.longValue()\n }\n }\n\n val ans = (MOD + cnt(R) - (if (L == 1) 0 else cnt(L - 1))) % MOD\n out.println(ans)\n }\n\n\n\n def log2(x: Long): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\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 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[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": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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 L, R = nl()\n\n def sum(k: Int): Long = {\n if (k < 0) 0\n else {\n (sum(k - 2) + (1L << k)) % MOD\n }\n }\n\n def cnt(x: Long): Long = {\n val k = log2(x)\n\n val cnt = sum(k - 2) + x - (1L << k) + 1\n debug(s\"x:$x k:$k cnt:$cnt\")\n // \u5076\u6570\n if ((k&1) == 1) {\n val a1 = BigInt(cnt) * BigInt(cnt + 1)\n val cnt2 = sum(k - 1)\n\n val a2 = BigInt(cnt2) * BigInt(cnt2 + 1) - cnt2\n debug(s\"cnt2:$cnt2 a1:$a1 a2:$a2\")\n val ans = (a1 + a2) % MOD\n ans.longValue()\n\n // \u5947\u6570\n } else {\n val a1 = BigInt(cnt) * BigInt(cnt + 1) - cnt\n val cnt2 = sum(k - 1)\n\n val a2 = BigInt(cnt2) * BigInt(cnt2 + 1)\n debug(s\"cnt2:$cnt2 a1:$a1 a2:$a2\")\n val ans = (a1 + a2) % MOD\n ans.longValue()\n }\n }\n\n val ans = cnt(R) - (if (L == 1) 0 else cnt(L - 1))\n out.println(ans)\n }\n\n\n\n def log2(x: Long): Int = {\n assert(x > 0)\n var a = x\n var i = 0 // \u4f55\u56de2\u3067\u5272\u3063\u305f\u30891\u306b\u306a\u308b\u304b\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 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[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}"}], "src_uid": "40a5e4b4193901cb3004dac24dba1d62"} {"nl": {"description": "The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u2014 the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 50$$$, $$$0 \\le m \\le n$$$, $$$2 \\le k \\le n$$$, $$$k$$$ is a divisors of $$$n$$$).", "output_spec": "For each test case, print one integer \u2014 the maximum number of points a player can get for winning the game.", "sample_inputs": ["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"], "sample_outputs": ["3\n0\n1\n0"], "notes": "NoteTest cases of the example are described in the statement."}, "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 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"}, {"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"} {"nl": {"description": "Tanya has $$$n$$$ candies numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th candy has the weight $$$a_i$$$.She plans to eat exactly $$$n-1$$$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies $$$i$$$ (let's call these candies good) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, $$$n=4$$$ and weights are $$$[1, 4, 3, 3]$$$. Consider all possible cases to give a candy to dad: Tanya gives the $$$1$$$-st candy to dad ($$$a_1=1$$$), the remaining candies are $$$[4, 3, 3]$$$. She will eat $$$a_2=4$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$4+3=7$$$ and in even days she will eat $$$3$$$. Since $$$7 \\ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good). Tanya gives the $$$2$$$-nd candy to dad ($$$a_2=4$$$), the remaining candies are $$$[1, 3, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$3$$$. Since $$$4 \\ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good). Tanya gives the $$$3$$$-rd candy to dad ($$$a_3=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). Tanya gives the $$$4$$$-th candy to dad ($$$a_4=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_3=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). In total there $$$2$$$ cases which should counted (these candies are good), so the answer is $$$2$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of candies. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^4$$$), where $$$a_i$$$ is the weight of the $$$i$$$-th candy.", "output_spec": "Print one integer \u2014 the number of such candies $$$i$$$ (good candies) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.", "sample_inputs": ["7\n5 5 4 5 5 5 6", "8\n4 8 8 7 8 4 4 5", "9\n2 3 4 2 2 3 2 2 4"], "sample_outputs": ["2", "2", "3"], "notes": "NoteIn the first example indices of good candies are $$$[1, 2]$$$.In the second example indices of good candies are $$$[2, 3]$$$.In the third example indices of good candies are $$$[4, 5, 9]$$$."}, "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 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"}, {"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"} {"nl": {"description": "Vanya decided to walk in the field of size n\u2009\u00d7\u2009n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi,\u2009yi). Vanya moves towards vector (dx,\u2009dy). That means that if Vanya is now at the cell (x,\u2009y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.", "input_spec": "The first line contains integers n,\u2009m,\u2009dx,\u2009dy(1\u2009\u2264\u2009n\u2009\u2264\u2009106, 1\u2009\u2264\u2009m\u2009\u2264\u2009105, 1\u2009\u2264\u2009dx,\u2009dy\u2009\u2264\u2009n) \u2014 the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi,\u2009yi (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n\u2009-\u20091) \u2014 the coordinates of apples. One cell may contain multiple apple trees.", "output_spec": "Print two space-separated numbers \u2014 the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.", "sample_inputs": ["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"], "sample_outputs": ["1 3", "0 0"], "notes": "NoteIn the first sample Vanya's path will look like: (1,\u20093)\u2009-\u2009(3,\u20091)\u2009-\u2009(0,\u20094)\u2009-\u2009(2,\u20092)\u2009-\u2009(4,\u20090)\u2009-\u2009(1,\u20093)In the second sample: (0,\u20090)\u2009-\u2009(1,\u20091)\u2009-\u2009(0,\u20090)"}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "6a2fe1f7e767a508530e9d922740c450"} {"nl": {"description": "Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k\u2009=\u20095 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1,\u2009a2,\u2009...,\u2009an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule\u00a0\u2014 the sequence of integers b1,\u2009b2,\u2009...,\u2009bn (bi\u2009\u2265\u2009ai), where bi means the total number of walks with the dog on the i-th day.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009500)\u00a0\u2014 the number of days and the minimum number of walks with Cormen for any two consecutive days. The second line contains integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009500)\u00a0\u2014 the number of walks with Cormen on the i-th day which Polycarp has already planned. ", "output_spec": "In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days. In the second line print n integers b1,\u2009b2,\u2009...,\u2009bn, where bi\u00a0\u2014 the total number of walks on the i-th day according to the found solutions (ai\u2009\u2264\u2009bi for all i from 1 to n). If there are multiple solutions, print any of them. ", "sample_inputs": ["3 5\n2 0 1", "3 1\n0 0 0", "4 6\n2 4 3 5"], "sample_outputs": ["4\n2 3 2", "1\n0 1 0", "0\n2 4 3 5"], "notes": null}, "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 {\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}"}, {"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"} {"nl": {"description": "Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k\u2009+\u20091)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t\u2009-\u20091 gestures (if the icon is on the screen t), and then make another gesture \u2014 press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.", "input_spec": "The first line of the input contains three numbers n,\u2009m,\u2009k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u2009105)\u00a0\u2014\u00a0the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1,\u2009a2,\u2009...,\u2009an\u00a0\u2014\u00a0the initial order of icons from left to right in the menu (from the first to the last one), ai\u00a0\u2014\u00a0 is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1,\u2009b2,\u2009...,\u2009bm(1\u2009\u2264\u2009bi\u2009\u2264\u2009n)\u00a0\u2014\u00a0the ids of the launched applications in the planned order. One application may be launched multiple times.", "output_spec": "Print a single number \u2014 the number of gestures that Anya needs to make to launch all the applications in the desired order.", "sample_inputs": ["8 3 3\n1 2 3 4 5 6 7 8\n7 8 1", "5 4 2\n3 1 5 2 4\n4 4 4 4"], "sample_outputs": ["7", "8"], "notes": "NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1,\u20092,\u20093, the second screen contains icons 4,\u20095,\u20096, the third screen contains icons 7,\u20098. After application 7 is launched, we get the new arrangement of the icons\u00a0\u2014\u00a0(123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures."}, "positive_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(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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Vasya has an array $$$a_1, a_2, \\dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \\le t_i \\le 1, 1 \\le l_i < r_i \\le n$$$) and it means: if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \\dots, a_{r_i}$$$ is sorted in non-decreasing order; if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \\dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 1000, 1 \\le m \\le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \\le t_i \\le 1, 1 \\le l_i < r_i \\le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \\dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \\dots , a_{r_i}$$$ is not sorted.", "output_spec": "If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them.", "sample_inputs": ["7 4\n1 1 3\n1 2 5\n0 5 6\n1 6 7", "4 2\n1 1 4\n0 2 3"], "sample_outputs": ["YES\n1 2 2 3 5 4 4", "NO"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"}, {"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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "Let's call a sequence of integers $$$x_1, x_2, \\dots, x_k$$$ MEX-correct if for all $$$i$$$ ($$$1 \\le i \\le k$$$) $$$|x_i - \\operatorname{MEX}(x_1, x_2, \\dots, x_i)| \\le 1$$$ holds. Where $$$\\operatorname{MEX}(x_1, \\dots, x_k)$$$ is the minimum non-negative integer that doesn't belong to the set $$$x_1, \\dots, x_k$$$. For example, $$$\\operatorname{MEX}(1, 0, 1, 3) = 2$$$ and $$$\\operatorname{MEX}(2, 1, 5) = 0$$$.You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo $$$998244353$$$. Note: a subsequence of an array $$$a$$$ is a sequence $$$[a_{i_1}, a_{i_2}, \\dots, a_{i_m}]$$$ meeting the constraints $$$1 \\le i_1 < i_2 < \\dots < i_m \\le n$$$. If two different ways to choose the sequence of indices $$$[i_1, i_2, \\dots, i_m]$$$ yield the same subsequence, the resulting subsequence should be counted twice (i.\u2009e. two subsequences are different if their sequences of indices $$$[i_1, i_2, \\dots, i_m]$$$ are not the same).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 5 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$5 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the number of non-empty MEX-correct subsequences of a given array, taken modulo $$$998244353$$$.", "sample_inputs": ["4\n3\n0 2 1\n2\n1 0\n5\n0 0 0 0 0\n4\n0 1 2 3"], "sample_outputs": ["4\n2\n31\n7"], "notes": "NoteIn the first example, the valid subsequences are $$$[0]$$$, $$$[1]$$$, $$$[0,1]$$$ and $$$[0,2]$$$.In the second example, the valid subsequences are $$$[0]$$$ and $$$[1]$$$.In the third example, any non-empty subsequence is valid. "}, "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 val d0 = new Array[Long](n+3)\n val d1 = new Array[Long](n+3)\n var ans = 0L\n for (i <- 1 to n) {\n val a = readInt()\n if (a > 0)\n d1(a-1) = (d1(a-1)*2L+d0(a-1))%rem\n d0(a+1) = (d0(a+1)*2L+d0(a))%rem\n d1(a+1) = (d1(a+1)*2L)%rem\n if (a == 0)\n d0(1) = (d0(1)+1L) % rem\n if (a == 1)\n d1(0) = (d1(0)+1L) % rem\n }\n for (i <- 0 to n+1) {\n ans = (ans + d0(i) + d1(i)) % rem\n }\n writer.println(ans)\n /*\n for (i <- 0 to n+1)\n writer.print(d0(i) + \" \")\n writer.println()\n for (i <- 0 to n+1)\n writer.print(d1(i) + \" \")\n writer.println()\n\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": [{"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 val d0 = new Array[Long](n+3)\n val d1 = new Array[Long](n+3)\n var ans = 0L\n for (i <- 1 to n) {\n val a = readInt()\n ans += d0(a) + d0(a+1) + d1(a+1)\n if (a > 0)\n ans += d0(a-1) + d1(a-1)\n if (a == 0 || a == 1)\n ans += 1\n ans %= rem\n if (a > 0)\n d1(a-1) = (d1(a-1)*2L+d0(a-1))%rem\n d0(a+1) = (d0(a+1)*2L+d0(a))%rem\n d0(a+2) = (d0(a+2)+d1(a))%rem\n d1(a+1) = (d1(a+1)*2L)%rem\n if (a == 0)\n d0(1) = (d0(1)+1L) % rem\n if (a == 1)\n d1(0) = (d1(0)+1L) % rem\n }\n writer.println(ans)\n /*\n for (i <- 0 to n+1)\n writer.print(d0(i) + \" \")\n writer.println()\n for (i <- 0 to n+1)\n writer.print(d1(i) + \" \")\n writer.println()\n\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}"}, {"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 val d0 = new Array[Long](n+3)\n val d1 = new Array[Long](n+3)\n var ans = 0L\n for (i <- 1 to n) {\n val a = readInt()\n ans += d0(a) + d0(a+1) + d1(a+1)\n if (a > 0)\n ans += d0(a-1) + d1(a-1)\n if (a == 0 || a == 1)\n ans += 1\n ans %= rem\n if (a > 0)\n d1(a-1) = (d1(a-1)*2L+d0(a-1))%rem\n d0(a+1) = (d0(a+1)*2L+d0(a))%rem\n d0(a+2) = (d0(a+2)+d1(a))%rem\n d1(a+1) = (d1(a+1)*2L)%rem\n if (a == 0)\n d0(1) = (d0(1)+1L) % rem\n if (a == 1)\n d1(0) = (d1(0)+1L) % rem\n }\n writer.println(ans)\n for (i <- 0 to n+1)\n writer.print(d0(i) + \" \")\n writer.println()\n for (i <- 0 to n+1)\n writer.print(d1(i) + \" \")\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}"}, {"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 = 998244353\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 d0 = new Array[Long](n+2)\n val d1 = new Array[Long](n+2)\n var ans = 0L\n for (i <- 1 to n) {\n val a = readInt()\n ans += d0(a) + d0(a+1) + d1(a+1)\n if (a > 0)\n ans += d0(a-1) + d1(a-1)\n if (a == 0 || a == 1)\n ans += 1\n ans %= rem\n if (a > 0)\n d1(a-1) = (d1(a-1)*2L+d0(a-1))%rem\n d0(a+1) = (d0(a+1)*2L+d0(a))%rem\n d1(a+1) = (d1(a+1)*2L+d1(a))%rem\n if (a == 0)\n d0(1) = (d0(1)+1L) % rem\n if (a == 1)\n d1(0) = (d1(0)+1L) % rem\n }\n writer.println(ans)\n //for (i <- 0 to n+1)\n // writer.print(d0(i) + \" \")\n //writer.println()\n //for (i <- 0 to n+1)\n // writer.print(d1(i) + \" \")\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}"}], "src_uid": "5b40c60ba54c7bb9a649b15588ef6510"} {"nl": {"description": "Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109\u2009+\u20097. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 0\u2009\u2264\u2009k\u2009\u2264\u2009min(20,\u2009n\u2009-\u20091))\u00a0\u2014 the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k. Each of the next n\u2009-\u20091 lines contain two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n)\u00a0\u2014 indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.", "output_spec": "Print one integer\u00a0\u2014 the remainder of division of the number of ways to paint the tree by 1\u2009000\u2009000\u2009007 (109\u2009+\u20097).", "sample_inputs": ["2 0\n1 2", "2 1\n1 2", "4 1\n1 2\n2 3\n3 4", "7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7"], "sample_outputs": ["1", "3", "9", "91"], "notes": "NoteIn the first sample, Ostap has to paint both vertices black.In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.In the third sample, the valid ways to paint vertices are: {1,\u20093}, {1,\u20094}, {2,\u20093}, {2,\u20094}, {1,\u20092,\u20093}, {1,\u20092,\u20094}, {1,\u20093,\u20094}, {2,\u20093,\u20094}, {1,\u20092,\u20093,\u20094}."}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n val MOD = 1000000007\n def readInts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n\n def mergePattern(p1: Map[Int, Long], p2: Map[Int, Long]): Map[Int, Long] = {\n val ans = mutable.HashMap.empty[Int, Long]\n for {\n (a1, b1) <- p1\n (a2, b2) <- p2\n } {\n val (a, b) =\n if (a1 + a2 > 0) (Math.max(a1, a2), b1 * b2 % MOD)\n else (Math.min(a1, a2), b1 * b2 % MOD)\n ans.put(a, (ans.getOrElse(a, 0L) + b) % MOD)\n }\n ans.toMap\n }\n\n val emptyLiftedPattern = Map(0 -> 1L, k+1 -> 1L)\n\n case class Tree(children: Seq[Tree]) {\n val pattern: Map[Int, Long] = {\n val liftedPattern = children.map(_.pattern).foldLeft(emptyLiftedPattern)(mergePattern)\n liftedPattern.flatMap {\n case (a, b) if a >= -k => Option(a - 1 -> b)\n case _ => None\n }\n }\n }\n\n val q = (2 to n).flatMap { i =>\n val Array(u, v) = readInts\n Seq(u->v, v->u)\n }\n\n def tree(x: Int, parent: Int): Tree = Tree(\n for {\n (a, b) <- q\n if a == x\n if b != parent\n } yield tree(b, a)\n )\n\n val t = tree(1, 0)\n val ans = t.pattern.filter(_._1 >= 0).values.sum % MOD\n println(ans)\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject C extends App {\n val MOD = 1000000007\n def readInts = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n\n val Array(n, k) = readInts\n\n def mergePattern(p1: Map[Int, Long], p2: Map[Int, Long]): Map[Int, Long] = {\n val ans = mutable.HashMap.empty[Int, Long]\n for {\n (a1, b1) <- p1\n (a2, b2) <- p2\n } {\n val (a, b) =\n if (a1 + a2 > 0) (Math.max(a1, a2), b1 * b2 % MOD)\n else (Math.min(a1, a2), b1 * b2 % MOD)\n ans.put(a, ans.getOrElse(a, 0L) + b)\n }\n ans.toMap\n }\n\n val emptyLiftedPattern = Map(0 -> 1L, k+1 -> 1L)\n\n case class Tree(children: Seq[Tree]) {\n val pattern: Map[Int, Long] = {\n val liftedPattern = children.map(_.pattern).foldLeft(emptyLiftedPattern)(mergePattern)\n liftedPattern.flatMap {\n case (a, b) if a >= -k => Option(a - 1 -> b)\n case _ => None\n }\n }\n }\n\n val q = (2 to n).flatMap { i =>\n val Array(u, v) = readInts\n Seq(u->v, v->u)\n }\n\n def tree(x: Int, parent: Int): Tree = Tree(\n for {\n (a, b) <- q\n if a == x\n if b != parent\n } yield tree(b, a)\n )\n\n val t = tree(1, 0)\n val ans = t.pattern.filter(_._1 >= 0).values.sum % MOD\n println(ans)\n}\n"}], "src_uid": "43fbb05dc01b5302f19d923e45e325e7"} {"nl": {"description": "Vova has won $$$n$$$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible \u2014 that means, to maximize the length of the longest such subsegment.Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 the number of trophies. The second line contains $$$n$$$ characters, each of them is either G or S. If the $$$i$$$-th character is G, then the $$$i$$$-th trophy is a golden one, otherwise it's a silver trophy. ", "output_spec": "Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.", "sample_inputs": ["10\nGGGSGGGSGG", "4\nGGGG", "3\nSSS"], "sample_outputs": ["7", "4", "0"], "notes": "NoteIn the first example Vova has to swap trophies with indices $$$4$$$ and $$$10$$$. Thus he will obtain the sequence \"GGGGGGGSGS\", the length of the longest subsegment of golden trophies is $$$7$$$. In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is $$$4$$$. In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than $$$0$$$."}, "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 G = ns(N).map(a => if (a == 'G') 1 else 0)\n val S = G.sum\n val cum = cumSum(G)\n var mx = 0\n rep(N) { i =>\n if (G(i) == 0) mx = 0\n else mx += 1\n }\n\n var ans = mx\n var r = 0\n rep(N) { l =>\n if (r < l) r = l\n while (r + 1 < N && cum(r + 2) - cum(l) >= (r + 1 - l + 1) - 1) r += 1\n val v = cum(r + 1) - cum(l) + 1\n if (v <= S) ans = max(ans, cum(r + 1) - cum(l) + 1)\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 C = ns(N).map(c => if (c == 'G') 1 else 0)\n val L, R = Array.ofDim[Int](N)\n val S = C.sum\n\n L(0) = C(0)\n rep(N - 1, 1) { i =>\n L(i) = C(i) match {\n case 0 => 0\n case 1 => L(i - 1) + 1\n }\n }\n\n R(N - 1) = C(N - 1)\n rep_r(N - 1) { i =>\n R(i) = C(i) match {\n case 0 => 0\n case 1 => R(i + 1) + 1\n }\n }\n\n var ans = L.max\n rep(N - 2, 1) { i =>\n if (C(i - 1) == 1 && C(i) == 0 && C(i + 1) == 1 && S > L(i - 1) + R(i + 1)) {\n ans = max(ans, L(i - 1) + R(i + 1) + 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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 = ns(N).map(c => if (c == 'G') 1 else 0)\n val L, R = Array.ofDim[Int](N)\n val S = C.sum\n\n L(0) = C(0)\n rep(N - 1, 1) { i =>\n L(i) = C(i) match {\n case 0 => 0\n case 1 => L(i - 1) + 1\n }\n }\n\n R(N - 1) = C(N - 1)\n rep_r(N - 1) { i =>\n R(i) = C(i) match {\n case 0 => 0\n case 1 => R(i + 1) + 1\n }\n }\n\n val mx = L.max\n var ans = if (mx == S) mx else mx + 1\n rep(N - 2, 1) { i =>\n if (C(i) == 0 && S >= L(i - 1) + R(i + 1) + 1) {\n ans = max(ans, L(i - 1) + R(i + 1) + 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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 = ns(N).map(c => if (c == 'G') 1 else 0)\n val L, R = Array.ofDim[Int](N)\n val S = C.sum\n\n L(0) = C(0)\n rep(N - 1, 1) { i =>\n L(i) = C(i) match {\n case 0 => 0\n case 1 => L(i - 1) + 1\n }\n }\n\n R(N - 1) = C(N - 1)\n rep_r(N - 1) { i =>\n R(i) = C(i) match {\n case 0 => 0\n case 1 => R(i + 1) + 1\n }\n }\n\n val mx = L.max\n var ans = if (mx == S) mx else mx + 1\n rep(N - 2, 1) { i =>\n if (C(i - 1) == 1 && C(i) == 0 && C(i + 1) == 1 && S > L(i - 1) + R(i + 1)) {\n ans = max(ans, L(i - 1) + R(i + 1) + 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"}], "src_uid": "5d9d847103544fa07480fb85c75d0b97"} {"nl": {"description": "Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \\cdot a_j$$$ where $$$a_1, \\dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \\dots, a_n$$$. Help Sasha restore the array!", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\leqslant n \\leqslant 10^3$$$), the size of the table. The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \\leq M_{ij} \\leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$.", "output_spec": "In a single line print $$$n$$$ integers, the original array $$$a_1, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any.", "sample_inputs": ["5\n0 4 6 2 4\n4 0 6 2 4\n6 6 0 3 6\n2 2 3 0 2\n4 4 6 2 0", "3\n0 99990000 99970002\n99990000 0 99980000\n99970002 99980000 0"], "sample_outputs": ["2 2 3 1 2", "9999 10000 9998"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val m = nm(n, n)\n val g = gcd(m(0).drop(1))\n val d = divisors(g)\n debug(s\"g:$g\")\n debug(d)\n val a = Array.ofDim[Int](n)\n def showResult(): Unit = {\n out.println(a.mkString(\" \"))\n }\n\n REP(d.length) { i =>\n a(0) = d(i)\n REP(n - 1, 1) { j =>\n a(j) = m(0)(j) / a(0)\n }\n var ok = true\n REP(n - 2, 1) { j =>\n ok &&= m(j)(j + 1) == a(j).toLong * a(j + 1)\n }\n if (ok) {\n showResult()\n return\n }\n }\n }\n\n /**\n * O(\u221ax)\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 gcd(a: Int, b: Int): Int = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n def gcd(as: Array[Int]): Int = {\n var res = as(0)\n REP(as.length - 1, 1) { i =>\n res = gcd(res, as(i))\n }\n res\n }\n}"}], "negative_code": [], "src_uid": "ced70b400694fa16929d4b0bce3da294"} {"nl": {"description": "You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100\\,000$$$, $$$1 \\le m \\le 10^9$$$)\u00a0\u2014 the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le m$$$)\u00a0\u2014 the number of blocks in each stack from left to right.", "output_spec": "Print exactly one integer\u00a0\u2014 the maximum number of blocks that can be removed.", "sample_inputs": ["5 6\n3 3 3 3 3", "3 5\n1 2 4", "5 5\n2 3 1 4 4", "1 1000\n548", "3 3\n3 1 1"], "sample_outputs": ["10", "3", "9", "0", "1"], "notes": "NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$. "}, "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]\u306b\uff11\u3053\u305a\u3064\u914d\u7f6e\n val ans = sumL(A) - remain\n out.println(ans)\n }\n\n /**\n * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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]): 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}"}, {"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 * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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"} {"nl": {"description": "A line on the plane is described by an equation Ax\u2009+\u2009By\u2009+\u2009C\u2009=\u20090. You are to find any point on this line, whose coordinates are integer numbers from \u2009-\u20095\u00b71018 to 5\u00b71018 inclusive, or to find out that such points do not exist.", "input_spec": "The first line contains three integers A, B and C (\u2009-\u20092\u00b7109\u2009\u2264\u2009A,\u2009B,\u2009C\u2009\u2264\u20092\u00b7109) \u2014 corresponding coefficients of the line equation. It is guaranteed that A2\u2009+\u2009B2\u2009>\u20090.", "output_spec": "If the required point exists, output its coordinates, otherwise output -1.", "sample_inputs": ["2 5 3"], "sample_outputs": ["6 -3"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them\u00a0\u2014 those with biggest ti.Your task is to handle queries of two types: \"1 id\"\u00a0\u2014 Friend id becomes online. It's guaranteed that he wasn't online before. \"2 id\"\u00a0\u2014 Check whether friend id is displayed by the system. Print \"YES\" or \"NO\" in a separate line. Are you able to help Limak and answer all queries of the second type?", "input_spec": "The first line contains three integers n, k and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009150\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009min(6,\u2009n))\u00a0\u2014 the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u2009109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1\u2009\u2264\u2009typei\u2009\u2264\u20092,\u20091\u2009\u2264\u2009idi\u2009\u2264\u2009n)\u00a0\u2014 the i-th query. If typei\u2009=\u20091 then a friend idi becomes online. If typei\u2009=\u20092 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei\u2009=\u20092) so the output won't be empty.", "output_spec": "For each query of the second type print one line with the answer\u00a0\u2014 \"YES\" (without quotes) if the given friend is displayed and \"NO\" (without quotes) otherwise.", "sample_inputs": ["4 2 8\n300 950 500 200\n1 3\n2 4\n2 3\n1 1\n1 2\n2 1\n2 2\n2 3", "6 3 9\n50 20 51 17 99 24\n1 3\n1 4\n1 5\n1 2\n2 4\n2 2\n1 1\n2 4\n2 3"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES", "NO\nYES\nNO\nYES"], "notes": "NoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries: \"1 3\"\u00a0\u2014 Friend 3 becomes online. \"2 4\"\u00a0\u2014 We should check if friend 4 is displayed. He isn't even online and thus we print \"NO\". \"2 3\"\u00a0\u2014 We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print \"YES\". \"1 1\"\u00a0\u2014 Friend 1 becomes online. The system now displays both friend 1 and friend 3. \"1 2\"\u00a0\u2014 Friend 2 becomes online. There are 3 friends online now but we were given k\u2009=\u20092 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1\u2009<\u2009t2,\u2009t3) so friend 1 won't be displayed \"2 1\"\u00a0\u2014 Print \"NO\". \"2 2\"\u00a0\u2014 Print \"YES\". \"2 3\"\u00a0\u2014 Print \"YES\". "}, "positive_code": [{"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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "7c778289806ceed506543ef816c587c9"} {"nl": {"description": "Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.", "input_spec": "A single input line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "Print a single integer \u2014 the answer to the problem without leading zeroes, or \"-1\" (without the quotes), if the number that meet the problem condition does not exist.", "sample_inputs": ["1", "5"], "sample_outputs": ["-1", "10080"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,\u20091]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k\u2009-\u2009d,\u2009k\u2009+\u2009d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k\u2009-\u2009d,\u2009k]. If she escapes to the right, her new interval will be [k,\u2009k\u2009+\u2009d].You are given a string s of length n. If the i-th character of s is \"l\" or \"r\", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.", "input_spec": "The input consists of only one line. The only line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009106). Each character in s will be either \"l\" or \"r\".", "output_spec": "Output n lines \u2014 on the i-th line you should print the i-th stone's number from the left.", "sample_inputs": ["llrlr", "rrlll", "lrlrr"], "sample_outputs": ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"], "notes": "NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1."}, "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 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}"}, {"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(new OutputStreamWriter(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=seq match{\n case List() => 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"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $$$1$$$; during the second operation you choose one of these numbers and increase it by $$$2$$$, and so on. You choose the number of these operations yourself.For example, if $$$a = 1$$$ and $$$b = 3$$$, you can perform the following sequence of three operations: add $$$1$$$ to $$$a$$$, then $$$a = 2$$$ and $$$b = 3$$$; add $$$2$$$ to $$$b$$$, then $$$a = 2$$$ and $$$b = 5$$$; add $$$3$$$ to $$$a$$$, then $$$a = 5$$$ and $$$b = 5$$$. Calculate the minimum number of operations required to make $$$a$$$ and $$$b$$$ equal. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print one integer \u2014 the minimum numbers of operations required to make $$$a$$$ and $$$b$$$ equal. ", "sample_inputs": ["3\n1 3\n11 11\n30 20"], "sample_outputs": ["3\n0\n4"], "notes": "NoteFirst test case considered in the statement.In the second test case integers $$$a$$$ and $$$b$$$ are already equal, so you don't need to perform any operations.In the third test case you have to apply the first, the second, the third and the fourth operation to $$$b$$$ ($$$b$$$ turns into $$$20 + 1 + 2 + 3 + 4 = 30$$$)."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u200910\u2009000, n\u2009\u2265\u20092m)\u00a0\u2014 the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.", "output_spec": "Print m lines. On the i-th line print the team of the i-th region\u00a0\u2014 the surnames of the two team members in an arbitrary order, or a single character \"?\" (without the quotes) if you need to spend further qualifying contests in the region.", "sample_inputs": ["5 2\nIvanov 1 763\nAndreev 2 800\nPetrov 1 595\nSidorov 1 790\nSemenov 2 503", "5 2\nIvanov 1 800\nAndreev 2 763\nPetrov 1 800\nSidorov 1 800\nSemenov 2 503"], "sample_outputs": ["Sidorov Ivanov\nAndreev Semenov", "?\nAndreev Semenov"], "notes": "NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: \"Petrov\"-\"Sidorov\", \"Ivanov\"-\"Sidorov\", \"Ivanov\" -\"Petrov\", so it is impossible to determine a team uniquely."}, "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 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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given a permutation of length $$$n$$$. Recall that the permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You can perform at most $$$n-1$$$ operations with the given permutation (it is possible that you don't perform any operations at all). The $$$i$$$-th operation allows you to swap elements of the given permutation on positions $$$i$$$ and $$$i+1$$$. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer $$$q$$$ independent test cases.For example, let's consider the permutation $$$[5, 4, 1, 3, 2]$$$. The minimum possible permutation we can obtain is $$$[1, 5, 2, 4, 3]$$$ and we can do it in the following way: perform the second operation (swap the second and the third elements) and obtain the permutation $$$[5, 1, 4, 3, 2]$$$; perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $$$[5, 1, 4, 2, 3]$$$; perform the third operation (swap the third and the fourth elements) and obtain the permutation $$$[5, 1, 2, 4, 3]$$$. perform the first operation (swap the first and the second elements) and obtain the permutation $$$[1, 5, 2, 4, 3]$$$; Another example is $$$[1, 2, 4, 3]$$$. The minimum possible permutation we can obtain is $$$[1, 2, 3, 4]$$$ by performing the third operation (swap the third and the fourth elements).", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2014 the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ \u2014 the given permutation.", "output_spec": "For each test case, print the answer on it \u2014 the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.", "sample_inputs": ["4\n5\n5 4 1 3 2\n4\n1 2 4 3\n1\n1\n4\n4 3 2 1"], "sample_outputs": ["1 5 2 4 3 \n1 2 3 4 \n1 \n1 4 3 2"], "notes": "NoteRecall that the permutation $$$p$$$ of length $$$n$$$ is lexicographically less than the permutation $$$q$$$ of length $$$n$$$ if there is such index $$$i \\le n$$$ that for all $$$j$$$ from $$$1$$$ to $$$i - 1$$$ the condition $$$p_j = q_j$$$ is satisfied, and $$$p_i < q_i$$$. For example: $$$p = [1, 3, 5, 2, 4]$$$ is less than $$$q = [1, 3, 5, 4, 2]$$$ (such $$$i=4$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$), $$$p = [1, 2]$$$ is less than $$$q = [2, 1]$$$ (such $$$i=1$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$). "}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1\u2009\u00d7\u2009n square and paints the squares black and white. After that Petya can start moves \u2014 during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya\u2019s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) which represents the stripe\u2019s length. The second line contains exactly n symbols \u2014 the line\u2019s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.", "output_spec": "If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.", "sample_inputs": ["6\n111010", "5\n10001", "7\n1100010", "5\n00100"], "sample_outputs": ["1", "1", "2", "2"], "notes": "NoteIn the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black."}, "positive_code": [{"source_code": "object P049D extends App {\n val n = readInt\n val a = readLine.zipWithIndex\n val c1e = a.count(x => (x._1 == '1' && x._2 % 2 == 0))\n val c1o = a.count(x => (x._1 == '1' && x._2 % 2 == 1))\n val c0e = a.count(x => (x._1 == '0' && x._2 % 2 == 0))\n val c0o = a.count(x => (x._1 == '0' && x._2 % 2 == 1))\n println(math.min(c1e + c0o, c1o + c0e))\n}\n"}], "negative_code": [], "src_uid": "7c313b911e644cd5efa4fdc31d7ffcc9"} {"nl": {"description": "Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \\cdot n_a \\cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.", "input_spec": "The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \\leq n \\leq 30$$$, $$$1 \\leq k \\leq 10^5$$$, $$$1 \\leq A,B \\leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \\ldots, a_{k}$$$ ($$$1 \\leq a_{i} \\leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.", "output_spec": "Output one integer \u2014 the minimum power needed to destroy the avengers base.", "sample_inputs": ["2 2 1 2\n1 3", "3 2 1 2\n1 7"], "sample_outputs": ["6", "8"], "notes": "NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \\cdot 2 \\cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \\cdot 1 \\cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \\cdot 1 \\cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$."}, "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 // \u4e00\u4eba\u3082\u3044\u306a\u304b\u3063\u305f\u3089\u5373\u6642\u7834\u58ca\u3059\u308b\u306e\u304c\u3044\u3044\n else if (r - l == 1) {\n // \u30b5\u30a4\u30ba\u304c1\u306e\u5834\u5408\u306f\u3082\u3046\u5206\u5272\u3067\u304d\u306a\u3044\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 // \u30a2\u30d9\u30f3\u30b8\u30e3\u30fc\u304c\u6570\u5c11\u306a\u3044\u306e\u3067dfs\u304clogK * K\u3050\u3089\u3044\u306e\u56de\u6570\u3067\u3059\u3080\u306f\u305a\n val ans = calc(0, 1 << K, M)\n\n out.println(ans)\n }\n\n // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] \u306e 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 //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}"}], "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 // \u4e00\u4eba\u3082\u3044\u306a\u304b\u3063\u305f\u3089\u5373\u6642\u7834\u58ca\u3059\u308b\u306e\u304c\u3044\u3044\n else if (r - l == 1) {\n // \u30b5\u30a4\u30ba\u304c1\u306e\u5834\u5408\u306f\u3082\u3046\u5206\u5272\u3067\u304d\u306a\u3044\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 // \u30a2\u30d9\u30f3\u30b8\u30e3\u30fc\u304c\u6570\u5c11\u306a\u3044\u306e\u3067dfs\u304clogK * K\u3050\u3089\u3044\u306e\u56de\u6570\u3067\u3059\u3080\u306f\u305a\n val ans = calc(0, 1 << K)\n\n out.println(ans)\n }\n\n // \u3042\u3048\u3066\u30b3\u30d4\u30da\n // \u8981\u306fcountLt\n // a >= x [x-2, x-1, x, x, x, x+1] \u306e 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"} {"nl": {"description": "You are given a 4x4 grid. You play a game\u00a0\u2014 there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.", "input_spec": "The only line contains a string $$$s$$$ consisting of zeroes and ones ($$$1 \\le |s| \\le 1000$$$). Zero describes vertical tile, one describes horizontal tile.", "output_spec": "Output $$$|s|$$$ lines\u00a0\u2014 for each tile you should output two positive integers $$$r,c$$$, not exceeding $$$4$$$, representing numbers of smallest row and column intersecting with it. If there exist multiple solutions, print any of them.", "sample_inputs": ["010"], "sample_outputs": ["1 1\n1 2\n1 4"], "notes": "NoteFollowing image illustrates the example after placing all three tiles: Then the first row is deleted: "}, "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(_ == '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}"}, {"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"} {"nl": {"description": "Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \\leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \\frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_{mid} = a_{mid + 1} \\oplus a_{mid + 2} \\oplus \\ldots \\oplus a_r$$$, then the pair is funny. In other words, $$$\\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\\oplus$$$ of elements of the right half. Note that $$$\\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$)\u00a0\u2014 the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i < 2^{20}$$$)\u00a0\u2014 array itself.", "output_spec": "Print one integer\u00a0\u2014 the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number.", "sample_inputs": ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"], "sample_outputs": ["1", "3", "0"], "notes": "NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \\oplus 3 = 4 \\oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs."}, "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"}, {"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}"}], "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"} {"nl": {"description": "An array $$$b$$$ is called to be a subarray of $$$a$$$ if it forms a continuous subsequence of $$$a$$$, that is, if it is equal to $$$a_l$$$, $$$a_{l + 1}$$$, $$$\\ldots$$$, $$$a_r$$$ for some $$$l, r$$$.Suppose $$$m$$$ is some known constant. For any array, having $$$m$$$ or more elements, let's define it's beauty as the sum of $$$m$$$ largest elements of that array. For example: For array $$$x = [4, 3, 1, 5, 2]$$$ and $$$m = 3$$$, the $$$3$$$ largest elements of $$$x$$$ are $$$5$$$, $$$4$$$ and $$$3$$$, so the beauty of $$$x$$$ is $$$5 + 4 + 3 = 12$$$. For array $$$x = [10, 10, 10]$$$ and $$$m = 2$$$, the beauty of $$$x$$$ is $$$10 + 10 = 20$$$.You are given an array $$$a_1, a_2, \\ldots, a_n$$$, the value of the said constant $$$m$$$ and an integer $$$k$$$. Your need to split the array $$$a$$$ into exactly $$$k$$$ subarrays such that: Each element from $$$a$$$ belongs to exactly one subarray. Each subarray has at least $$$m$$$ elements. The sum of all beauties of $$$k$$$ subarrays is maximum possible.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m$$$, $$$2 \\le k$$$, $$$m \\cdot k \\le n$$$)\u00a0\u2014 the number of elements in $$$a$$$, the constant $$$m$$$ in the definition of beauty and the number of subarrays to split to. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$).", "output_spec": "In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition. In the second line, print $$$k-1$$$ integers $$$p_1, p_2, \\ldots, p_{k-1}$$$ ($$$1 \\le p_1 < p_2 < \\ldots < p_{k-1} < n$$$) representing the partition of the array, in which: All elements with indices from $$$1$$$ to $$$p_1$$$ belong to the first subarray. All elements with indices from $$$p_1 + 1$$$ to $$$p_2$$$ belong to the second subarray. $$$\\ldots$$$. All elements with indices from $$$p_{k-1} + 1$$$ to $$$n$$$ belong to the last, $$$k$$$-th subarray. If there are several optimal partitions, print any of them.", "sample_inputs": ["9 2 3\n5 2 5 2 4 1 1 3 2", "6 1 4\n4 1 3 2 2 3", "2 1 2\n-1000000000 1000000000"], "sample_outputs": ["21\n3 5", "12\n1 3 5", "0\n1"], "notes": "NoteIn the first example, one of the optimal partitions is $$$[5, 2, 5]$$$, $$$[2, 4]$$$, $$$[1, 1, 3, 2]$$$. The beauty of the subarray $$$[5, 2, 5]$$$ is $$$5 + 5 = 10$$$. The beauty of the subarray $$$[2, 4]$$$ is $$$2 + 4 = 6$$$. The beauty of the subarray $$$[1, 1, 3, 2]$$$ is $$$3 + 2 = 5$$$. The sum of their beauties is $$$10 + 6 + 5 = 21$$$.In the second example, one optimal partition is $$$[4]$$$, $$$[1, 3]$$$, $$$[2, 2]$$$, $$$[3]$$$."}, "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\u306e\u964d\u9806\u3067\u4e26\u3079\u308b\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\u306e\u6607\u9806\u3067\u30bd\u30fc\u30c8\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": "\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"}, {"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"} {"nl": {"description": "Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of snow drifts. Each of the following n lines contains two integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u20091000) \u2014 the coordinates of the i-th snow drift. Note that the north direction coin\u0441ides with the direction of Oy axis, so the east direction coin\u0441ides with the direction of the Ox axis. All snow drift's locations are distinct.", "output_spec": "Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.", "sample_inputs": ["2\n2 1\n1 2", "2\n2 1\n4 1"], "sample_outputs": ["1", "0"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote monotonic renumeration of array $$$a$$$ as an array $$$b$$$ consisting of $$$n$$$ integers such that all of the following conditions are met: $$$b_1 = 0$$$; for every pair of indices $$$i$$$ and $$$j$$$ such that $$$1 \\le i, j \\le n$$$, if $$$a_i = a_j$$$, then $$$b_i = b_j$$$ (note that if $$$a_i \\ne a_j$$$, it is still possible that $$$b_i = b_j$$$); for every index $$$i \\in [1, n - 1]$$$ either $$$b_i = b_{i + 1}$$$ or $$$b_i + 1 = b_{i + 1}$$$. For example, if $$$a = [1, 2, 1, 2, 3]$$$, then two possible monotonic renumerations of $$$a$$$ are $$$b = [0, 0, 0, 0, 0]$$$ and $$$b = [0, 0, 0, 0, 1]$$$.Your task is to calculate the number of different monotonic renumerations of $$$a$$$. The answer may be large, so print it modulo $$$998244353$$$.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print one integer \u2014 the number of different monotonic renumerations of $$$a$$$, taken modulo $$$998244353$$$.", "sample_inputs": ["5\n1 2 1 2 3", "2\n100 1", "4\n1 3 3 7"], "sample_outputs": ["2", "2", "4"], "notes": null}, "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 = 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\u306e\u521d\u671f\u30bb\u30b0\u30e1\u30f3\u30c8\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\u306eset\u3054\u3068\u306e\u30bb\u30b0\u30e1\u30f3\u30c8\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 // \u307e\u3060\u540c\u3058\u30bb\u30b0\u30e1\u30f3\u30c8\u306b\u306a\u3063\u3066\u3044\u306a\u3044\u306a\u3089\uff12\u3064\u306e\u30bb\u30b0\u30e1\u30f3\u30c8\u306e\u9593\u3092\u5168\u90e8\u878d\u5408\u3059\u308b\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 // \u3053\u306e\uff12\u3064\u306e\u30bb\u30b0\u30e1\u30f3\u30c8\u306f\u5fc5\u305a\u5171\u901a\u90e8\u5206\u304c\u306a\u3044\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\u304c\u56fa\u5b9a\u306a\u306e\u3067-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}"}, {"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"} {"nl": {"description": "There are $$$n$$$ piles of stones, where the $$$i$$$-th pile has $$$a_i$$$ stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 1000$$$) \u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 10^5$$$) \u00a0\u2014 the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1,\\ldots,a_n$$$ ($$$1\\le a_i\\le 10^9$$$) \u00a0\u2014 $$$a_i$$$ is equal to the number of stones in the $$$i$$$-th pile. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, if the player who makes the first move will win, output \"First\". Otherwise, output \"Second\".", "sample_inputs": ["7\n3\n2 5 4\n8\n1 1 1 1 1 1 1 1\n6\n1 2 3 4 5 6\n6\n1 1 2 1 2 2\n1\n1000000000\n5\n1 2 2 1 1\n3\n1 1 1"], "sample_outputs": ["First\nSecond\nSecond\nFirst\nFirst\nSecond\nFirst"], "notes": "NoteIn the first test case, the first player will win the game. His winning strategy is: The first player should take the stones from the first pile. He will take $$$1$$$ stone. The numbers of stones in piles will be $$$[1, 5, 4]$$$. The second player should take the stones from the first pile. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 5, 4]$$$. The first player should take the stones from the second pile because the first pile is empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 1, 4]$$$. The second player should take the stones from the second pile because the first pile is empty. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 0, 4]$$$. The first player should take the stones from the third pile because the first and second piles are empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 0, 0]$$$. The second player will lose the game because all piles will be empty. "}, "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\n n.times {\n val pile = in.nextInt()\n\n val numbers = in.line().split(\" \").map(_.toInt)\n\n var count = 0\n val len = numbers.length\n\n var cons = 0\n var f = false\n numbers.foreach(num => {\n if (num == 1 && !f) {\n cons = cons + 1\n } else {\n f = true\n }\n })\n\n if (cons == len) {\n if (len % 2 == 0) {\n println(\"Second\")\n } else {\n println(\"First\")\n }\n } else {\n if (cons % 2 == 1) {\n println(\"Second\")\n } else {\n println(\"First\")\n }\n }\n\n /*var start = false\n 0.until(len)\n .foreach(index => {\n if (numbers(index) > 1) {\n start = true\n } else {\n if (start) count = count + 1\n count = count + 1\n start = false\n }\n })\n if (start) count = count + 1\n println(count)\n if (count % 2 == 0) println(\"Second\") else println(\"First\")*/\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": "object 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 pile = in.nextInt()\n\n val numbers = in.line().split(\" \").map(_.toInt)\n\n var count = 0\n val len = numbers.length\n var start = false\n 0.until(len)\n .foreach(index => {\n if (numbers(index) > 1) {\n start = true\n } else {\n if (start) count = count + 1\n count = count + 1\n start = false\n }\n })\n if (start) count = count + 1\n if (count % 2 == 0) println(\"Second\") else println(\"First\")\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": "0c9030689394ad4e126e5b8681f1535c"} {"nl": {"description": "Thanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort?*Infinity Gauntlet required.", "input_spec": "The first line of input contains a single number $$$n$$$ ($$$1 \\le n \\le 16$$$) \u2014 the size of the array. $$$n$$$ is guaranteed to be a power of 2. The second line of input contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \\le a_i \\le 100$$$) \u2014 the elements of the array.", "output_spec": "Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order.", "sample_inputs": ["4\n1 2 2 4", "8\n11 12 1 2 13 14 3 4", "4\n7 6 5 4"], "sample_outputs": ["4", "2", "1"], "notes": "NoteIn the first example the array is already sorted, so no finger snaps are required.In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array.In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction."}, "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\n def dfs(A: Array[Int]): Int = {\n if (Arrays.equals(A.sorted, A)) {\n A.length\n } else {\n val (x, y) = A.splitAt(A.length / 2)\n max(dfs(x), dfs(y))\n }\n }\n\n val ans = dfs(na(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 java.util\nimport java.util.Scanner\nimport scala.math._\nimport scala.collection.mutable.ListBuffer\n\nobject Main {\n\n def findSubOrderedListSize(list: List[Int]): Int ={\n if(util.Arrays.equals(list.toArray.sorted, list.toArray))\n list.size\n else{\n val (x, y) = list.splitAt(list.size / 2)\n max(findSubOrderedListSize(x), findSubOrderedListSize(y))\n }\n\n\n }\n\n def main(args: Array[String]): Unit = {\n val sc = new Scanner(System.in)\n val n: Int = sc.nextInt()\n var list = new ListBuffer[Int]()\n for( i <- 0 to n - 1 ){\n var elem = sc.nextInt()\n list += elem\n }\n\n val finalList: List[Int] = list.toList\n println(findSubOrderedListSize(finalList))\n\n }\n}\n"}], "negative_code": [], "src_uid": "e5c68be38968fbc9677f3c1adddaff58"} {"nl": {"description": "Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string\u00a0\u2014\u00a0each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s|\u2009-\u2009ai\u2009+\u20091. It is guaranteed that 2\u00b7ai\u2009\u2264\u2009|s|.You face the following task: determine what Pasha's string will look like after m days.", "input_spec": "The first line of the input contains Pasha's string s of length from 2 to 2\u00b7105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014\u00a0 the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1\u2009\u2264\u2009ai; 2\u00b7ai\u2009\u2264\u2009|s|)\u00a0\u2014\u00a0the position from which Pasha started transforming the string on the i-th day.", "output_spec": "In the first line of the output print what Pasha's string s will look like after m days.", "sample_inputs": ["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"], "sample_outputs": ["aedcbf", "vwxyz", "fbdcea"], "notes": null}, "positive_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 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": "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"} {"nl": {"description": "You are given a sequence $$$b_1, b_2, \\ldots, b_n$$$. Find the lexicographically minimal permutation $$$a_1, a_2, \\ldots, a_{2n}$$$ such that $$$b_i = \\min(a_{2i-1}, a_{2i})$$$, or determine that it is impossible.", "input_spec": "Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). The first line of each test case consists of one integer $$$n$$$\u00a0\u2014 the number of elements in the sequence $$$b$$$ ($$$1 \\le n \\le 100$$$). The second line of each test case consists of $$$n$$$ different integers $$$b_1, \\ldots, b_n$$$\u00a0\u2014 elements of the sequence $$$b$$$ ($$$1 \\le b_i \\le 2n$$$). It is guaranteed that the sum of $$$n$$$ by all test cases doesn't exceed $$$100$$$.", "output_spec": "For each test case, if there is no appropriate permutation, print one number $$$-1$$$. Otherwise, print $$$2n$$$ integers $$$a_1, \\ldots, a_{2n}$$$\u00a0\u2014 required lexicographically minimal permutation of numbers from $$$1$$$ to $$$2n$$$.", "sample_inputs": ["5\n1\n1\n2\n4 1\n3\n4 1 3\n4\n2 3 4 5\n5\n1 5 7 2 8"], "sample_outputs": ["1 2 \n-1\n4 5 1 2 3 6 \n-1\n1 3 5 6 7 9 2 4 8 10"], "notes": null}, "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 }\n val edges = Array.fill(201)(Array.fill(201)(false))\n val used = Array.fill(201)(true)\n val res = Array.fill(201)(0)\n val pos = Array.fill(201)(0)\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val t = in.nextInt()\n (1 to t).foreach{ numCase =>\n\n\n val n = in.nextInt()\n val n2 = n*2\n (1 to n2).foreach{ i =>\n used(i) = false\n (1 to n2).foreach{ j =>\n edges(i)(j) = false\n }\n }\n (1 to n).foreach{ i =>\n val b = in.nextInt()\n res(i*2-1) = b\n used(b) = true\n pos(b) = i*2-1\n ((b+1) to n2).foreach{ j =>\n edges(b)(j) = true\n }\n }\n\n var imposible = false\n (1 to n2).reverse.foreach{ b =>\n if(!used(b)){\n\n val potentials = (1 to n2).filter{ j => edges(j)(b)}\n if(potentials.isEmpty){\n imposible = true\n }else{\n val j = potentials.max\n used(b) = true\n pos(b) = pos(j) +1\n res(pos(b)) = b\n (1 to n2).foreach{ k =>\n edges(k)(b) = false\n edges(k)(j) = false\n edges(b)(k) = false\n edges(j)(k) = false\n }\n }\n }\n\n }\n if(imposible){\n out.println(\"-1\")\n }else{\n //println(res.slice(1,n2+1).mkString(\" \"))\n\n (2 to n2 by 2).foreach{ i =>\n val pot = ((i+2) to n2 by 2).filter{ k => res(k) > res(i-1) && res(i) > res(k-1) && res(k) < res(i)}\n if(pot.nonEmpty){\n val j = pot.minBy(k => res(k))\n val z = res(j)\n res(j) = res(i)\n res(i) = z\n }\n }\n //println(res.slice(1,n2+1).mkString(\" \"))\n out.println(res.slice(1,n2+1).mkString(\" \"))\n }\n\n\n\n\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": "c4d32fcacffaa5d3a4db6dfa376d0324"} {"nl": {"description": "Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?", "input_spec": "First line of input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of players. The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the bids of players.", "output_spec": "Print \"Yes\" (without the quotes) if players can make their bids become equal, or \"No\" otherwise.", "sample_inputs": ["4\n75 150 75 50", "3\n100 150 250"], "sample_outputs": ["Yes", "No"], "notes": "NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "2bb893703cbffe9aeaa0bed02f42a05c"} {"nl": {"description": "Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009109) \u2014 sizes of towers.", "output_spec": "Print the number of operations needed to destroy all towers.", "sample_inputs": ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"], "sample_outputs": ["3", "2"], "notes": "NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation."}, "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": "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}"}, {"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"} {"nl": {"description": "Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $$$T$$$, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at $$$n$$$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The $$$i$$$-th obelisk is at integer coordinates $$$(x_i, y_i)$$$. The $$$j$$$-th clue consists of $$$2$$$ integers $$$(a_j, b_j)$$$ and belongs to the obelisk $$$p_j$$$, where $$$p$$$ is some (unknown) permutation on $$$n$$$ elements. It means that the treasure is located at $$$T=(x_{p_j} + a_j, y_{p_j} + b_j)$$$. This point $$$T$$$ is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.", "input_spec": "The first line contains an integer $$$n$$$\u00a0($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the number of obelisks, that is also equal to the number of clues. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$\u00a0($$$-10^6 \\leq x_i, y_i \\leq 10^6$$$)\u00a0\u2014 the coordinates of the $$$i$$$-th obelisk. All coordinates are distinct, that is $$$x_i \\neq x_j$$$ or $$$y_i \\neq y_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \\neq j$$$. Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$\u00a0($$$-2 \\cdot 10^6 \\leq a_i, b_i \\leq 2 \\cdot 10^6$$$)\u00a0\u2014 the direction of the $$$i$$$-th clue. All coordinates are distinct, that is $$$a_i \\neq a_j$$$ or $$$b_i \\neq b_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \\neq j$$$. It is guaranteed that there exists a permutation $$$p$$$, such that for all $$$i,j$$$ it holds $$$\\left(x_{p_i} + a_i, y_{p_i} + b_i\\right) = \\left(x_{p_j} + a_j, y_{p_j} + b_j\\right)$$$. ", "output_spec": "Output a single line containing two integers $$$T_x, T_y$$$\u00a0\u2014 the coordinates of the treasure. If there are multiple answers, you may print any of them.", "sample_inputs": ["2\n2 5\n-6 4\n7 -2\n-1 -3", "4\n2 2\n8 2\n-7 0\n-2 6\n1 -14\n16 -12\n11 -18\n7 -14"], "sample_outputs": ["1 2", "9 -12"], "notes": "NoteAs $$$n = 2$$$, we can consider all permutations on two elements. If $$$p = [1, 2]$$$, then the obelisk $$$(2, 5)$$$ holds the clue $$$(7, -2)$$$, which means that the treasure is hidden at $$$(9, 3)$$$. The second obelisk $$$(-6, 4)$$$ would give the clue $$$(-1,-3)$$$ and the treasure at $$$(-7, 1)$$$. However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is $$$[2, 1]$$$, then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence $$$(-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)$$$, so $$$T = (1,2)$$$ is the location of the treasure. In the second sample, the hidden permutation is $$$[2, 3, 4, 1]$$$."}, "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\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"}, {"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"} {"nl": {"description": "Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.", "input_spec": "The first line of input contains three space-separated integers n,\u2009k,\u2009d (1\u2009\u2264\u2009n,\u2009d\u2009\u2264\u20091000;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009109).", "output_spec": "If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.", "sample_inputs": ["3 2 2", "3 2 1"], "sample_outputs": ["1 1 2 \n1 2 1", "-1"], "notes": "NoteNote that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day."}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened: if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing; if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\\rightarrow$$$ abb $$$\\rightarrow$$$ abba $$$\\rightarrow$$$ abbac $$$\\rightarrow$$$ abbaca $$$\\rightarrow$$$ abbacabb $$$\\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.", "output_spec": "For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.", "sample_inputs": ["4\na\nzzaaz\nccff\ncbddbb"], "sample_outputs": ["a\nz\n\nbc"], "notes": null}, "positive_code": [{"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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called \"minutes\". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to \"move\" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y < x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \\cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.", "input_spec": "The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le y < x \\le 10^9$$$)\u00a0\u2014 the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.", "output_spec": "Print exactly one integer\u00a0\u2014 the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.", "sample_inputs": ["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"], "sample_outputs": ["60", "142", "999999997"], "notes": "NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \\cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \\cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \\cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$."}, "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 (from, to) = na2(N)\n\n case class Point(v: Int, tpe: Int, i: Int)\n val P = Array.ofDim[Point](N * 2)\n rep(N) { i =>\n P(i * 2) = Point(from(i), 0, i)\n P(i * 2 + 1) = Point(to(i), 1, i) // \u540c\u3058\u5834\u6240\u306a\u3089TO\u306e\u65b9\u304c\u51e6\u7406\u304c\u5f8c\u306b\u306a\u3089\u306a\u3044\u3068\u56f0\u308b\n }\n\n Sorting.quickSort(P)(Ordering.by(a => (a.v, a.tpe)))\n\n var ans = N.toLong * X % MOD\n rep(N) { i =>\n ans = (ans + Y.toLong * (to(i) - from(i))) % MOD\n }\n\n val found = new java.util.ArrayDeque[Int]\n rep(N * 2) { i =>\n val p = P(i)\n p.tpe match {\n case 0 =>\n if (!found.isEmpty) {\n if ((p.v - found.peek).toLong * Y < X) {\n val top = found.pop()\n ans = (MOD + ans + (p.v - top).toLong * Y - X) % MOD\n }\n }\n\n case 1 =>\n found.addFirst(p.v)\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}"}], "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, X, Y = ni()\n val (from, to) = na2(N)\n\n case class Point(v: Int, tpe: Int, i: Int)\n val P = Array.ofDim[Point](N * 2)\n rep(N) { i =>\n P(i * 2) = Point(from(i), 0, i)\n P(i * 2 + 1) = Point(to(i), 1, i) // \u540c\u3058\u5834\u6240\u306a\u3089TO\u306e\u65b9\u304c\u51e6\u7406\u304c\u5f8c\u306b\u306a\u3089\u306a\u3044\u3068\u56f0\u308b\n }\n\n Sorting.quickSort(P)(Ordering.by(a => (a.v, a.tpe)))\n\n var ans = N.toLong * X % MOD\n rep(N) { i =>\n ans = (ans + Y.toLong * (to(i) - from(i))) % MOD\n }\n\n val found = new java.util.ArrayDeque[Int]\n rep(N * 2) { i =>\n val p = P(i)\n p.tpe match {\n case 0 =>\n if (!found.isEmpty) {\n if ((p.v - found.peek).toLong * Y < X) {\n val top = found.pop()\n ans = (ans + (p.v - top).toLong * Y - X) % MOD\n }\n }\n\n case 1 =>\n found.addFirst(p.v)\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}"}], "src_uid": "6f4629e2dd9bca7980c8ee4f2e4b3edd"} {"nl": {"description": "A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \\times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \\le i \\le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \\le j \\le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\\max(R)-\\min(R))^2 + (\\max(C)-\\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\\max(X)$$$ as the maximum value in $$$X$$$ and $$$\\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \\le n \\le 300, 0 \\le k \\le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.", "sample_inputs": ["4\n2 2\n3 8\n1 0\n4 16"], "sample_outputs": ["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"], "notes": "NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject D extends App {\n\n def display(A: Array[Array[Int]]): Unit = {\n var maxR = -1\n var minR = Int.MaxValue\n\n var maxC = -1\n var minC = Int.MaxValue\n\n for {\n row <- A.indices\n } {\n val s = A(row).sum\n maxR = Math.max(maxR, s)\n minR = Math.min(minR, s)\n }\n\n val B = A.transpose\n for {\n row <- B.indices\n } {\n val s = B(row).sum\n maxC = Math.max(maxC, s)\n minC = Math.min(minC, s)\n }\n\n val left = (maxR - minR)\n val right = (maxC - minC)\n println(left * left + right * right)\n for {\n row <- A.indices\n } {\n println(A(row).mkString)\n }\n }\n\n val t = readInt()\n 1 to t foreach { _ =>\n val Array(n, k) = readLine().split(\" \").map(_.toInt)\n val A = Array.fill(n, n)(0)\n\n var row = 0\n var col = 0\n var colOffset = 1\n\n for (i <- 0 until k) {\n A(row)(col) = 1\n\n row += 1\n col += 1\n if (row == n) {\n row = 0\n col = colOffset\n colOffset += 1\n } else {\n col = col % n\n row = row % n\n }\n }\n\n display(A)\n }\n}\n"}], "negative_code": [], "src_uid": "0f18382d450be90edf1fd1a3770b232b"} {"nl": {"description": "You have a string $$$s$$$ of length $$$n$$$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to $$$n - 1$$$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2013 the number of test cases. Each test case is represented by two lines. The first line of $$$i$$$-th test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2013 the length of string $$$s$$$. The second line of $$$i$$$-th test case contains string $$$s$$$, consisting of only characters > and <.", "output_spec": "For each test case print one line. For $$$i$$$-th test case print the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.", "sample_inputs": ["3\n2\n<>\n3\n><<\n1\n>"], "sample_outputs": ["1\n0\n0"], "notes": "NoteIn the first test case we can delete any character in string <>.In the second test case we don't need to delete any characters. The string > < < is good, because we can perform the following sequence of operations: > < < $$$\\rightarrow$$$ < < $$$\\rightarrow$$$ <."}, "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"}, {"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"}], "negative_code": [], "src_uid": "0ba97bcfb5f539c848f2cd097b34ff33"} {"nl": {"description": "A sequence of square brackets is regular if by inserting symbols \"+\" and \"1\" into it, you can get a regular mathematical expression from it. For example, sequences \"[[]][]\", \"[]\" and \"[[][[]]]\" \u2014 are regular, at the same time \"][\", \"[[]\" and \"[[]]][\" \u2014 are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height \u2014 use symbols '+', '-' and '|'. For example, the sequence \"[[][]][]\" should be represented as: +- -++- -+ |+- -++- -+|| ||| || ||| ||+- -++- -+|| |+- -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique. ", "input_spec": "The first line contains an even integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the length of the sequence of brackets. The second line contains the sequence of brackets \u2014 these are n symbols \"[\" and \"]\". It is guaranteed that the given sequence of brackets is regular. ", "output_spec": "Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces. ", "sample_inputs": ["8\n[[][]][]", "6\n[[[]]]", "6\n[[][]]", "2\n[]", "4\n[][]"], "sample_outputs": ["+- -++- -+\n|+- -++- -+|| |\n|| || ||| |\n|+- -++- -+|| |\n+- -++- -+", "+- -+\n|+- -+|\n||+- -+||\n||| |||\n||+- -+||\n|+- -+|\n+- -+", "+- -+\n|+- -++- -+|\n|| || ||\n|+- -++- -+|\n+- -+", "+- -+\n| |\n+- -+", "+- -++- -+\n| || |\n+- -++- -+"], "notes": null}, "positive_code": [{"source_code": "/**\n * Created by ruslan on 3/12/17.\n */\nobject ProblemD 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 inputString = next\n val base = new Empty()\n\n var lastClosed = new Empty\n var queue: List[Expression] = List(base)\n\n for (s <- inputString.toCharArray) {\n if (s == '[') {\n val newOpen = new Brackets\n queue match {\n case last :: tail => last.add(newOpen)\n }\n queue = newOpen :: queue\n }\n else {\n queue match {\n case last :: tail => {\n if (last.getExpressions == Nil) last.add(new Empty)\n queue = tail\n }\n }\n }\n }\n\n val maxLevel = base.getExpressions.foldLeft(0)((acc, e) => Math.max(acc, e.level))\n\n base.getString(maxLevel).foreach(println)\n}\n\nabstract class Expression {\n var expressions: List[Expression] = Nil\n var parent: Expression = _\n var level: Int = 2\n\n def add(e: Expression): Unit = {\n expressions = e :: expressions\n e.setParent(this)\n if (parent != null) parent.incrementLevel(level)\n }\n\n def setParent(e: Expression): Unit = this.parent = e\n\n def incrementLevel(subLevel: Int): Unit = {\n level = Math.max(level, subLevel + 1)\n if (parent != null) parent.incrementLevel(level)\n }\n\n def getExpressions: List[Expression] = expressions\n\n def getString(level: Int): Array[String]\n}\n\nclass Brackets extends Expression {\n override def getString(level: Int): Array[String] = {\n val base = expressions.reverse.foldLeft(Array[String]())((a, e) => {\n val leftSide = e.getString(level - 1)\n a.zipAll(leftSide, \"\", \"\").foldLeft(Array[String]())((acc, pair) => Array.concat(acc, Array(pair._1 + pair._2)))\n })\n\n val topBottom = \"+-\" + \" \" * (base(0).length - 2) + \"-+\"\n for (i <- base.indices) base(i) = \"|\" + base(i) + \"|\"\n Array.concat(Array(topBottom), base, Array(topBottom))\n }\n}\n\n\nclass Empty extends Expression {\n override def getString(level: Int): Array[String] = {\n if (expressions != Nil) {\n expressions.reverse.foldLeft(Array[String]())((a, e) => {\n val leftSide = e.getString(level)\n a.zipAll(leftSide, \"\", \"\").foldLeft(Array[String]())((acc, pair) => Array.concat(acc, Array(pair._1 + pair._2)))\n })\n } else {\n\n val emptySpace = new Array[String]((level - 1) * 2 + 1)\n for (i <- emptySpace.indices) emptySpace(i) = \" \"\n\n emptySpace\n }\n }\n}"}], "negative_code": [], "src_uid": "7d9fb64a0a324a51432fbb01b4cc2c0e"} {"nl": {"description": "Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.", "input_spec": "A single line contains two integers m and n (1\u2009\u2264\u2009m,\u2009n\u2009\u2264\u2009105).", "output_spec": "Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009\u2009-\u20094.", "sample_inputs": ["6 1", "6 3", "2 2"], "sample_outputs": ["3.500000000000", "4.958333333333", "1.750000000000"], "notes": "NoteConsider the third test example. If you've made two tosses: You can get 1 in the first toss, and 2 in the second. Maximum equals to 2. You can get 1 in the first toss, and 1 in the second. Maximum equals to 1. You can get 2 in the first toss, and 1 in the second. Maximum equals to 2. You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value"}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009wi\u2009\u2264\u2009106), where ai,\u2009bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.", "output_spec": "Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.", "sample_inputs": ["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"], "sample_outputs": ["1 4 3 5", "1 4 3 5"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "Since you are the best Wraith King, Nizhniy Magazin \u00abMir\u00bb at the centre of Vinnytsia is offering you a discount.You are given an array a of length n and an integer c. The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3,\u20091,\u20096,\u20095,\u20092] with c\u2009=\u20092 is 3\u2009+\u20096\u2009+\u20095\u2009=\u200914.Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.", "input_spec": "The first line contains integers n and c (1\u2009\u2264\u2009n,\u2009c\u2009\u2264\u2009100\u2009000). The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 elements of a.", "output_spec": "Output a single integer \u00a0\u2014 the smallest possible sum of values of these subarrays of some partition of a.", "sample_inputs": ["3 5\n1 2 3", "12 10\n1 1 10 10 10 10 10 10 9 10 10 10", "7 2\n2 3 6 4 5 7 1", "8 4\n1 3 4 5 5 3 4 1"], "sample_outputs": ["6", "92", "17", "23"], "notes": "NoteIn the first example any partition yields 6 as the sum.In the second example one of the optimal partitions is [1,\u20091],\u2009[10,\u200910,\u200910,\u200910,\u200910,\u200910,\u20099,\u200910,\u200910,\u200910] with the values 2 and 90 respectively.In the third example one of the optimal partitions is [2,\u20093],\u2009[6,\u20094,\u20095,\u20097],\u2009[1] with the values 3, 13 and 1 respectively.In the fourth example one of the optimal partitions is [1],\u2009[3,\u20094,\u20095,\u20095,\u20093,\u20094],\u2009[1] with the values 1, 21 and 1 respectively."}, "positive_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 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"}, {"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"} {"nl": {"description": "One day Vasya decided to have a look at the results of Berland 1910 Football Championship\u2019s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of lines in the description. Then follow n lines \u2014 for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.", "output_spec": "Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.", "sample_inputs": ["1\nABC", "5\nA\nABA\nABA\nA\nA"], "sample_outputs": ["ABC", "A"], "notes": null}, "positive_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).map(_ => in.next()).groupBy(x => x).maxBy(_._2.length)._1)\n}\n"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "e3dcb1cf2186bf7e67fd8da20c1242a9"} {"nl": {"description": "Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either \"AB\" or \"BB\". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\\to$$$ AABBA $$$\\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 20000)$$$ \u00a0\u2014 the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains a single test case each, consisting of a non-empty string $$$s$$$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $$$s$$$ are either 'A' or 'B'. It is guaranteed that the sum of $$$|s|$$$ (length of $$$s$$$) among all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer: the length of the shortest string that Zookeeper can make.", "sample_inputs": ["3\nAAA\nBABA\nAABBBABBBB"], "sample_outputs": ["3\n2\n0"], "notes": "NoteFor the first test case, you can't make any moves, so the answer is $$$3$$$.For the second test case, one optimal sequence of moves is BABA $$$\\to$$$ BA. So, the answer is $$$2$$$.For the third test case, one optimal sequence of moves is AABBBABBBB $$$\\to$$$ AABBBABB $$$\\to$$$ AABBBB $$$\\to$$$ ABBB $$$\\to$$$ AB $$$\\to$$$ (empty string). So, the answer is $$$0$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "ee295fd90ee9283709447481f172c73c"} {"nl": {"description": "Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x\u2009-\u2009p vertices where 1\u2009\u2264\u2009p\u2009<\u2009x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of tests Peter is about to make. The second line contains n space separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), i-th of them stands for the number of vertices in the cycle added before the i-th test.", "output_spec": "Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.", "sample_inputs": ["3\n1 2 3", "5\n1 1 5 1 1"], "sample_outputs": ["2\n1\n1", "2\n2\n2\n2\n2"], "notes": "NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3. If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses. If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses."}, "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).scanLeft(2) {\n case(a, b) => (a + b + 1) % 2\n }.tail.map(2 - _)\n println(line.toList.mkString(\"\\n\"))\n}\n"}, {"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"} {"nl": {"description": "Daniel is organizing a football tournament. He has come up with the following tournament format: In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.", "sample_inputs": ["3", "25", "2"], "sample_outputs": ["3\n4", "20", "-1"], "notes": null}, "positive_code": [{"source_code": "object B extends App {\n\n def sqrt(number: BigInt) = {\n def next(n: BigInt, i: BigInt): BigInt = (n + i / n) >> 1\n\n val one = BigInt(1)\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 def readString = Console.readLine\n\n val n = BigInt(readString)\n\n var T = BigInt(0)\n var found = false\n \n while (T <= n) {\n val TT = 2 * T - 1\n val D = TT * TT + 8 * n\n val root = sqrt(D)\n if (D.equals(root * root) && (root - TT) % 2 == 0) {\n val i = (root - TT) / 2\n if (i % 2 != 0) {\n \t println(i * (T + 1))\n \t found = true\n }\n }\n T = 2 * T + 1\n }\n \n if (!found) println(-1)\n}"}], "negative_code": [], "src_uid": "7589b30ec643278d8a83d74d43d9aebe"} {"nl": {"description": "In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation $$$p$$$ of size $$$n$$$ is given. A permutation of size $$$n$$$ is an array of size $$$n$$$ in which each integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 4, 3, 2]$$$ and $$$[4, 2, 1, 3]$$$ are correct permutations while $$$[1, 2, 4]$$$ and $$$[1, 2, 2]$$$ are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[1, 5, 2]$$$ currently in the deque, adding an element $$$4$$$ to the beginning will produce the sequence $$$[\\color{red}{4}, 1, 5, 2]$$$, and adding same element to the end will produce $$$[1, 5, 2, \\color{red}{4}]$$$.The elements of the permutation are sequentially added to the initially empty deque, starting with $$$p_1$$$ and finishing with $$$p_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation $$$p = [3, 1, 2, 4]$$$, one of the possible sequences of actions looks like this: $$$\\quad$$$ 1.add $$$3$$$ to the end of the deque:deque has a sequence $$$[\\color{red}{3}]$$$ in it;$$$\\quad$$$ 2.add $$$1$$$ to the beginning of the deque:deque has a sequence $$$[\\color{red}{1}, 3]$$$ in it;$$$\\quad$$$ 3.add $$$2$$$ to the end of the deque:deque has a sequence $$$[1, 3, \\color{red}{2}]$$$ in it;$$$\\quad$$$ 4.add $$$4$$$ to the end of the deque:deque has a sequence $$$[1, 3, 2, \\color{red}{4}]$$$ in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence $$$[x_1, x_2, \\ldots, x_n]$$$ is lexicographically smaller than the sequence $$$[y_1, y_2, \\ldots, y_n]$$$ if there exists such $$$i \\leq n$$$ that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$, $$$\\ldots$$$, $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$. In other words, if the sequences $$$x$$$ and $$$y$$$ have some (possibly empty) matching prefix, and the next element of the sequence $$$x$$$ is strictly smaller than the corresponding element of the sequence $$$y$$$. For example, the sequence $$$[1, 3, 2, 4]$$$ is smaller than the sequence $$$[1, 3, 4, 2]$$$ because after the two matching elements $$$[1, 3]$$$ in the start the first sequence has an element $$$2$$$ which is smaller than the corresponding element $$$4$$$ in the second sequence.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 permutation size. The second line of the description contains $$$n$$$ space-separated integers $$$p_i$$$ ($$$1 \\le p_i \\le n$$$; all $$$p_i$$$ are all unique)\u00a0\u2014 elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should contain $$$n$$$ space-separated integer numbers\u00a0\u2014 the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.", "sample_inputs": ["5\n4\n3 1 2 4\n3\n3 2 1\n3\n3 1 2\n2\n1 2\n2\n2 1"], "sample_outputs": ["1 3 2 4 \n1 2 3 \n1 3 2 \n1 2 \n1 2"], "notes": "NoteOne of the ways to get a lexicographically smallest permutation $$$[1, 3, 2, 4]$$$ from the permutation $$$[3, 1, 2, 4]$$$ (the first sample test case) is described in the problem statement."}, "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": "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"}, {"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"} {"nl": {"description": "New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1\u2009\u00d7\u2009n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n\u2009-\u20091 positive integers a1,\u2009a2,\u2009...,\u2009an\u2009-\u20091. For every integer i where 1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091 the condition 1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u2009i holds. Next, he made n\u2009-\u20091 portals, numbered by integers from 1 to n\u2009-\u20091. The i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) portal connects cell i and cell (i\u2009+\u2009ai), and one can travel from cell i to cell (i\u2009+\u2009ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i\u2009+\u2009ai) to cell i using the i-th portal. It is easy to see that because of condition 1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u2009i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.", "input_spec": "The first line contains two space-separated integers n (3\u2009\u2264\u2009n\u2009\u2264\u20093\u2009\u00d7\u2009104) and t (2\u2009\u2264\u2009t\u2009\u2264\u2009n) \u2014 the number of cells, and the index of the cell which I want to go to. The second line contains n\u2009-\u20091 space-separated integers a1,\u2009a2,\u2009...,\u2009an\u2009-\u20091 (1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u2009i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.", "output_spec": "If I can go to cell t using the transportation system, print \"YES\". Otherwise, print \"NO\".", "sample_inputs": ["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, the visited cells are: 1,\u20092,\u20094; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,\u20092,\u20094,\u20096,\u20097,\u20098; so we can't visit the cell 5, which we want to visit."}, "positive_code": [{"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}"}, {"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 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}"}, {"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 } // \u043f\u0435\u0447\u0430\u0442\u0430\u0435\u043c \u0438\u043b\u0438 \u043a\u0443\u0434\u0430-\u0442\u043e \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u043c\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 } // \u043f\u0435\u0447\u0430\u0442\u0430\u0435\u043c \u0438\u043b\u0438 \u043a\u0443\u0434\u0430-\u0442\u043e \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u043c\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; // \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043f\u043e \u043c\u0430\u0441\u0438\u0432\u0443 \u0430\n var con =0;\n var g = new Array[List[Int]](t(0))\n for(v <- 0 to g.length-2)// \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0430\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}"}], "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 } // \u043f\u0435\u0447\u0430\u0442\u0430\u0435\u043c \u0438\u043b\u0438 \u043a\u0443\u0434\u0430-\u0442\u043e \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u043c\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; // \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043f\u043e \u043c\u0430\u0441\u0438\u0432\u0443 \u0430\n var con =0;\n var g = new Array[List[Int]](t(0))\n for(v <- 0 to g.length-1)// \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0430\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 } // \u043f\u0435\u0447\u0430\u0442\u0430\u0435\u043c \u0438\u043b\u0438 \u043a\u0443\u0434\u0430-\u0442\u043e \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u043c\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; // \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f \u043f\u043e \u043c\u0430\u0441\u0438\u0432\u0443 \u0430\n var con =0;\n var g = new Array[List[Int]](t(0))\n for(v <- 0 to g.length-1)// \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0430\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"} {"nl": {"description": "The king of Berland organizes a ball! $$$n$$$ pair are invited to the ball, they are numbered from $$$1$$$ to $$$n$$$. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from $$$1$$$ to $$$k$$$, inclusive.Let $$$b_i$$$ be the color of the man's costume and $$$g_i$$$ be the color of the woman's costume in the $$$i$$$-th pair. You have to choose a color for each dancer's costume (i.e. values $$$b_1, b_2, \\dots, b_n$$$ and $$$g_1, g_2, \\dots g_n$$$) in such a way that: for every $$$i$$$: $$$b_i$$$ and $$$g_i$$$ are integers between $$$1$$$ and $$$k$$$, inclusive; there are no two completely identical pairs, i.e. no two indices $$$i, j$$$ ($$$i \\ne j$$$) such that $$$b_i = b_j$$$ and $$$g_i = g_j$$$ at the same time; there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. $$$b_i \\ne g_i$$$ for every $$$i$$$; for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every $$$i$$$ from $$$1$$$ to $$$n-1$$$ the conditions $$$b_i \\ne b_{i + 1}$$$ and $$$g_i \\ne g_{i + 1}$$$ hold. Let's take a look at the examples of bad and good color choosing (for $$$n=4$$$ and $$$k=3$$$, man is the first in a pair and woman is the second):Bad color choosing: $$$(1, 2)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$, $$$(1, 2)$$$ \u2014 contradiction with the second rule (there are equal pairs); $$$(2, 3)$$$, $$$(1, 1)$$$, $$$(3, 2)$$$, $$$(1, 3)$$$ \u2014 contradiction with the third rule (there is a pair with costumes of the same color); $$$(1, 2)$$$, $$$(2, 3)$$$, $$$(1, 3)$$$, $$$(2, 1)$$$ \u2014 contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same). Good color choosing: $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(1, 3)$$$, $$$(3, 1)$$$; $$$(1, 2)$$$, $$$(3, 1)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$; $$$(3, 1)$$$, $$$(1, 2)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$. You have to find any suitable color choosing or say that no suitable choosing exists.", "input_spec": "The only line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n, k \\le 2 \\cdot 10^5$$$) \u2014 the number of pairs and the number of colors.", "output_spec": "If it is impossible to find any suitable colors choosing, print \"NO\". Otherwise print \"YES\" and then the colors of the costumes of pairs in the next $$$n$$$ lines. The $$$i$$$-th line should contain two integers $$$b_i$$$ and $$$g_i$$$ \u2014 colors of costumes of man and woman in the $$$i$$$-th pair, respectively. You can print each letter in any case (upper or lower). For example, \"YeS\", \"no\" and \"yES\" are all acceptable.", "sample_inputs": ["4 3", "10 4", "13 4"], "sample_outputs": ["YES\n3 1\n1 3\n3 2\n2 3", "YES\n2 1\n1 3\n4 2\n3 4\n4 3\n3 2\n2 4\n4 1\n1 4\n3 1", "NO"], "notes": null}, "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 if (N > M.toLong * (M - 1)) out.println(\"NO\")\n else {\n out.println(\"YES\")\n var cnt = 0\n REP(M - 1, 1) { i =>\n i + 1 to M foreach { j =>\n if (cnt == N) return\n out.println(s\"$i $j\")\n cnt += 1\n\n if (cnt == N) return\n out.println(s\"$j $i\")\n cnt += 1\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}"}], "negative_code": [], "src_uid": "c9237925ab3de588a3f047c226f7fe83"} {"nl": {"description": "Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of lines. Next n lines contain commands. A command consists of a character that represents the operation (\"&\", \"|\" or \"^\" for AND, OR or XOR respectively), and the constant xi 0\u2009\u2264\u2009xi\u2009\u2264\u20091023.", "output_spec": "Output an integer k (0\u2009\u2264\u2009k\u2009\u2264\u20095) \u2014 the length of your program. Next k lines must contain commands in the same format as in the input.", "sample_inputs": ["3\n| 3\n^ 2\n| 1", "3\n& 1\n& 3\n& 5", "3\n^ 1\n^ 2\n^ 3"], "sample_outputs": ["2\n| 3\n^ 2", "1\n& 1", "0"], "notes": "NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5\u2009=\u2009x&(1&3&5)\u2009=\u2009x&1. So these two programs always give the same outputs."}, "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\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"}, {"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": "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}"}], "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"} {"nl": {"description": "You are given a palindromic string $$$s$$$ of length $$$n$$$.You have to count the number of indices $$$i$$$ $$$(1 \\le i \\le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome. For example, consider $$$s$$$ = \"aba\" If we remove $$$s_1$$$ from $$$s$$$, the string becomes \"ba\" which is not a palindrome. If we remove $$$s_2$$$ from $$$s$$$, the string becomes \"aa\" which is a palindrome. If we remove $$$s_3$$$ from $$$s$$$, the string becomes \"ab\" which is not a palindrome. A palindrome is a string that reads the same backward as forward. For example, \"abba\", \"a\", \"fef\" are palindromes whereas \"codeforces\", \"acd\", \"xy\" are not.", "input_spec": "The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10^3)$$$ \u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(2 \\leq n \\leq 10^5)$$$ \u00a0\u2014 the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of lowercase English letters. It is guaranteed that $$$s$$$ is a palindrome. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer \u00a0\u2014 the number of indices $$$i$$$ $$$(1 \\le i \\le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome. ", "sample_inputs": ["3\n\n3\n\naba\n\n8\n\nacaaaaca\n\n2\n\ndd"], "sample_outputs": ["1\n4\n2"], "notes": "NoteThe first test case is described in the statement.In the second test case, the indices $$$i$$$ that result in palindrome after removing $$$s_i$$$ are $$$3, 4, 5, 6$$$. Hence the answer is $$$4$$$. In the third test case, removal of any of the indices results in \"d\" which is a palindrome. Hence the answer is $$$2$$$."}, "positive_code": [{"source_code": "\nobject PrA extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val out = new PrintWriter (System.out)\n val in = new Scanner (System.in)\n\n def solve_ = {\n in.nextLine()\n val str = in.nextLine()\n val n = str.length\n var curidx = n / 2\n val midchar = str(curidx)\n var acc = (n + 1) % 2 - 1\n while (curidx < n && str(curidx) == midchar){\n acc += 2\n curidx += 1\n }\n out.println(acc)\n }\n\n def solve = {\n val n = in.nextInt\n in.nextLine\n for (i <- 0 until n) {\n solve_\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 * in.nextInt - read int\n * in.nextLine - read string\n * in.nextDouble - read double\n * out.println - putStrLn\n */\n"}], "negative_code": [{"source_code": "\nobject PrA extends App {\n import java.io.{PrintWriter}\n import java.util.{Locale, Scanner}\n\n val out = new PrintWriter (System.out)\n val in = new Scanner (System.in)\n\n def solve = {\n in.nextLine()\n val str = in.nextLine()\n val n = str.length\n var curidx = n / 2\n val midchar = str(curidx)\n var acc = (n + 1) % 2 - 1\n while (curidx < n && str(curidx) == midchar){\n acc += 2\n curidx += 1\n }\n out.println(acc)\n }\n\n\n try {\n solve\n } catch {\n case _: Exception => sys.exit(9999)\n } finally {\n out.flush\n }\n}\n\n/*\n * in.nextInt - read int\n * in.nextLine - read string\n * in.nextDouble - read double\n * out.println - putStrLn\n */\n"}], "src_uid": "fa761cd247a815f105668b716c20f0b4"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. Initially all elements of $$$a$$$ are either $$$0$$$ or $$$1$$$. You need to process $$$q$$$ queries of two kinds: 1 x : Assign to $$$a_x$$$ the value $$$1 - a_x$$$. 2 k : Print the $$$k$$$-th largest value of the array. As a reminder, $$$k$$$-th largest value of the array $$$b$$$ is defined as following: Sort the array in the non-increasing order, return $$$k$$$-th element from it. For example, the second largest element in array $$$[0, 1, 0, 1]$$$ is $$$1$$$, as after sorting in non-increasing order it becomes $$$[1, 1, 0, 0]$$$, and the second element in this array is equal to $$$1$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 10^5$$$) \u2014 the length of the given array and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$) \u2014 elements of the initial array. Each of the following $$$q$$$ lines contains two integers. The first integer is $$$t$$$ ($$$1 \\le t \\le 2$$$) \u2014 the type of query. If $$$t = 1$$$ the second integer is $$$x$$$ ($$$1 \\le x \\le n$$$) \u2014 the position of the modified number. You have to assign to $$$a_x$$$ the value $$$1 - a_x$$$. If $$$t = 2$$$ the second integer is $$$k$$$ ($$$1 \\le k \\le n$$$) \u2014 you need to print the $$$k$$$-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying $$$t = 2$$$).", "output_spec": "For each query of the second type, print a single integer \u2014 the answer to the query.", "sample_inputs": ["5 5\n1 1 0 1 0\n2 3\n1 2\n2 3\n2 1\n2 5"], "sample_outputs": ["1\n0\n1\n0"], "notes": "NoteInitially $$$a = [1, 1, 0, 1, 0]$$$.The first operation is printing the third largest value, which is $$$1$$$.The second operation is assigning $$$a_2$$$ the value $$$0$$$, $$$a$$$ becomes $$$[1, 0, 0, 1, 0]$$$.The third operation is printing the third largest value, it is $$$0$$$.The fourth operation is printing the first largest value, it is $$$1$$$.The last operation is printing the fifth largest value, it is $$$0$$$."}, "positive_code": [{"source_code": "object A {\n import InOut._\n def main(args: Array[String]): Unit = {\n val n, q = nextInt\n val as = nextInts(n)\n var ones = as.sum\n\n for (_ <- 1 to q) {\n val t, x = nextInt\n if (t == 1) {\n as(x - 1) = 1 - as(x - 1)\n if (as(x - 1) == 1) ones += 1 else ones -=1\n } else {\n// println(as.mkString, ones)\n val res = if (x > ones) 0 else 1\n out.println(res)\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": "ccf7aba6ca9bbf39a5ec8a20ec018825"} {"nl": {"description": "One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2\u00b7m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2\u00b7m from left to right, then the j-th flat of the i-th floor has windows 2\u00b7j\u2009-\u20091 and 2\u00b7j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2\u00b7m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.", "output_spec": "Print a single integer\u00a0\u2014 the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.", "sample_inputs": ["2 2\n0 0 0 1\n1 0 1 1", "1 3\n1 1 0 1 0 0"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off."}, "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 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"}, {"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"} {"nl": {"description": "Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $$$p_i$$$ \u2014 the index of the router to which the $$$i$$$-th router was connected after being purchased ($$$p_i < i$$$).There are $$$n$$$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $$$n$$$-th router.", "input_spec": "The first line contains integer number $$$n$$$ ($$$2 \\le n \\le 200000$$$) \u2014 the number of the routers. The following line contains $$$n-1$$$ integers $$$p_2, p_3, \\dots, p_n$$$ ($$$1 \\le p_i < i$$$), where $$$p_i$$$ is equal to index of the router to which the $$$i$$$-th was connected after purchase.", "output_spec": "Print the path from the $$$1$$$-st to the $$$n$$$-th router. It starts with $$$1$$$ and ends with $$$n$$$. All the elements in the path should be distinct.", "sample_inputs": ["8\n1 1 2 2 3 2 5", "6\n1 2 3 4 5", "7\n1 1 2 3 4 3"], "sample_outputs": ["1 2 5 8", "1 2 3 4 5 6", "1 3 7"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "e25efe1020ae64d55b3257ba457f809d"} {"nl": {"description": "Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are $$$n$$$ cities in the republic, some of them are connected by $$$m$$$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $$$1$$$, travel to the city $$$n$$$ by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads \u2014 in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $$$1$$$ to $$$n$$$, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $$$1$$$ to $$$n$$$ or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.", "input_spec": "The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \\leq n \\leq 500000$$$, $$$0 \\leq m \\leq 500000$$$) \u2014 the number of cities and the number of roads. The $$$i$$$-th of next $$$m$$$ lines contains three integers \u2014 $$$u_i$$$, $$$v_i$$$ and $$$t_i$$$ ($$$1 \\leq u_i, v_i \\leq n$$$, $$$t_i \\in \\{0, 1\\}$$$) \u2014 numbers of cities connected by road and its type, respectively ($$$0$$$ \u2014 night road, $$$1$$$ \u2014 morning road).", "output_spec": "In the first line output the length of the desired path (or $$$-1$$$, if it's possible to choose such schedule that there's no path from $$$1$$$ to $$$n$$$). In the second line output the desired schedule \u2014 a string of $$$n$$$ digits, where $$$i$$$-th digit is $$$0$$$, if the $$$i$$$-th city is a night one, and $$$1$$$ if it's a morning one. If there are multiple answers, print any.", "sample_inputs": ["3 4\n1 2 0\n1 3 1\n2 3 0\n2 3 1", "4 8\n1 1 0\n1 3 0\n1 3 1\n3 2 0\n2 1 0\n3 4 1\n2 4 0\n2 4 1", "5 10\n1 2 0\n1 3 1\n1 4 0\n2 3 0\n2 3 1\n2 5 0\n3 4 0\n3 4 1\n4 2 1\n4 5 0"], "sample_outputs": ["2\n011", "3\n1101", "-1\n11111"], "notes": "NoteFor the first sample, if we paint city $$$1$$$ white, the shortest path is $$$1 \\rightarrow 3$$$. Otherwise, it's $$$1 \\rightarrow 2 \\rightarrow 3$$$ regardless of other cities' colors.For the second sample, we should paint city $$$3$$$ black, and there are both black and white roads going from $$$2$$$ to $$$4$$$. Note that there can be a road connecting a city with itself."}, "positive_code": [{"source_code": "//package codeforces.contests._1407\n\nobject EgorInTheRepublicOfDagestan {\n\n import scala.collection.immutable.Queue\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)\n\n (1 to m).foreach { _ =>\n val Array(l, r, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n graph(r) ::= (l, color)\n }\n\n val visited = new Array[Boolean](n + 1) // true if ever been inside the Queue\n val color, distance = Array.fill[Int](n + 1)(-1)\n\n @scala.annotation.tailrec\n def bfs(queue: Queue[Int] = Queue(n)): Unit = {\n if (queue.nonEmpty) {\n val (v, q) = queue.dequeue\n\n val updatedQueue = graph(v).foldLeft(q) { case (q, (u, c)) =>\n color(u) match {\n case -1 => color(u) =\n (c + 1) % 2 // set opposite color, block this edge\n q\n case _ if visited(u) =>\n q\n case `c` =>\n visited(u) = true\n distance(u) = distance(v) + 1\n q.enqueue(u)\n case _ =>\n q\n }\n }\n\n bfs(updatedQueue)\n }\n }\n\n color(n) = 1 // doesn't matter\n distance(n) = 0\n\n visited(n) = true\n\n bfs()\n\n println(distance(1))\n println(color.map(x => if (x == -1) 0 else x).view(1, n + 1).mkString(\"\"))\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1407\n\nobject EgorInTheRepublicOfDagestan {\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val graph0, graph1 = Array.fill[List[Int]](n + 1)(Nil)\n\n (1 to m).foreach { _ =>\n val Array(l, r, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n if (color == 0) graph0(l) ::= r else graph1(l) ::= r\n }\n\n val visited: Array[Boolean] = new Array[Boolean](n + 1)\n\n def recur(v: Int, next: List[Int], color: Int): (Int, List[(Int, Int)]) = {\n val neighbours = next.dropWhile(visited)\n val result = if (neighbours.nonEmpty) {\n val u = neighbours.head\n visited(u) = true\n val r = dfs(u)\n visited(u) = false\n\n val (accC, accList) = neighbours.tail.foldLeft(r) { (acc, u) =>\n if (acc._1 != -1 && !visited(u)) {\n visited(u) = true\n val (c, list) = dfs(u)\n visited(u) = false\n if (c == -1)\n (-1, list)\n else if (c > acc._1)\n (c, list)\n else\n acc\n } else acc\n }\n\n (if (accC == -1) -1 else accC + 1, (v, color) :: accList)\n } else (-1, List((v, color)))\n\n result\n }\n\n def dfs(v: Int): (Int, List[(Int, Int)]) = {\n if (v == n) (0, Nil)\n else {\n val r0@(c0, _) = recur(v, graph0(v), 0)\n if (c0 != -1) {\n val r1@(c1, _) = recur(v, graph1(v), 1)\n if (c1 != -1)\n if (c0 > c1) r0 else r1\n else r1\n } else r0\n }\n }\n\n val tag = new Array[Int](n + 1)\n\n visited(1) = true\n val (c, list) = dfs(1)\n visited(1) = false\n list.foreach { case (v, color) => tag(v) = color }\n\n println(c)\n println(tag.view(1, n + 1).mkString(\"\"))\n }\n}\n"}, {"source_code": "//package codeforces.contests._1407\n\nobject EgorInTheRepublicOfDagestan {\n\n import scala.collection.immutable.Queue\n\n def main(args: Array[String]): Unit = {\n val Array(n, m) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)\n\n (1 to m).foreach { _ =>\n val Array(l, r, color) = io.StdIn.readLine().split(\" \").map(_.toInt)\n graph(r) ::= (l, color)\n }\n\n val visited = new Array[Boolean](n + 1) // true if ever been inside the Queue\n val color, distance = Array.fill[Int](n + 1)(-1)\n\n @scala.annotation.tailrec\n def bfs(queue: Queue[Int] = Queue(n)): Unit = {\n if (queue.nonEmpty) {\n val (v, q) = queue.dequeue\n\n val updatedQueue = graph(v).foldLeft(q) { case (q, (u, c)) =>\n color(u) match {\n case -1 => color(u) = (c + 1) % 2 // set opposite color, block this edge\n q\n case _ if !visited(u) =>\n visited(u) = true\n distance(u) = distance(v) + 1\n q.enqueue(u)\n case _ =>\n q\n }\n }\n\n bfs(updatedQueue)\n }\n }\n\n color(n) = 1 // doesn't matter\n distance(n) = 0\n\n visited(n) = true\n\n bfs()\n\n println(distance(1))\n println(color.map(x => if (x == -1) 0 else x).view(1, n + 1).mkString(\"\"))\n }\n}\n"}], "src_uid": "f26a979dc042ec9564cfecce29e5a1cf"} {"nl": {"description": "There are $$$n + 1$$$ cities, numbered from $$$0$$$ to $$$n$$$. $$$n$$$ roads connect these cities, the $$$i$$$-th road connects cities $$$i - 1$$$ and $$$i$$$ ($$$i \\in [1, n]$$$).Each road has a direction. The directions are given by a string of $$$n$$$ characters such that each character is either L or R. If the $$$i$$$-th character is L, it means that the $$$i$$$-th road initially goes from the city $$$i$$$ to the city $$$i - 1$$$; otherwise it goes from the city $$$i - 1$$$ to the city $$$i$$$.A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i.\u2009e., if a road is directed from city $$$i$$$ to the city $$$i + 1$$$, it is possible to travel from $$$i$$$ to $$$i + 1$$$, but not from $$$i + 1$$$ to $$$i$$$. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $$$i$$$, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city $$$i$$$. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 3 \\cdot 10^5$$$). The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters, each character is either L or R. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print $$$n + 1$$$ integers. The $$$i$$$-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the $$$i$$$-th city.", "sample_inputs": ["2\n6\nLRRRLL\n3\nLRL"], "sample_outputs": ["1 3 2 3 1 3 2\n1 4 1 4"], "notes": null}, "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 s = nextLine\n val left, right, res = Array.fill(n + 1)(0)\n\n var prev = ' '\n var stride = 0\n for (i <- 1 to n) {\n val c = s(i - 1)\n if (c != prev) stride += 1\n else stride = 1\n if (c == 'L') left(i) = stride\n prev = c\n }\n\n prev = ' '\n stride = 0\n for (i <- n-1 to 0 by -1) {\n val c = s(i)\n if (c != prev) stride += 1\n else stride = 1\n// println(i,c, prev, stride)\n if (c == 'R') right(i) = stride\n prev = c\n }\n//println(left.mkString(\" \"))\n// println(right.mkString(\" \"))\n for (i <- res.indices) {\n res(i) = 1 + left(i) + right(i)\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"}], "negative_code": [], "src_uid": "f51a46e87b8871c3f581786f84e5e6d1"} {"nl": {"description": "Fox Ciel is playing a mobile puzzle game called \"Two Dots\". The basic levels are played on a board of size n\u2009\u00d7\u2009m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1,\u2009d2,\u2009...,\u2009dk a cycle if and only if it meets the following condition: These k dots are different: if i\u2009\u2260\u2009j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1\u2009\u2264\u2009i\u2009\u2264\u2009k\u2009-\u20091: di and di\u2009+\u20091 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.", "output_spec": "Output \"Yes\" if there exists a cycle, and \"No\" otherwise.", "sample_inputs": ["3 4\nAAAA\nABCA\nAAAA", "3 4\nAAAA\nABCA\nAADA", "4 4\nYYYR\nBYBY\nBBBY\nBBBY", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB", "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ"], "sample_outputs": ["Yes", "No", "Yes", "Yes", "No"], "notes": "NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red)."}, "positive_code": [{"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": "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": "\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"}, {"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}"}], "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"} {"nl": {"description": "Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1,\u2009s2,\u2009...,\u2009sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1\u2009\u2264\u2009i\u2009\u2264\u2009n). Help Polycarpus determine the length of the city phone code. ", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7104) \u2014 the number of Polycarpus's friends. The following n lines contain strings s1,\u2009s2,\u2009...,\u2009sn \u2014 the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.", "output_spec": "Print the number of digits in the city phone code.", "sample_inputs": ["4\n00209\n00219\n00999\n00909", "2\n1\n2", "3\n77012345678999999999\n77012345678901234567\n77012345678998765432"], "sample_outputs": ["2", "0", "12"], "notes": "NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string \"00209\" has 6 prefixes: \"\" (an empty prefix), \"0\", \"00\", \"002\", \"0020\", \"00209\".In the first sample the city phone code is string \"00\".In the second sample the city phone code is an empty string.In the third sample the city phone code is string \"770123456789\"."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "081b35620952bd32ce6d8ddc756e5c9d"} {"nl": {"description": "When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type \u2014 if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!", "input_spec": "The first line of the input contains three space-separated numbers, n, m and k (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u200918, 0\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009*\u2009(n\u2009-\u20091)) \u2014 the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, 0\u2009\u2264\u2009ci\u2009\u2264\u2009109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009k), that xi\u2009=\u2009xj and yi\u2009=\u2009yj.", "output_spec": "In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.", "sample_inputs": ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"], "sample_outputs": ["3", "12"], "notes": "NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5."}, "positive_code": [{"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 var (n, m, k) = (0, 0, 0)\n var a: Array[Int] = null\n var mat: Array[Array[Int]] = null\n var f: Array[Array[Long]] = null\n \n def main(args: Array[String]): Unit = {\n n = in.nextInt\n m = in.nextInt\n k = in.nextInt\n \n a = new Array[Int](n + 1)\n \n for (i <- 0 until n) {\n a(i) = in.nextInt\n }\n \n mat = ofDim(n, n)\n f = ofDim((1 << n), n)\n \n for (i <- 1 to k) {\n val (x, y, c) = (in.nextInt - 1, in.nextInt - 1, in.nextInt)\n mat(x)(y) = c\n }\n \n for (i <- 0 until n) {\n f(1 << i)(i) = a(i)\n }\n \n \n \n for (mask <- 1 until (1 << n)) {\n for (x <- 0 until n) {\n if ((mask & (1 << x)) != 0) {\n for (y <- 0 until n) {\n if ((mask & (1 << y)) == 0) {\n val t = f(mask)(x) + a(y) + mat(x)(y)\n if (t > f(mask | (1 << y))(y)) f(mask | (1 << y))(y) = t\n }\n }\n }\n }\n }\n \n var result = 0L\n \n for (mask <- 0 until (1 << n)) {\n var cnt = 0\n var x = mask\n while (x > 0) {\n cnt += 1\n x &= x - 1\n }\n if (cnt == m) {\n for (x <- 0 until n) {\n if ((mask & (1 << x)) != 0) result = math.max(result, f(mask)(x))\n }\n }\n }\n \n out.println(result)\n \n out.close\n }\n}"}], "negative_code": [], "src_uid": "5b881f1cd74b17358b954299c2742bdf"} {"nl": {"description": "So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal \u2014 their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city \u2014 that's the strategy the flatlanders usually follow when they besiege cities.The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r\u2009\u2265\u20090) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range \u2014 as a disk (including the border) with the center at the point where the radar is placed.", "input_spec": "The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|,\u2009|yi|\u2009\u2264\u2009104;\u00a01\u2009\u2264\u2009ri\u2009\u2264\u2009104) \u2014 the city's coordinates and the distance from the city to the flatlanders, correspondingly. It is guaranteed that the cities are located at different points.", "output_spec": "Print a single real number \u2014 the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10\u2009-\u20096.", "sample_inputs": ["0 0 1\n6 0 3", "-10 10 3\n10 -10 3"], "sample_outputs": ["1.000000000000000", "11.142135623730951"], "notes": "NoteThe figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2,\u20090). The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0,\u20090). "}, "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"}, {"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}"}], "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"} {"nl": {"description": "Recently, the students of School 179 have developed a unique algorithm, which takes in a binary string $$$s$$$ as input. However, they soon found out that if some substring $$$t$$$ of $$$s$$$ is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of $$$s$$$ so that the algorithm will work correctly on the string?A binary string is a string where each character is either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A palindrome is a string that reads the same backwards as forwards.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.", "output_spec": "For each test case, print YES (case-insensitive) if it is possible to reorder the characters of $$$s$$$ so that there are no substrings that are a palindrome of length greater than 1, or NO (case-insensitive) otherwise.", "sample_inputs": ["4\n\n1\n\n1\n\n2\n\n10\n\n2\n\n01\n\n4\n\n1010"], "sample_outputs": ["YES\nYES\nYES\nNO"], "notes": "NoteIn the first three test cases, the given strings do not contain palindromes of length greater than 1, so the answers are YES.In the last test case, it is impossible to reorder the characters so that the string does not contain palindromes of length greater than 1, so the answer is NO."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $$$n$$$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $$$i$$$-th from the left sushi as $$$t_i$$$, where $$$t_i = 1$$$ means it is with tuna, and $$$t_i = 2$$$ means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $$$[2, 2, 2, 1, 1, 1]$$$ is valid, but subsegment $$$[1, 2, 1, 2, 1, 2]$$$ is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100\\,000$$$)\u00a0\u2014 the number of pieces of sushi. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$t_i = 1$$$, denoting a sushi with tuna or $$$t_i = 2$$$, denoting a sushi with eel), representing the types of sushi from left to right. It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.", "output_spec": "Print a single integer\u00a0\u2014 the maximum length of a valid continuous segment.", "sample_inputs": ["7\n2 2 2 1 1 2 2", "6\n1 2 1 2 1 2", "9\n2 2 1 1 1 2 2 2 2"], "sample_outputs": ["4", "2", "6"], "notes": "NoteIn the first example Arkady can choose the subsegment $$$[2, 2, 1, 1]$$$ or the subsegment $$$[1, 1, 2, 2]$$$ with length $$$4$$$.In the second example there is no way but to choose one of the subsegments $$$[2, 1]$$$ or $$$[1, 2]$$$ with length $$$2$$$.In the third example Arkady's best choice is the subsegment $$$[1, 1, 1, 2, 2, 2]$$$."}, "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) :+ 0\n var tpe = 0\n var cnt = 0\n var prevCnt = 0\n var ans = 0\n REP(N + 1) { i =>\n if (A(i) == tpe) {\n cnt += 1\n } else {\n ans = max(ans, min(prevCnt, cnt) * 2)\n tpe = A(i)\n prevCnt = cnt\n cnt = 1\n }\n }\n\n out.println(ans)\n }\n\n private val oj = System.getProperty(\"ONLINE_JUDGE\") != null ||\n 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": "6477fdad8455f57555f93c021995bb4d"} {"nl": {"description": "You have a permutation: an array $$$a = [a_1, a_2, \\ldots, a_n]$$$ of distinct integers from $$$1$$$ to $$$n$$$. The length of the permutation $$$n$$$ is odd.Consider the following algorithm of sorting the permutation in increasing order.A helper procedure of the algorithm, $$$f(i)$$$, takes a single argument $$$i$$$ ($$$1 \\le i \\le n-1$$$) and does the following. If $$$a_i > a_{i+1}$$$, the values of $$$a_i$$$ and $$$a_{i+1}$$$ are exchanged. Otherwise, the permutation doesn't change.The algorithm consists of iterations, numbered with consecutive integers starting with $$$1$$$. On the $$$i$$$-th iteration, the algorithm does the following: if $$$i$$$ is odd, call $$$f(1), f(3), \\ldots, f(n - 2)$$$; if $$$i$$$ is even, call $$$f(2), f(4), \\ldots, f(n - 1)$$$. It can be proven that after a finite number of iterations the permutation will be sorted in increasing order.After how many iterations will this happen for the first time?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 999$$$; $$$n$$$ is odd)\u00a0\u2014 the length of the permutation. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the permutation itself. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$999$$$.", "output_spec": "For each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time. If the given permutation is already sorted, print $$$0$$$.", "sample_inputs": ["3\n3\n3 2 1\n7\n4 5 7 1 3 2 6\n5\n1 2 3 4 5"], "sample_outputs": ["3\n5\n0"], "notes": "NoteIn the first test case, the permutation will be changing as follows: after the $$$1$$$-st iteration: $$$[2, 3, 1]$$$; after the $$$2$$$-nd iteration: $$$[2, 1, 3]$$$; after the $$$3$$$-rd iteration: $$$[1, 2, 3]$$$. In the second test case, the permutation will be changing as follows: after the $$$1$$$-st iteration: $$$[4, 5, 1, 7, 2, 3, 6]$$$; after the $$$2$$$-nd iteration: $$$[4, 1, 5, 2, 7, 3, 6]$$$; after the $$$3$$$-rd iteration: $$$[1, 4, 2, 5, 3, 7, 6]$$$; after the $$$4$$$-th iteration: $$$[1, 2, 4, 3, 5, 6, 7]$$$; after the $$$5$$$-th iteration: $$$[1, 2, 3, 4, 5, 6, 7]$$$. In the third test case, the permutation is already sorted and the answer is $$$0$$$."}, "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": "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"}, {"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"} {"nl": {"description": "Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.Mike has $$$n$$$ sweets with sizes $$$a_1, a_2, \\ldots, a_n$$$. All his sweets have different sizes. That is, there is no such pair $$$(i, j)$$$ ($$$1 \\leq i, j \\leq n$$$) such that $$$i \\ne j$$$ and $$$a_i = a_j$$$.Since Mike has taught for many years, he knows that if he gives two sweets with sizes $$$a_i$$$ and $$$a_j$$$ to one child and $$$a_k$$$ and $$$a_p$$$ to another, where $$$(a_i + a_j) \\neq (a_k + a_p)$$$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\leq n \\leq 1\\,000$$$)\u00a0\u2014 the number of sweets Mike has. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^5$$$)\u00a0\u2014 the sizes of the sweets. It is guaranteed that all integers are distinct.", "output_spec": "Print one integer\u00a0\u2014 the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.", "sample_inputs": ["8\n1 8 3 11 4 9 2 7", "7\n3 1 7 11 9 2 12"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first example, Mike can give $$$9+2=11$$$ to one child, $$$8+3=11$$$ to another one, and $$$7+4=11$$$ to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.In the second example, Mike can give $$$3+9=12$$$ to one child and $$$1+11$$$ to another one. Therefore, Mike can invite two children. Note that it is not the only solution."}, "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)\n\n // \u91cd\u8907\u30ab\u30a6\u30f3\u30c8\u3057\u306a\u3044\u306e\u3067\u5358\u7d14\u306b\u5168\u7d44\u307f\u5408\u308f\u305b\n val C = Array.ofDim[Int](2e5.toInt + 1)\n REP(N - 1) { i =>\n TO(i + 1, N - 1) { j =>\n C(A(i) + A(j)) += 1\n }\n }\n\n val ans = C.max\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": [], "src_uid": "44619ba06ec0dc410ef598ea45a76271"} {"nl": {"description": "There are $$$n$$$ piles of sand where the $$$i$$$-th pile has $$$a_i$$$ blocks of sand. The $$$i$$$-th pile is called too tall if $$$1 < i < n$$$ and $$$a_i > a_{i-1} + a_{i+1}$$$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)You are given an integer $$$k$$$. An operation consists of picking $$$k$$$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $$$1 \\leq l,r \\leq n$$$ such that $$$r-l+1=k$$$. Then for all $$$l \\leq i \\leq r$$$, update $$$a_i \\gets a_i+1$$$.What is the maximum number of piles that can simultaneously be too tall after some (possibly zero) operations?", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \\leq n \\leq 2 \\cdot 10^5$$$; $$$1 \\leq k \\leq n$$$)\u00a0\u2014 the number of piles of sand and the size of the operation, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the sizes of the piles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the maximum number of piles that are simultaneously too tall after some (possibly zero) operations.", "sample_inputs": ["3\n\n5 2\n\n2 9 2 4 1\n\n4 4\n\n1 3 2 1\n\n3 1\n\n1 3 1"], "sample_outputs": ["2\n0\n1"], "notes": "NoteIn the first test case, we can perform the following three operations: Add one unit of sand to piles $$$1$$$ and $$$2$$$: $$$[\\color{red}{3}, \\color{red}{10}, 2, 4, 1]$$$. Add one unit of sand to piles $$$4$$$ and $$$5$$$: $$$[3, 10, 2, \\color{red}{5}, \\color{red}{2}]$$$. Add one unit of sand to piles $$$3$$$ and $$$4$$$: $$$[3, 10, \\color{red}{3}, \\color{red}{6}, 2]$$$. Now piles $$$2$$$ and $$$4$$$ are too tall, so in this case the answer is $$$2$$$. It can be shown that it is impossible to make more than $$$2$$$ piles too tall.In the second test case, any operation will increase all piles by $$$1$$$ unit, so the number of too tall piles will always be $$$0$$$.In the third test case, we can increase any pile by $$$1$$$ unit of sand. It can be shown that the maximum number of too tall piles is $$$1$$$."}, "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\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 k = tokenizer.nextToken().toInt\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val A = ListBuffer.empty[Int]\r\n for (i <- 1 to n)\r\n A+= tokenizer.nextToken().toInt\r\n val B = A.toArray\r\n var c = 0\r\n if (k!=1) {\r\n for (i <- B.indices) {\r\n if ((i > 0) & ( i < B.length-1)){\r\n if (B(i) > B(i-1) + B(i+1)) {\r\n c+=1\r\n }\r\n }\r\n }\r\n println(c)\r\n }\r\n else {\r\n println((n - 1) /2)\r\n }\r\n }\r\n }\r\n\r\n\r\n}"}], "negative_code": [], "src_uid": "4d5d20fd586ddbea2adeab104a6c2aec"} {"nl": {"description": "After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant\u2019s sentences, Yash determined a new cipher technique.For a given sentence, the cipher is processed as: Convert all letters of the sentence to lowercase. Reverse each of the words of the sentence individually. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentenceKira is childish and he hates losingthe resulting string isariksihsidlihcdnaehsetahgnisolNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000)\u00a0\u2014 the length of the ciphered text. The second line consists of n lowercase English letters\u00a0\u2014 the ciphered text t. The third line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi|\u2009\u2264\u20091\u2009000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1\u2009000\u2009000.", "output_spec": "Print one line \u2014 the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.", "sample_inputs": ["30\nariksihsidlihcdnaehsetahgnisol\n10\nKira\nhates\nis\nhe\nlosing\ndeath\nchildish\nL\nand\nNote", "12\niherehtolleh\n5\nHI\nHo\nthere\nHeLLo\nhello"], "sample_outputs": ["Kira is childish and he hates losing", "HI there HeLLo"], "notes": "NoteIn sample case 2 there may be multiple accepted outputs, \"HI there HeLLo\" and \"HI there hello\" you may output any of them. "}, "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"}, {"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"}], "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"} {"nl": {"description": "Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \\times n$$$. Alice has a single piece left\u00a0\u2014 a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself\u00a0\u2014 he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 1000$$$)\u00a0\u2014 the dimensions of the chessboard. The second line contains two integers $$$a_x$$$ and $$$a_y$$$ ($$$1 \\leq a_x, a_y \\leq n$$$)\u00a0\u2014 the coordinates of Alice's queen. The third line contains two integers $$$b_x$$$ and $$$b_y$$$ ($$$1 \\leq b_x, b_y \\leq n$$$)\u00a0\u2014 the coordinates of Bob's king. The fourth line contains two integers $$$c_x$$$ and $$$c_y$$$ ($$$1 \\leq c_x, c_y \\leq n$$$)\u00a0\u2014 the coordinates of the location that Bob wants to get to. It is guaranteed that Bob's king is currently not in check and the target location is not in check either. Furthermore, the king is not located on the same square as the queen (i.e. $$$a_x \\neq b_x$$$ or $$$a_y \\neq b_y$$$), and the target does coincide neither with the queen's position (i.e. $$$c_x \\neq a_x$$$ or $$$c_y \\neq a_y$$$) nor with the king's position (i.e. $$$c_x \\neq b_x$$$ or $$$c_y \\neq b_y$$$).", "output_spec": "Print \"YES\" (without quotes) if Bob can get from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check, otherwise print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["8\n4 4\n1 3\n3 1", "8\n4 4\n2 3\n1 6", "8\n3 5\n1 2\n6 1"], "sample_outputs": ["YES", "NO", "NO"], "notes": "NoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares $$$(2, 3)$$$ and $$$(3, 2)$$$. Note that the direct route through $$$(2, 2)$$$ goes through check. In the second case, the queen watches the fourth rank, and the king has no means of crossing it. In the third case, the queen watches the third file. "}, "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 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"}, {"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"} {"nl": {"description": "You are given a binary matrix $$$A$$$ of size $$$n \\times n$$$. Let's denote an $$$x$$$-compression of the given matrix as a matrix $$$B$$$ of size $$$\\frac{n}{x} \\times \\frac{n}{x}$$$ such that for every $$$i \\in [1, n], j \\in [1, n]$$$ the condition $$$A[i][j] = B[\\lceil \\frac{i}{x} \\rceil][\\lceil \\frac{j}{x} \\rceil]$$$ is met.Obviously, $$$x$$$-compression is possible only if $$$x$$$ divides $$$n$$$, but this condition is not enough. For example, the following matrix of size $$$2 \\times 2$$$ does not have any $$$2$$$-compression: $$$01$$$ $$$10$$$ For the given matrix $$$A$$$, find maximum $$$x$$$ such that an $$$x$$$-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.", "input_spec": "The first line contains one number $$$n$$$ ($$$4 \\le n \\le 5200$$$) \u2014 the number of rows and columns in the matrix $$$A$$$. It is guaranteed that $$$n$$$ is divisible by $$$4$$$. Then the representation of matrix follows. Each of $$$n$$$ next lines contains $$$\\frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are 1011, and if the number is $$$5$$$, then the corresponding elements are 0101. Elements are not separated by whitespaces.", "output_spec": "Print one number: maximum $$$x$$$ such that an $$$x$$$-compression of the given matrix is possible.", "sample_inputs": ["8\nE7\nE7\nE7\n00\n00\nE7\nE7\nE7", "4\n7\nF\nF\nF"], "sample_outputs": ["1", "1"], "notes": "NoteThe first example corresponds to the matrix: $$$11100111$$$ $$$11100111$$$ $$$11100111$$$ $$$00000000$$$ $$$00000000$$$ $$$11100111$$$ $$$11100111$$$ $$$11100111$$$ It is easy to see that the answer on this example is $$$1$$$."}, "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 val HEX = Array.ofDim[Int](128)\n REP(10) { i =>\n HEX('0' + i) = i\n }\n REP(6) { i =>\n HEX('A' + i) = i + 10\n }\n\n def solve(): Unit = {\n import java.util\n val N = ni()\n val cum = Array.ofDim[Int](N + 1, N + 1)\n// val M = Array.ofDim[Boolean](N, N)\n REP(N) { i =>\n val hex = ns()\n REP(N / 4) { j =>\n val bits = HEX(hex(j))\n REP(4) { k =>\n if ((bits & (1 << (3 - k))) > 0) cum(i + 1)(j * 4 + k + 1) = 1\n }\n }\n }\n// REP(N) { i =>\n// debug(M(i))\n// }\n\n val d = divisors(N)\n// debug(d)\n\n// val cum = Array.ofDim[Int](N + 1, N + 1)\n// REP(N) { i =>\n// REP(N) { j =>\n// if (M(i)(j)) cum(i + 1)(j + 1) = 1\n// }\n// }\n\n REP(N + 1) { i =>\n REP(N) { j =>\n cum(i)(j + 1) += cum(i)(j)\n }\n }\n\n REP(N + 1) { i =>\n REP(N) { j =>\n cum(j + 1)(i) += cum(j)(i)\n }\n }\n\n// REP(N + 1) { i =>\n// debug(cum(i))\n// }\n\n // [(r0, c0), (r1, c1))\n def count(r0: Int, c0: Int, r1: Int, c1: Int): Int = {\n cum(r1)(c1) + cum(r0)(c0) - cum(r1)(c0) - cum(r0)(c1)\n }\n\n def valid(x: Int): Boolean = {\n val sum = x * x\n\n REP(N / x) { i =>\n REP(N / x) { j =>\n val cnt = count(i * x, j * x, (i + 1) * x, (j + 1) * x)\n if (cnt != 0 && cnt != sum) return false\n }\n }\n\n true\n }\n\n var ans = 1\n REP_r(d.length - 1, 1) { i =>\n if (valid(d(i))) {\n ans = max(ans, d(i))\n }\n }\n\n out.println(ans)\n }\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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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 val HEX = Array.ofDim[Int](128)\n REP(10) { i =>\n HEX('0' + i) = i\n }\n REP(6) { i =>\n HEX('A' + i) = i + 10\n }\n\n def solve(): Unit = {\n val N = ni()\n val M = Array.ofDim[Boolean](N, N)\n REP(N) { i =>\n val hex = ns()\n REP(N / 4) { j =>\n val bits = HEX(hex(j))\n REP(4) { k =>\n M(i)(j * 4 + k) = (bits & (1 << (3 - k))) > 0\n }\n }\n }\n// REP(N) { i =>\n// debug(M(i))\n// }\n\n val d = divisors(N)\n// debug(d)\n\n // \u7e26\u3001\u6a2a\u306e1\u306e\u6570\n val V, H = Array.ofDim[Int](N)\n REP(N) { i =>\n REP(N) { j =>\n if (M(i)(j)) {\n V(i) += 1\n H(j) += 1\n }\n }\n }\n\n// debug(V)\n// debug(H)\n\n def valid(x: Int) = {\n // \u5727\u7e2e\u3055\u308c\u308b\u30d6\u30ed\u30c3\u30af\u306e\u30b5\u30a4\u30ba\n val sum = x * x\n\n var ok = true\n\n // \u5404\u5217\u3001\u884c\u306fx\u306e\u500d\u6570\n REP(N) { i =>\n ok &&= V(i) % x == 0 && H(i) % x == 0\n }\n\n // \u5727\u7e2e\u4e88\u5b9a\u306e\u5404\u5217\u3001\u5404\u884c\u3092\u8db3\u3057\u305f\u3082\u306e\u306fsum\u306e\u500d\u6570\n REP(N / x) { i =>\n var v, h = 0\n REP(x) { j =>\n v += V(i * x + j)\n h += H(i * x + j)\n }\n ok &&= v % sum == 0 && h % sum == 0\n }\n ok\n }\n\n var ans = 1\n REP_r(d.length - 1, 1) { i =>\n if (valid(d(i))) {\n ans = max(ans, d(i))\n }\n }\n\n out.println(ans)\n }\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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "31d95251cd79d889ff9f0a624ef31394"} {"nl": {"description": "You are given a positive decimal number x.Your task is to convert it to the \"simple exponential notation\".Let x\u2009=\u2009a\u00b710b, where 1\u2009\u2264\u2009a\u2009<\u200910, then in general case the \"simple exponential notation\" looks like \"aEb\". If b equals to zero, the part \"Eb\" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.", "input_spec": "The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types \"float\", \"double\" and other.", "output_spec": "Print the only line \u2014 the \"simple exponential notation\" of the given number x.", "sample_inputs": ["16", "01.23400", ".100", "100."], "sample_outputs": ["1.6E1", "1.234", "1E-1", "1E2"], "notes": null}, "positive_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(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}"}, {"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"} {"nl": {"description": "A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v,\u2009u).A parent of vertex v in the rooted tree with the root in vertex r (v\u2009\u2260\u2009r) is vertex pv, such that d(r,\u2009pv)\u2009+\u20091\u2009=\u2009d(r,\u2009v) and d(pv,\u2009v)\u2009=\u20091. For example, on the picture the parent of vertex v\u2009=\u20095 is vertex p5\u2009=\u20092.One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1\u2009<\u2009v\u2009\u2264\u2009n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7=\"ba\". The characters in the strings are numbered starting from 0. An example of Polycarpus's tree (corresponds to the example from the statement) Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v,\u2009x) that means that the position is the x-th letter of the string sv (1\u2009<\u2009v\u2009\u2264\u2009n, 0\u2009\u2264\u2009x\u2009<\u2009|sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2,\u20091) and (3,\u20091).Let's consider the pair of positions (v,\u2009x) and (u,\u2009y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v,\u2009x) to (u,\u2009y), written in the order of this path. For example, in the picture the highlighted positions define string \"bacaba\".Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of vertices of Polycarpus's tree. Next n\u2009-\u20091 lines contain the tree edges. The i-th of them contains number pi\u2009+\u20091 and string si\u2009+\u20091 (1\u2009\u2264\u2009pi\u2009+\u20091\u2009\u2264\u2009n;\u00a0pi\u2009+\u20091\u2009\u2260\u2009(i\u2009+\u20091)). String si\u2009+\u20091 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2. It is guaranteed that the input contains at most 3\u00b7105 English letters.", "output_spec": "Print a single integer \u2014 the required number. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["7\n1 ab\n5 bacaba\n1 abacaba\n2 aca\n5 ba\n2 ba\naba", "7\n1 ab\n5 bacaba\n1 abacaba\n2 aca\n5 ba\n2 ba\nbacaba"], "sample_outputs": ["6", "4"], "notes": "NoteIn the first test case string \"aba\" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.", "input_spec": "The first line of the input contains integers n and m (3\u2009\u2264\u2009n\u2009\u2264\u200948, . Then follow m lines, each contains a pair of integers ai,\u2009bi (1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009n) \u2014 the pair ai,\u2009bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai,\u2009bi occurs in the input at most once.", "output_spec": "If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1\u2009\u2264\u2009xi,\u2009yi,\u2009zi\u2009\u2264\u2009n) \u2014 the i-th team. If there are multiple answers, you are allowed to print any of them.", "sample_inputs": ["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"], "sample_outputs": ["3 2 1", "-1", "3 2 1"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.mutable.Set\n\nobject B {\n \n def ma(n:Int, M:List[(Int,Int)], x:Int):Set[Int] = {\n var R:Set[Int] = Set(x)\n for(i <- 0 until n) {\n for(p <- M) {\n if(R.contains(p._1) || R.contains(p._2)){\n R = R union Set(p._1, p._2)\n } \n }\n }\n R\n }\n\n def pr(L:List[Int]) = {\n for(x<-L)print((x+1)+\" \")\n\tprintln\n }\n \n def solve(n: Int, M: List[(Int, Int)]): List[List[Int]] = {\n var R: List[List[Int]] = List()\n val U = Array.fill(n)(false)\n var left:Set[Int] = Set()\n for (i <- 0 until n) {\n if (!U(i)) {\n val S = ma(n, M, i);\n if (S.size > 3) return null\n if (S.size == 1)left += i\n else {\n S.foreach( x=>U(x) = true)\n R = S.toList :: R\n }\n }\n }\n if(R.length>n/3)return null\n while(R.length < n/3)R=List()::R\n val it = left.iterator\n for(L<-R){\n var rl = L\n while(rl.length<3){\n rl = it.next ::rl\n }\n pr(rl)\n }\n R\n }\n def main(args: Array[String]) {\n\t var scan = new Scanner(System.in)\n\t val n = scan.nextInt;val m = scan.nextInt\n\t val M = List.fill(m)((scan.nextInt-1, scan.nextInt-1))\n\t val R = solve(n,M)\n\t if (R==null)println(-1)\n }\n}\n\n"}], "negative_code": [], "src_uid": "46e7cd6723553d2c6d6c6d0999a5b5fc"} {"nl": {"description": "Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i\u2009+\u20091, that is, the prices of the jewelry are 2,\u20093,\u20094,\u2009... n\u2009+\u20091.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.", "input_spec": "The only line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000)\u00a0\u2014 the number of jewelry pieces.", "output_spec": "The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.", "sample_inputs": ["3", "4"], "sample_outputs": ["2\n1 1 2", "2\n2 1 1 2"], "notes": "NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given n rectangles, labeled 1 through n. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).Your task is to determine if there's a non-empty subset of the rectangles that forms a square. That is, determine if there exists a subset of the rectangles and some square for which every point that belongs to the interior or the border of that square belongs to the interior or the border of at least one of the rectangles in the subset, and every point that belongs to the interior or the border of at least one rectangle in the subset belongs to the interior or the border of that square.", "input_spec": "First line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of rectangles. Each of the next n lines contains a description of a rectangle, with the i-th such line describing the rectangle labeled i. Each rectangle description consists of four integers: x1, y1, x2, y2 \u2014 coordinates of the bottom left and the top right corners (0\u2009\u2264\u2009x1\u2009<\u2009x2\u2009\u2264\u20093000, 0\u2009\u2264\u2009y1\u2009<\u2009y2\u2009\u2264\u20093000). No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle).", "output_spec": "If such a subset exists, print \"YES\" (without quotes) on the first line of the output file, followed by k, the number of rectangles in the subset. On the second line print k numbers \u2014 the labels of rectangles in the subset in any order. If more than one such subset exists, print any one. If no such subset exists, print \"NO\" (without quotes).", "sample_inputs": ["9\n0 0 1 9\n1 0 9 1\n1 8 9 9\n8 1 9 8\n2 2 3 6\n3 2 7 3\n2 6 7 7\n5 3 7 6\n3 3 5 6", "4\n0 0 1 9\n1 0 9 1\n1 8 9 9\n8 1 9 8"], "sample_outputs": ["YES 5\n5 6 7 8 9", "NO"], "notes": "NoteThe first test case looks as follows: Note that rectangles 6, 8, and 9 form a square as well, and would be an acceptable answer.The second test case looks as follows: "}, "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 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}"}, {"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}"}, {"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"} {"nl": {"description": "Mihai has an $$$8 \\times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 36$$$)\u00a0\u2014 the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.", "output_spec": "For each test case, output two integers $$$r$$$ and $$$c$$$ ($$$2 \\leq r, c \\leq 7$$$)\u00a0\u2014 the row and column of the bishop. The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.", "sample_inputs": ["3\n\n\n\n\n.....#..\n\n#...#...\n\n.#.#....\n\n..#.....\n\n.#.#....\n\n#...#...\n\n.....#..\n\n......#.\n\n\n\n\n#.#.....\n\n.#......\n\n#.#.....\n\n...#....\n\n....#...\n\n.....#..\n\n......#.\n\n.......#\n\n\n\n\n.#.....#\n\n..#...#.\n\n...#.#..\n\n....#...\n\n...#.#..\n\n..#...#.\n\n.#.....#\n\n#......."], "sample_outputs": ["4 3\n2 2\n4 5"], "notes": "NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row $$$4$$$ and column $$$3$$$, the correct output is 4 3."}, "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 StdIn.readLine()\r\n val chessboard = for (_ <- 0 until 8) yield {\r\n StdIn.readLine().split(\"\").map(x =>\r\n if (x == \"#\") {\r\n true\r\n } else {\r\n false\r\n }\r\n )\r\n }\r\n\r\n for(i <- 0 until 8) {\r\n for(j <- 0 until 8) {\r\n if(lookup(chessboard, i, j) && lookup(chessboard, i - 1, j - 1) && lookup(chessboard, i - 1, j + 1) && lookup(chessboard, i + 1, j + 1) && lookup(chessboard, i + 1, j - 1)) {\r\n println(s\"${i + 1} ${j + 1}\")\r\n }\r\n }\r\n }\r\n\r\n }\r\n }\r\n\r\n def lookup(seq: Seq[Array[Boolean]], i: Int, j: Int): Boolean = {\r\n if(i < 8 && i >= 0 && j < 8 && j >= 0) {\r\n seq(i)(j)\r\n } else {\r\n false\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "b0f968ca75fbea2f11a7e4b9006f136e"} {"nl": {"description": "You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k < n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.", "sample_inputs": ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"], "sample_outputs": ["10\n0"], "notes": null}, "positive_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(_.toLong).sorted\n val sum: Long = barrels.takeRight(r + 1).sum\n println(sum)\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"}, {"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"}], "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"} {"nl": {"description": "Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.", "input_spec": "The first line of input contains two integers n and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009300\u2009000)\u00a0\u2014 the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typei\u00a0\u2014 type of the i-th event. If typei\u2009=\u20091 or typei\u2009=\u20092 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1\u2009\u2264\u2009typei\u2009\u2264\u20093,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009ti\u2009\u2264\u2009q).", "output_spec": "Print the number of unread notifications after each event.", "sample_inputs": ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"], "sample_outputs": ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"], "notes": "NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). "}, "positive_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 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\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}"}, {"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": "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"} {"nl": {"description": "Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form \"reader entered room\", \"reader left room\". Every reader is assigned a registration number during the registration procedure at the library \u2014 it's a unique integer from 1 to 106. Thus, the system logs events of two forms: \"+ ri\" \u2014 the reader with registration number ri entered the room; \"- ri\" \u2014 the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as \"+ ri\" or \"- ri\", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.", "output_spec": "Print a single integer \u2014 the minimum possible capacity of the reading room.", "sample_inputs": ["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"], "sample_outputs": ["3", "2", "1"], "notes": "NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3."}, "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 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"}, {"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"} {"nl": {"description": "There is an array with n elements a1,\u2009a2,\u2009...,\u2009an and the number x.In one operation you can select some i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) and replace element ai with ai\u2009&\u2009x, where & denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i\u2009\u2260\u2009j such that ai\u2009=\u2009aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.", "input_spec": "The first line contains integers n and x (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009x\u2009\u2264\u2009100\u2009000), number of elements in the array and the number to and with. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009100\u2009000), the elements of the array.", "output_spec": "Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.", "sample_inputs": ["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"], "sample_outputs": ["1", "0", "-1"], "notes": "NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility). Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.", "input_spec": "The first line of input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009104) \u2014 number of universes and number of groups respectively. The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k\u2009>\u20090) followed by k integers vi,\u20091,\u2009vi,\u20092,\u2009...,\u2009vi,\u2009k. If vi,\u2009j is negative, it means that Rick from universe number \u2009-\u2009vi,\u2009j has joined this group and otherwise it means that Morty from universe number vi,\u2009j has joined it. Sum of k for all groups does not exceed 104.", "output_spec": "In a single line print the answer to Summer's question. Print \"YES\" if she should cancel the event and \"NO\" otherwise.", "sample_inputs": ["4 2\n1 -3\n4 -2 3 2 -3", "5 2\n5 3 -2 1 -1 5\n3 -5 2 5", "7 2\n3 -1 6 7\n7 -5 4 2 4 7 -3 4"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event."}, "positive_code": [{"source_code": "object _787B 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 groups = read[Seq[Set[Int]]]\n val ans = groups.exists({group =>\n val g2: Set[Int] = group.map(_.abs)\n g2.size == group.size\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 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": "f110b9351fe8ff20676d11ecfc92aee3"} {"nl": {"description": "Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1,\u2009...,\u20092ak if and only if there exists a non-negative integer x such that 2a1\u2009+\u20092a2\u2009+\u2009...\u2009+\u20092ak\u2009=\u20092x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. ", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106), the number of weights. The second line contains n integers w1,\u2009...,\u2009wn separated by spaces (0\u2009\u2264\u2009wi\u2009\u2264\u2009106 for each 1\u2009\u2264\u2009i\u2009\u2264\u2009n), the powers of two forming the weights values.", "output_spec": "Print the minimum number of steps in a single line.", "sample_inputs": ["5\n1 1 2 3 3", "4\n0 1 2 3"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two."}, "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\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}"}, {"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"} {"nl": {"description": "As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k.", "input_spec": "The first line contains three space-separated integers n,\u2009m,\u2009k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009105, 1\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n,\u2009a\u2009\u2260\u2009b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.", "output_spec": "Print the single number \u2014 the answer to the problem modulo k.", "sample_inputs": ["2 0 1000000000", "3 0 100", "4 1 1000000000\n1 4"], "sample_outputs": ["1", "3", "8"], "notes": "NoteThe first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime \u2014 there are 3 ways to do it.The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime."}, "positive_code": [{"source_code": "//package round110.div1\n\n//package round110.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 05.03.12\n * Time: 6:21\n * To change this template use File | Settings | File Templates.\n */\n\nobject D {\n val Array(evidCount, refCount, mod) = readLine split ' ' map (_ toInt)\n var all: List[Evidence] = Nil\n val evid = Array.ofDim[Evidence](evidCount)\n\n for (_ <- 1 to refCount) readLine split ' ' map (_ toInt) match {\n case Array(left, right) => evidence(left) refer evidence(right)\n }\n val result = {\n val setNums = all filter (_ isMain) map (_.count.toLong)\n\n if (setNums.length + evidCount - all.length == 1) 1 % mod\n else {\n val mull = setNums match {\n case Nil => 1\n case List(a) => a\n case list => list reduce ((left, right) => (left * right) % mod)\n }\n val summ = fastPow(evidCount, setNums.length + evidCount - all.length - 2)\n (mull.toLong * summ) % mod\n }\n }\n\n\n def main(args: Array[String]) = println(result)\n\n def fastPow(base: Int, pow: Int): Int = {\n if (base == 1) return 1\n var acc = 1L\n var mul = base toLong\n var bit = 1L\n while (bit <= pow) {\n if ((pow & bit) != 0) acc = (acc * mul) % mod\n mul = (mul * mul) % mod\n bit <<= 1\n }\n return acc toInt\n }\n\n\n def evidence(index: Int) = {\n evid(index - 1) match {\n case null => {\n val created = new Evidence\n evid(index - 1) = created\n created\n }\n case existing => existing\n }\n }\n\n class Evidence {\n private var parent = this\n private var rank = 0\n private[this] var _count: Int = 1\n\n def count = _count\n\n private def count_=(count: Int) = _count = count\n\n\n all ::= this\n\n def main: Evidence = {\n if (this.parent != this) this.parent = this.parent main;\n this.parent\n }\n\n def isMain = this.parent == this\n\n def absorb(that: Evidence) {\n count += that.count\n that.parent = this\n if (this.rank == that.rank) this.rank += 1\n }\n\n def refer(that: Evidence) {\n val thisMain = this main;\n val thatMain = that main;\n if (thisMain == thatMain) return;\n if (thisMain.rank <= thatMain.rank) thatMain absorb thisMain\n else thisMain absorb thatMain\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//package round110.div1\n\n//package round110.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 05.03.12\n * Time: 6:21\n * To change this template use File | Settings | File Templates.\n */\n\nobject D {\n val Array(evidCount, refCount, mod) = readLine split ' ' map (_ toInt)\n var all: List[Evidence] = Nil\n val evid = Array.ofDim[Evidence](evidCount)\n\n for (_ <- 1 to refCount) readLine split ' ' map (_ toInt) match {\n case Array(left, right) => evidence(left) refer evidence(right)\n }\n\n val setNums = all filter (_ isMain) map (_.count.toLong)\n val mull = setNums match {\n case Nil => 1\n case List(a) => a\n case list => list reduce ((left, right) => (left * right) % mod)\n }\n val summ = fastPow(evidCount, setNums.length + evidCount - all.length - 2)\n val result = (mull.toLong * summ) % mod\n\n def main(args: Array[String]) = println(result)\n\n def fastPow(base: Int, pow: Int): Int = {\n if (base == 1) return 1\n var acc = 1L\n var mul = base toLong\n var bit = 1L\n while (bit <= pow) {\n if ((pow & bit) != 0) acc = (acc * mul) % mod\n mul = (mul * mul) % mod\n bit <<= 1\n }\n return acc toInt\n }\n\n\n def evidence(index: Int) = {\n evid(index - 1) match {\n case null => {\n val created = new Evidence\n evid(index - 1) = created\n created\n }\n case existing => existing\n }\n }\n\n class Evidence {\n private var parent = this\n private var rank = 0\n private[this] var _count: Int = 1\n\n def count = _count\n\n private def count_=(count: Int) = _count = count\n\n\n all ::= this\n\n def main: Evidence = {\n if (this.parent != this) this.parent = this.parent main;\n this.parent\n }\n\n def isMain = this.parent == this\n\n def absorb(that: Evidence) {\n count += that.count\n that.parent = this\n if (this.rank == that.rank) this.rank += 1\n }\n\n def refer(that: Evidence) {\n val thisMain = this main;\n val thatMain = that main;\n if (thisMain == thatMain) return;\n if (thisMain.rank <= thatMain.rank) thatMain absorb thisMain\n else thisMain absorb thatMain\n }\n }\n\n}\n"}, {"source_code": "//package round110.div1\n\n//package round110.div2\n\n/**\n * Created by IntelliJ IDEA.\n * User: User\n * Date: 05.03.12\n * Time: 6:21\n * To change this template use File | Settings | File Templates.\n */\n\nobject D {\n val Array(evidCount, refCount, mod) = readLine split ' ' map (_ toInt)\n var all: List[Evidence] = Nil\n val evid = Array.ofDim[Evidence](evidCount)\n\n for (_ <- 1 to refCount) readLine split ' ' map (_ toInt) match {\n case Array(left, right) => evidence(left) refer evidence(right)\n }\n\n val setNums = all filter (_ isMain) map (_.count.toLong)\n val mull = setNums match {\n case Nil => 1\n case List(a) => a\n case list => list reduce ((left, right) => (left * right) % mod)\n }\n val summ = fastPow(evidCount, setNums.length + evidCount - all.length - 2)\n val result = (mull.toLong * summ) % mod\n\n def main(args: Array[String]) = println(result)\n\n def fastPow(base: Int, pow: Int): Int = {\n if (base == 1) return 1\n var acc = 1L\n var mul = base toLong\n var bit = 1L\n while (bit <= pow) {\n if ((pow & bit) != 0) acc = (acc * mul) % mod\n mul = (mul * mul) % mod\n bit <<= 1\n }\n return acc toInt\n }\n\n\n def evidence(index: Int) = {\n evid(index - 1) match {\n case null => {\n val created = new Evidence\n evid(index - 1) = created\n created\n }\n case existing => existing\n }\n }\n\n class Evidence {\n private var parent = this\n private var rank = 0\n private[this] var _count: Int = 1\n\n def count = _count\n\n private def count_=(count: Int) = _count = count\n\n\n all ::= this\n\n def main: Evidence = {\n if (this.parent != this) this.parent = this.parent main;\n this.parent\n }\n\n def isMain = this.parent == this\n\n def absorb(that: Evidence) {\n count += that.count\n that.parent = this\n if (this.rank == that.rank) this.rank += 1\n }\n\n def refer(that: Evidence) {\n val thisMain = this main;\n val thatMain = that main;\n if (thisMain.rank <= thatMain.rank) thatMain absorb thisMain\n else thisMain absorb thatMain\n }\n }\n\n}\n"}], "src_uid": "b244d5c52acda47c5e8ef92029a9635f"} {"nl": {"description": "You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$: Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \\le i, j \\le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$. Select any arbitrary index $$$i$$$ ($$$1 \\le i \\le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^6$$$)\u00a0\u2014 the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.", "output_spec": "Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.", "sample_inputs": ["3\n100\n001", "4\n0101\n0011"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: \"100\" $$$\\to$$$ \"000\" $$$\\to$$$ \"001\". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then \"100\" $$$\\to$$$ \"001\", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as \"0101\" $$$\\to$$$ \"0011\". The cost is $$$|2 - 3| = 1$$$."}, "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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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"}, {"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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$\"abca\" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \\le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$\"abca\", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$s$$$ and the number of tries correspondingly. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of each test case contains $$$m$$$ integers $$$p_1, p_2, \\dots, p_m$$$ ($$$1 \\le p_i < n$$$) \u2014 the number of characters pressed right during the $$$i$$$-th try. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ both does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$, $$$\\sum m \\le 2 \\cdot 10^5$$$). It is guaranteed that the answer for each letter does not exceed $$$2 \\cdot 10^9$$$.", "output_spec": "For each test case, print the answer \u2014 $$$26$$$ integers: the number of times you press the button 'a', the number of times you press the button 'b', $$$\\dots$$$, the number of times you press the button 'z'.", "sample_inputs": ["3\n4 2\nabca\n1 3\n10 5\ncodeforces\n2 8 3 2 9\n26 10\nqwertyuioplkjhgfdsazxcvbnm\n20 10 1 2 3 5 10 5 9 4"], "sample_outputs": ["4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 \n2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2"], "notes": "NoteThe first test case is described in the problem statement. Wrong tries are \"a\", \"abc\" and the final try is \"abca\". The number of times you press 'a' is $$$4$$$, 'b' is $$$2$$$ and 'c' is $$$2$$$.In the second test case, there are five wrong tries: \"co\", \"codeforc\", \"cod\", \"co\", \"codeforce\" and the final try is \"codeforces\". The number of times you press 'c' is $$$9$$$, 'd' is $$$4$$$, 'e' is $$$5$$$, 'f' is $$$3$$$, 'o' is $$$9$$$, 'r' is $$$3$$$ and 's' is $$$1$$$."}, "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 s = ns(n)\n\n val p = na(m)\n\n val cnt = Array.fill[Int](26)(0)\n\n REP(n) { i =>\n cnt(s(i) - 'a') += 1\n }\n g = Array.ofDim[Array[Int]](26)\n REP(26) { i =>\n g(i) = Array.ofDim[Int](cnt(i))\n }\n\n REP_r(n) { i =>\n g(s(i) - 'a')(cnt(s(i) - 'a') - 1) = i\n cnt(s(i) - 'a') -= 1\n }\n ans = Array.fill[Long](26)(0)\n REP(m) { i =>\n bs(p(i) - 1)\n }\n REP(n) { i =>\n ans(s(i) - 'a') += 1\n }\n out.println(ans.mkString(\" \"))\n }\n }\n var g: Array[Array[Int]] = _\n var ans: Array[Long] = _\n\n def bs(v: Int): Unit = {\n REP(26) { i =>\n if(g(i).length > 0) {\n var l = 0\n var r = g(i).length - 1\n while (r - l > 1) {\n val m = l + (r - l) / 2\n if (g(i)(m) > v) r = m - 1\n else l = m\n }\n if (g(i).length > 0 && g(i)(r) <= v) ans(i) += (r+1)\n else if (g(i).length > 0 && g(i)(l) <= v) ans(i) += (l+1)\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "51ea912b40b07c1ba097292ffd0cec18"} {"nl": {"description": "Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n\u2009-\u20091). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that: he pointed at the person with index (bi\u2009+\u20091)\u00a0mod\u00a0n either with an elbow or with a nod (x\u00a0mod\u00a0y is the remainder after dividing x by y); if j\u2009\u2265\u20094 and the players who had turns number j\u2009-\u20091, j\u2009-\u20092, j\u2009-\u20093, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice; the turn went to person number (bi\u2009+\u20091)\u00a0mod\u00a0n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.", "input_spec": "The first line contains a single integer n (4\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns. ", "output_spec": "Print a single integer \u2014 the number of glasses of juice Vasya could have drunk if he had played optimally well.", "sample_inputs": ["4\nabbba", "4\nabbab"], "sample_outputs": ["1", "0"], "notes": "NoteIn both samples Vasya has got two turns \u2014 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like \"abbbb\". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different."}, "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.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": "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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions: Length of the substring is at least $$$2$$$ 'a' occurs strictly more times in this substring than 'b' 'a' occurs strictly more times in this substring than 'c' Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 10^{5})$$$ \u00a0\u2014 the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \\le n \\le 10^{6})$$$ \u00a0\u2014 the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting only of characters 'a', 'b' and 'c'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^{6}$$$.", "output_spec": "For each test case, output the length of the smallest substring which satisfies the given conditions or print $$$-1$$$ if there is no such substring.", "sample_inputs": ["3\n2\naa\n5\ncbabb\n8\ncacabccc"], "sample_outputs": ["2\n-1\n3"], "notes": "NoteConsider the first test case. In the substring \"aa\", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring \"aa\" satisfies the condition and the answer is $$$2$$$. The substring \"a\" also satisfies this condition, however its length is not at least $$$2$$$.In the second test case, it can be shown that in none of the substrings of \"cbabb\" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, \"cacabccc\", the length of the smallest substring that satisfies the conditions is $$$3$$$."}, "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 val s = readString()\n\n def check(k:Int): Boolean = {\n var a = 0\n var b = 0\n var c = 0\n for (i <- 0 until s.length) {\n if (s(i) == 'a')\n a += 1\n if (s(i) == 'b')\n b += 1\n if (s(i) == 'c')\n c += 1\n if (i >= k) {\n if (s(i-k) == 'a')\n a -= 1\n if (s(i-k) == 'b')\n b -= 1\n if (s(i-k) == 'c')\n c -= 1\n }\n if (i >= k-1 && a > b && a > c)\n return true\n }\n false\n }\n\n def bs(st: Int, en: Int): Int = {\n for (i <- st to en)\n if (check(i))\n return i\n return -1\n }\n\n writer.println(bs(2, min(7, n)))\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "c2f3d09674190f90c940f134c3e22afe"} {"nl": {"description": "On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k\u2009+\u20091. Find the maximal number of peas it will be able to collect and which moves it should make to do it.The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.", "input_spec": "The first line contains three integers n, m, k (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100,\u20090\u2009\u2264\u2009k\u2009\u2264\u200910) \u2014 the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces \u2014 the chessboard's description. Each square is described by one number \u2014 the number of peas in it. The first line corresponds to the uppermost row and the last line \u2014 to the lowest row.", "output_spec": "If it is impossible to reach the highest row having collected the number of peas divisible by k\u2009+\u20091, print -1. Otherwise, the first line must contain a single number \u2014 the maximal number of peas the pawn can collect given that the number must be divisible by k\u2009+\u20091. The second line must contain a single number \u2014 the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n\u2009-\u20091 symbols \u2014 the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.", "sample_inputs": ["3 3 1\n123\n456\n789", "3 3 0\n123\n456\n789", "2 2 10\n98\n75"], "sample_outputs": ["16\n2\nRL", "17\n3\nLR", "-1"], "notes": null}, "positive_code": [{"source_code": "object D41 {\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, k) = readInts(3)\n val MOD = k + 1\n val g = Array.fill(n)(read.map(_ - '0').toArray)\n val dp = Array.fill(n, m, MOD)(-1)\n for (i <- n - 1 to 0 by -1; j <- 0 until m) {\n if (i == n - 1) {\n dp(i)(j)(g(i)(j) % MOD) = g(i)(j)\n } else {\n for (mod <- 0 until MOD) {\n if (j >= 1 && dp(i + 1)(j - 1)(mod) >= 0)\n dp(i)(j)((g(i)(j) + dp(i + 1)(j - 1)(mod)) % MOD) = math.max(\n dp(i)(j)((g(i)(j) + dp(i + 1)(j - 1)(mod)) % MOD),\n dp(i + 1)(j - 1)(mod) + g(i)(j)\n )\n if (j < m - 1 && dp(i + 1)(j + 1)(mod) >= 0)\n dp(i)(j)((g(i)(j) + dp(i + 1)(j + 1)(mod)) % MOD) = math.max(\n dp(i)(j)((g(i)(j) + dp(i + 1)(j + 1)(mod)) % MOD),\n dp(i + 1)(j + 1)(mod) + g(i)(j)\n )\n }\n }\n }\n\n var res = -1\n var idxJ = 0\n for (j <- 0 until m if (dp(0)(j)(0) > res)) {\n res = dp(0)(j)(0)\n idxJ = j\n }\n out.println(res)\n if (res != -1) {\n // tracePath\n var idxI = 0\n var mod = 0\n val path = ArrayBuffer.empty[Char]\n while (idxI < n - 1) {\n val next = dp(idxI)(idxJ)(mod) - g(idxI)(idxJ)\n var done = false\n if (idxJ - 1 >= 0 && dp(idxI + 1)(idxJ - 1)(next % MOD) == next) {\n mod = next % MOD\n idxJ -= 1\n path.append('R')\n done = true\n }\n if (!done && idxJ + 1 < m && dp(idxI + 1)(idxJ + 1)(next % MOD) == next) {\n mod = next % MOD\n idxJ += 1\n path.append('L')\n done = true\n }\n idxI += 1\n }\n out.println(idxJ + 1)\n out.println(path.reverseIterator.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"}], "negative_code": [], "src_uid": "ea84cfce0a7f46f33e9e84be6c4dc648"} {"nl": {"description": "You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.", "input_spec": "First line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0\u2009\u2264\u2009ai\u2009\u2264\u2009105;\u00a00\u2009\u2264\u2009bi\u2009\u2264\u2009104) \u2014 number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).", "output_spec": "Print one integer \u2014 smallest amount of money you need to spend to win the elections.", "sample_inputs": ["5\n1 2\n1 2\n1 2\n2 1\n0 0", "4\n1 2\n1 2\n2 1\n0 0", "1\n100000 0"], "sample_outputs": ["3", "2", "0"], "notes": null}, "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 (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}"}, {"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"} {"nl": {"description": "Leha like all kinds of strange things. Recently he liked the function F(n,\u2009k). Consider all possible k-element subsets of the set [1,\u20092,\u2009...,\u2009n]. For subset find minimal element in it. F(n,\u2009k) \u2014 mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i,\u2009j such that 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009m the condition Ai\u2009\u2265\u2009Bj holds. Help Leha rearrange the numbers in the array A so that the sum is maximally possible, where A' is already rearranged array.", "input_spec": "First line of input data contains single integer m (1\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 length of arrays A and B. Next line contains m integers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 array A. Next line contains m integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009109) \u2014 array B.", "output_spec": "Output m integers a'1,\u2009a'2,\u2009...,\u2009a'm \u2014 array A' which is permutation of the array A.", "sample_inputs": ["5\n7 3 5 3 4\n2 1 3 2 3", "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2"], "sample_outputs": ["4 7 3 5 3", "2 6 4 5 8 8 6"], "notes": null}, "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(m) = readInts(1)\n val as = readInts(m).sorted\n val bs = readInts(m).zipWithIndex.sortBy(_._1)\n\n val res = Array.ofDim[Int](m)\n\n for (i <- as.indices) res(bs(i)._2) = as(m - i - 1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(res.mkString(\" \"))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "c51e15aeb3f287608a26b85865546e85"} {"nl": {"description": "The store sells $$$n$$$ beads. The color of each bead is described by a lowercase letter of the English alphabet (\"a\"\u2013\"z\"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads \"a\", \"b\", \"c\", \"a\", \"c\", \"c\", then you can assemble the following necklaces (these are not all possible options): And the following necklaces cannot be assembled from beads sold in the store: The first necklace cannot be assembled because it has three beads \"a\" (of the two available). The second necklace cannot be assembled because it contains a bead \"d\", which is not sold in the store. We call a necklace $$$k$$$-beautiful if, when it is turned clockwise by $$$k$$$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace. As you can see, this necklace is, for example, $$$3$$$-beautiful, $$$6$$$-beautiful, $$$9$$$-beautiful, and so on, but it is not $$$1$$$-beautiful or $$$2$$$-beautiful.In particular, a necklace of length $$$1$$$ is $$$k$$$-beautiful for any integer $$$k$$$. A necklace that consists of beads of the same color is also beautiful for any $$$k$$$.You are given the integers $$$n$$$ and $$$k$$$, and also the string $$$s$$$ containing $$$n$$$ lowercase letters of the English alphabet\u00a0\u2014 each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $$$k$$$-beautiful necklace you can assemble.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 2000$$$). The second line of each test case contains the string $$$s$$$ containing $$$n$$$ lowercase English letters\u00a0\u2014 the beads in the store. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.", "output_spec": "Output $$$t$$$ answers to the test cases. Each answer is a positive integer\u00a0\u2014 the maximum length of the $$$k$$$-beautiful necklace you can assemble.", "sample_inputs": ["6\n6 3\nabcbac\n3 6\naaa\n7 1000\nabczgyo\n5 4\nababa\n20 10\naaebdbabdbbddaadaadc\n20 5\necbedececacbcbccbdec"], "sample_outputs": ["6\n3\n5\n4\n15\n10"], "notes": "NoteThe first test case is explained in the statement.In the second test case, a $$$6$$$-beautiful necklace can be assembled from all the letters.In the third test case, a $$$1000$$$-beautiful necklace can be assembled, for example, from beads \"abzyo\"."}, "positive_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 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"}, {"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"} {"nl": {"description": "\u00a0\u2014 Do you have a wish? \u00a0\u2014 I want people to stop gifting each other arrays.O_o and Another Young BoyAn array of $$$n$$$ positive integers $$$a_1,a_2,\\ldots,a_n$$$ fell down on you from the skies, along with a positive integer $$$k \\le n$$$.You can apply the following operation at most $$$k$$$ times: Choose an index $$$1 \\le i \\le n$$$ and an integer $$$1 \\le x \\le 10^9$$$. Then do $$$a_i := x$$$ (assign $$$x$$$ to $$$a_i$$$). Then build a complete undirected weighted graph with $$$n$$$ vertices numbered with integers from $$$1$$$ to $$$n$$$, where edge $$$(l, r)$$$ ($$$1 \\le l < r \\le n$$$) has weight $$$\\min(a_{l},a_{l+1},\\ldots,a_{r})$$$.You have to find the maximum possible diameter of the resulting graph after performing at most $$$k$$$ operations.The diameter of a graph is equal to $$$\\max\\limits_{1 \\le u < v \\le n}{\\operatorname{d}(u, v)}$$$, where $$$\\operatorname{d}(u, v)$$$ is the length of the shortest path between vertex $$$u$$$ and vertex $$$v$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$1 \\le k \\le n$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer\u00a0\u2014 the maximum possible diameter of the graph after performing at most $$$k$$$ operations.", "sample_inputs": ["6\n\n3 1\n\n2 4 1\n\n3 2\n\n1 9 84\n\n3 1\n\n10 2 6\n\n3 2\n\n179 17 1000000000\n\n2 1\n\n5 9\n\n2 2\n\n4 2"], "sample_outputs": ["4\n168\n10\n1000000000\n9\n1000000000"], "notes": "NoteIn the first test case, one of the optimal arrays is $$$[2,4,5]$$$.The graph built on this array: $$$\\operatorname{d}(1, 2) = \\operatorname{d}(1, 3) = 2$$$ and $$$\\operatorname{d}(2, 3) = 4$$$, so the diameter is equal to $$$\\max(2,2,4) = 4$$$."}, "positive_code": [{"source_code": "object Main {\n private val in = scala.io.StdIn\n\n val inf = 1000000000\n\n def checkAns(x: Int, k1: Int, b: Array[Int]): Boolean = {\n var k = k1\n val a = new Array[Int](b.length)\n val n = a.length\n for (i <- 0 until n)\n a(i) = b(i)\n\n var mn = 2\n\n if (2 * a(0) < x) {\n a(0) = inf;\n k = k - 1;\n }\n for (i <- 1 until n) {\n if (2 * a(i) < x) {\n k = k - 1;\n a(i) = inf;\n }\n\n if (Math.min(a(i - 1), a(i)) >= x) mn = 0\n else if (Math.max(a(i - 1), a(i)) >= x) mn = Math.min(mn, 1);\n }\n mn <= k\n }\n\n def main(args: Array[String]): Unit = {\n val t = in.readInt()\n for (_ <- 1 to t) {\n val Array(n, k) = in.readLine().split(\" \").map(_.toInt)\n val a = in.readLine().split(\" \").map(_.toInt)\n\n var l = 0\n var r = inf + 1\n while (l < r - 1) {\n val m = (l + r) / 2\n if (checkAns(m, k, a)) l = m\n else r = m;\n }\n println(l)\n }\n }\n}\n"}], "negative_code": [], "src_uid": "d1c2caeec0fe1ac33a6735b03d7c75ce"} {"nl": {"description": "A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Let $$$p$$$ be any permutation of length $$$n$$$. We define the fingerprint $$$F(p)$$$ of $$$p$$$ as the sorted array of sums of adjacent elements in $$$p$$$. More formally,$$$$$$F(p)=\\mathrm{sort}([p_1+p_2,p_2+p_3,\\ldots,p_{n-1}+p_n]).$$$$$$For example, if $$$n=4$$$ and $$$p=[1,4,2,3],$$$ then the fingerprint is given by $$$F(p)=\\mathrm{sort}([1+4,4+2,2+3])=\\mathrm{sort}([5,6,5])=[5,5,6]$$$.You are given a permutation $$$p$$$ of length $$$n$$$. Your task is to find a different permutation $$$p'$$$ with the same fingerprint. Two permutations $$$p$$$ and $$$p'$$$ are considered different if there is some index $$$i$$$ such that $$$p_i \\ne p'_i$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 668$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2\\le n\\le 100$$$) \u00a0\u2014 the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1,\\ldots,p_n$$$ ($$$1\\le p_i\\le n$$$). It is guaranteed that $$$p$$$ is a permutation.", "output_spec": "For each test case, output $$$n$$$ integers $$$p'_1,\\ldots, p'_n$$$ \u2014 a permutation such that $$$p'\\ne p$$$ and $$$F(p')=F(p)$$$. We can prove that for every permutation satisfying the input constraints, a solution exists. If there are multiple solutions, you may output any.", "sample_inputs": ["3\n2\n1 2\n6\n2 1 6 5 4 3\n5\n2 4 3 1 5"], "sample_outputs": ["2 1\n1 2 5 6 3 4\n3 1 5 2 4"], "notes": "NoteIn the first test case, $$$F(p)=\\mathrm{sort}([1+2])=[3]$$$.And $$$F(p')=\\mathrm{sort}([2+1])=[3]$$$.In the second test case, $$$F(p)=\\mathrm{sort}([2+1,1+6,6+5,5+4,4+3])=\\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$$$.And $$$F(p')=\\mathrm{sort}([1+2,2+5,5+6,6+3,3+4])=\\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$$$.In the third test case, $$$F(p)=\\mathrm{sort}([2+4,4+3,3+1,1+5])=\\mathrm{sort}([6,7,4,6])=[4,6,6,7]$$$.And $$$F(p')=\\mathrm{sort}([3+1,1+5,5+2,2+4])=\\mathrm{sort}([4,6,7,6])=[4,6,6,7]$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \\ldots, d_n$$$ ($$$0 \\leq d_i \\leq 10^9$$$)\u00a0\u2014 the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.", "sample_inputs": ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"], "sample_outputs": ["-3\n0\n0"], "notes": "NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$."}, "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 ds = nextLongs(n).sorted\n\n var res = 0L\n var prev = 0L\n var mul = 0L\n var back = 0L\n for (d <- ds) {\n val x = (d - prev)\n res += x\n back += mul * x\n res -= back\n prev = d\n mul += 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"}], "negative_code": [], "src_uid": "7dfe0db5a99e6e4d71eb012fab07685b"} {"nl": {"description": "Alex decided to go on a touristic trip over the country.For simplicity let's assume that the country has $$$n$$$ cities and $$$m$$$ bidirectional roads connecting them. Alex lives in city $$$s$$$ and initially located in it. To compare different cities Alex assigned each city a score $$$w_i$$$ which is as high as interesting city seems to Alex.Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $$$v$$$ from city $$$u$$$, he may choose as the next city in the trip any city connected with $$$v$$$ by the road, except for the city $$$u$$$.Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.", "input_spec": "First line of input contains two integers $$$n$$$ and $$$m$$$, ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le m \\le 2 \\cdot 10^5$$$) which are numbers of cities and roads in the country. Second line contains $$$n$$$ integers $$$w_1, w_2, \\ldots, w_n$$$ ($$$0 \\le w_i \\le 10^9$$$) which are scores of all cities. The following $$$m$$$ lines contain description of the roads. Each of these $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$) which are cities connected by this road. It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads. The last line contains single integer $$$s$$$ ($$$1 \\le s \\le n$$$), which is the number of the initial city.", "output_spec": "Output single integer which is the maximum possible sum of scores of visited cities.", "sample_inputs": ["5 7\n2 2 8 6 9\n1 2\n1 3\n2 4\n3 2\n4 5\n2 5\n1 5\n2", "10 12\n1 7 1 9 3 3 6 30 1 10\n1 2\n1 3\n3 5\n5 7\n2 3\n5 4\n6 9\n4 6\n3 7\n6 8\n9 4\n9 10\n6"], "sample_outputs": ["27", "61"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 \u30ce\u30fc\u30c9\u6570\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 \u30ce\u30fc\u30c9\u6570\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"} {"nl": {"description": "You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 1000$$$) \u2014 the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \\le n \\le 10^{18}$$$).", "output_spec": "Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it.", "sample_inputs": ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"], "sample_outputs": ["0\n4\n6\n6\n-1\n6\n72"], "notes": null}, "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.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"}, {"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": "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"}], "negative_code": [], "src_uid": "ed5ea0e664aa986ab86e4e6746e8a1bf"} {"nl": {"description": "There are two rival donut shops.The first shop sells donuts at retail: each donut costs $$$a$$$ dollars.The second shop sells donuts only in bulk: box of $$$b$$$ donuts costs $$$c$$$ dollars. So if you want to buy $$$x$$$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to $$$x$$$.You want to determine two positive integer values: how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop? how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop? If any of these values doesn't exist then that value should be equal to $$$-1$$$. If there are multiple possible answers, then print any of them.The printed values should be less or equal to $$$10^9$$$. It can be shown that under the given constraints such values always exist if any values exist at all.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\le a \\le 10^9$$$, $$$2 \\le b \\le 10^9$$$, $$$1 \\le c \\le 10^9$$$).", "output_spec": "For each testcase print two positive integers. For both shops print such $$$x$$$ that buying $$$x$$$ donuts in this shop is strictly cheaper than buying $$$x$$$ donuts in the other shop. $$$x$$$ should be greater than $$$0$$$ and less or equal to $$$10^9$$$. If there is no such $$$x$$$, then print $$$-1$$$. If there are multiple answers, then print any of them.", "sample_inputs": ["4\n5 10 4\n4 5 20\n2 2 3\n1000000000 1000000000 1000000000"], "sample_outputs": ["-1 20\n8 -1\n1 2\n-1 1000000000"], "notes": "NoteIn the first testcase buying any number of donuts will be cheaper in the second shop. For example, for $$$3$$$ or $$$5$$$ donuts you'll have to buy a box of $$$10$$$ donuts for $$$4$$$ dollars. $$$3$$$ or $$$5$$$ donuts in the first shop would cost you $$$15$$$ or $$$25$$$ dollars, respectively, however. For $$$20$$$ donuts you'll have to buy two boxes for $$$8$$$ dollars total. Note that $$$3$$$ and $$$5$$$ are also valid answers for the second shop, along with many other answers.In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. $$$8$$$ donuts cost $$$32$$$ dollars in the first shop and $$$40$$$ dollars in the second shop (because you have to buy two boxes). $$$10$$$ donuts will cost $$$40$$$ dollars in both shops, so $$$10$$$ is not a valid answer for any of the shops.In the third testcase $$$1$$$ donut costs $$$2$$$ and $$$3$$$ dollars, respectively. $$$2$$$ donuts cost $$$4$$$ and $$$3$$$ dollars. Thus, $$$1$$$ is a valid answer for the first shop and $$$2$$$ is a valid answer for the second shop.In the fourth testcase $$$10^9$$$ donuts cost $$$10^{18}$$$ dollars in the first shop and $$$10^9$$$ dollars in the second shop."}, "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"}, {"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"}], "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"} {"nl": {"description": "Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n\u2009-\u20091.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit. ", "input_spec": "The first line contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the number of flats in the house. The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i. ", "output_spec": "Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house. ", "sample_inputs": ["3\nAaA", "7\nbcAAcbc", "6\naaBCCe"], "sample_outputs": ["2", "3", "5"], "notes": "NoteIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6."}, "positive_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 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"}, {"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"} {"nl": {"description": "Recently Duff has been a soldier in the army. Malek is her commander.Their country, Andarz Gu has n cities (numbered from 1 to n) and n\u2009-\u20091 bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.There are also m people living in Andarz Gu (numbered from 1 to m). Each person has and ID number. ID number of i\u2009-\u2009th person is i and he/she lives in city number ci. Note that there may be more than one person in a city, also there may be no people living in the city. Malek loves to order. That's why he asks Duff to answer to q queries. In each query, he gives her numbers v,\u2009u and a.To answer a query:Assume there are x people living in the cities lying on the path from city v to city u. Assume these people's IDs are p1,\u2009p2,\u2009...,\u2009px in increasing order. If k\u2009=\u2009min(x,\u2009a), then Duff should tell Malek numbers k,\u2009p1,\u2009p2,\u2009...,\u2009pk in this order. In the other words, Malek wants to know a minimums on that path (or less, if there are less than a people).Duff is very busy at the moment, so she asked you to help her and answer the queries.", "input_spec": "The first line of input contains three integers, n,\u2009m and q (1\u2009\u2264\u2009n,\u2009m,\u2009q\u2009\u2264\u2009105). The next n\u2009-\u20091 lines contain the roads. Each line contains two integers v and u, endpoints of a road (1\u2009\u2264\u2009v,\u2009u\u2009\u2264\u2009n, v\u2009\u2260\u2009u). Next line contains m integers c1,\u2009c2,\u2009...,\u2009cm separated by spaces (1\u2009\u2264\u2009ci\u2009\u2264\u2009n for each 1\u2009\u2264\u2009i\u2009\u2264\u2009m). Next q lines contain the queries. Each of them contains three integers, v,\u2009u and a (1\u2009\u2264\u2009v,\u2009u\u2009\u2264\u2009n and 1\u2009\u2264\u2009a\u2009\u2264\u200910).", "output_spec": "For each query, print numbers k,\u2009p1,\u2009p2,\u2009...,\u2009pk separated by spaces in one line.", "sample_inputs": ["5 4 5\n1 3\n1 2\n1 4\n4 5\n2 1 4 3\n4 5 6\n1 5 2\n5 5 10\n2 3 3\n5 3 1"], "sample_outputs": ["1 3\n2 2 3\n0\n3 1 2 4\n1 2"], "notes": "NoteGraph of Andarz Gu in the sample case is as follows (ID of people in each city are written next to them): "}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Consider a sequence [a1,\u2009a2,\u2009... ,\u2009an]. Define its prefix product sequence .Now given n, find a permutation of [1,\u20092,\u2009...,\u2009n], such that its prefix product sequence is a permutation of [0,\u20091,\u2009...,\u2009n\u2009-\u20091].", "input_spec": "The only input line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "In the first output line, print \"YES\" if such sequence exists, or print \"NO\" if no such sequence exists. If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n. If there are multiple solutions, you are allowed to print any of them.", "sample_inputs": ["7", "6"], "sample_outputs": ["YES\n1\n4\n3\n6\n5\n2\n7", "NO"], "notes": "NoteFor the second sample, there are no valid sequences."}, "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 var prime = true\n for (i <- 2 until n) if (n % i == 0) prime = false\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 4) println(\"YES\\n1\\n3\\n2\\n4\")\n else if (prime) {\n println(\"YES\")\n val used = mutable.BitSet(n + 1)\n var fact = BigInt(1)\n for (i <- 2 until n) fact = fact * i % n\n val as = Array.ofDim[Long](n)\n as(0) = 1\n as(n - 1) = n\n \n for (i <- n - 2 to 1 by -1) {\n val x = n + 1 - fact % n\n as(i) = x.toLong\n fact = fact * x.modInverse(n) % n\n }\n \n println(as.mkString(\"\\n\"))\n \n } else println(\"NO\")\n\n Console.flush\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\n var prime = true\n for (i <- 2 until n) if (n % i == 0) prime = false\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (prime) {\n println(\"YES\")\n val used = mutable.BitSet(n + 1)\n var fact = BigInt(1)\n for (i <- 2 until n) fact = fact * i % n\n val as = Array.ofDim[Long](n)\n as(0) = 1\n as(n - 1) = n\n \n for (i <- n - 2 to 1 by -1) {\n val x = n + 1 - fact % n\n as(i) = x.toLong\n fact = fact * x.modInverse(n) % n\n }\n \n println(as.mkString(\"\\n\"))\n \n } else println(\"NO\")\n\n Console.flush\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 var prime = true\n for (i <- 2 until n) if (n % i == 0) prime = false\n \n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n == 4) println(\"1\\n3\\n2\\n4\")\n else if (prime) {\n println(\"YES\")\n val used = mutable.BitSet(n + 1)\n var fact = BigInt(1)\n for (i <- 2 until n) fact = fact * i % n\n val as = Array.ofDim[Long](n)\n as(0) = 1\n as(n - 1) = n\n \n for (i <- n - 2 to 1 by -1) {\n val x = n + 1 - fact % n\n as(i) = x.toLong\n fact = fact * x.modInverse(n) % n\n }\n \n println(as.mkString(\"\\n\"))\n \n } else println(\"NO\")\n\n Console.flush\n}"}], "src_uid": "8b61e354ece0242eff539163f76cabde"} {"nl": {"description": "A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $$$n$$$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of $$$n$$$ numbers: $$$d_1, d_2, \\dots, d_n$$$ ($$$-10^6 \\le d_i \\le 10^6$$$). The $$$i$$$-th element means that monster's hp (hit points) changes by the value $$$d_i$$$ during the $$$i$$$-th minute of each round. Formally, if before the $$$i$$$-th minute of a round the monster's hp is $$$h$$$, then after the $$$i$$$-th minute it changes to $$$h := h + d_i$$$.The monster's initial hp is $$$H$$$. It means that before the battle the monster has $$$H$$$ hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to $$$0$$$. Print -1 if the battle continues infinitely.", "input_spec": "The first line contains two integers $$$H$$$ and $$$n$$$ ($$$1 \\le H \\le 10^{12}$$$, $$$1 \\le n \\le 2\\cdot10^5$$$). The second line contains the sequence of integers $$$d_1, d_2, \\dots, d_n$$$ ($$$-10^6 \\le d_i \\le 10^6$$$), where $$$d_i$$$ is the value to change monster's hp in the $$$i$$$-th minute of a round.", "output_spec": "Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer $$$k$$$ such that $$$k$$$ is the first minute after which the monster is dead.", "sample_inputs": ["1000 6\n-100 -200 -300 125 77 -4", "1000000000000 5\n-1 0 0 0 0", "10 4\n-3 -6 5 4"], "sample_outputs": ["9", "4999999999996", "-1"], "notes": null}, "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) // \u4f55\u30bf\u30fc\u30f3\u304b\u304b\u3063\u3066\u3082\u305f\u304a\u305b\u306a\u3044\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"}, {"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}"}], "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"} {"nl": {"description": "Sereja has two sequences a and b and number p. Sequence a consists of n integers a1,\u2009a2,\u2009...,\u2009an. Similarly, sequence b consists of m integers b1,\u2009b2,\u2009...,\u2009bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q\u2009+\u2009(m\u2009-\u20091)\u00b7p\u2009\u2264\u2009n;\u00a0q\u2009\u2265\u20091), such that sequence b can be obtained from sequence aq,\u2009aq\u2009+\u2009p,\u2009aq\u2009+\u20092p,\u2009...,\u2009aq\u2009+\u2009(m\u2009-\u20091)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.", "input_spec": "The first line contains three integers n, m and p (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105,\u20091\u2009\u2264\u2009p\u2009\u2264\u20092\u00b7105). The next line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The next line contains m integers b1, b2, ..., bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.", "sample_inputs": ["5 3 1\n1 2 3 2 1\n1 2 3", "6 3 2\n1 3 2 2 3 1\n1 2 3"], "sample_outputs": ["2\n1 3", "2\n1 2"], "notes": null}, "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 Array(n, m, p) = readInts(3)\n val mpL = p.longValue * (m - 1)\n \n val as0 = readInts(n)\n val bs0 = readInts(m) \n\n val amap = bs0.zipWithIndex.reverse.toMap.withDefaultValue(m)\n val as = as0.map(amap)\n val bs = bs0.map(amap)\n \n val bc = Array.fill(m + 1)(0)\n for (b <- bs) bc(b) += 1\n \n val res = mutable.ArrayBuffer[Int]()\n \n var offset = 0\n \n while (offset < p && offset + mpL < n) {\n \n val ac = bc.clone\n \n var i = 0 \n while (i < m) {\n val a = as(offset + i * p)\n ac(a) -= 1\n i += 1\n }\n \n var q = offset\n var zeroC = ac.count(_ == 0)\n if (zeroC > m) res += (q + 1)\n \n while (q + m * p < n) {\n val a1 = as(q)\n ac(a1) += 1\n if (ac(a1) == 0) zeroC += 1 else if (ac(a1) == 1) zeroC -=1 \n val a2 = as(q + m * p) \n ac(a2) -= 1\n if (ac(a2) == 0) zeroC += 1 else if (ac(a2) == -1) zeroC -=1 \n q += p\n if (zeroC > m) res += (q + 1)\n }\n \n offset += 1\n }\n\n println(res.size)\n println(res.sorted.mkString(\" \"))\n}"}], "negative_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 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, p) = readInts(3)\n val as0 = /*Array.fill(n)(scala.util.Random.nextInt) */readInts(n)\n val bs0 = /*Array.fill(n)(scala.util.Random.nextInt) */readInts(m) \n\n val amap = bs0.zipWithIndex.reverse.toMap.withDefaultValue(m)\n val as = as0.map(amap)\n val bs = bs0.map(amap)\n \n val bc = Array.fill(m + 1)(0)\n for (b <- bs) bc(b) += 1\n \n val res = mutable.ArrayBuffer[Int]()\n \n var offset = 0\n while (offset < p && offset + (m - 1) * p < n) {\n val ac = Array.fill(m + 1)(0)\n var i = 0\n while (i < m) {\n ac(as(offset + i * p)) += 1\n i += 1\n }\n var q = offset\n var lastBad = 0\n while (lastBad <= m && ac(lastBad) == bc(lastBad)) lastBad += 1\n if (lastBad > m) res += (q + 1)\n while (q + m * p < n) {\n ac(as(q)) -= 1\n val qq = q + m * p \n ac(as(qq)) += 1\n if ((as(q) == lastBad && ac(as(q)) == bc(as(q))) ||\n as(qq) == lastBad && ac(as(qq)) == bc(as(qq))) {\n \t while (lastBad <= m && ac(lastBad) == bc(lastBad)) lastBad += 1\n } else lastBad = as(q) min as(qq) min lastBad\n q += p\n if (lastBad > m) res += (q + 1)\n }\n offset += 1\n }\n\n println(res.size)\n println(res.sorted.mkString(\" \"))\n}"}], "src_uid": "84cce147e8aadb140afaaa95917fdf0d"} {"nl": {"description": "Let's call the string beautiful if it does not contain a substring of length at least $$$2$$$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You are given a string $$$s$$$ of length $$$n$$$, each character of the string is one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You have to answer $$$m$$$ queries\u00a0\u2014 calculate the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the string $$$s$$$ and the number of queries. The second line contains the string $$$s$$$, it consists of $$$n$$$ characters, each character one of the first $$$3$$$ Latin letters. The following $$$m$$$ lines contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$)\u00a0\u2014 parameters of the $$$i$$$-th query.", "output_spec": "For each query, print a single integer\u00a0\u2014 the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.", "sample_inputs": ["5 4\nbaacb\n1 3\n1 5\n4 5\n2 3"], "sample_outputs": ["1\n2\n0\n1"], "notes": "NoteConsider the queries of the example test. in the first query, the substring is baa, which can be changed to bac in one operation; in the second query, the substring is baacb, which can be changed to cbacb in two operations; in the third query, the substring is cb, which can be left unchanged; in the fourth query, the substring is aa, which can be changed to ba in one operation. "}, "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 //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}"}, {"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"} {"nl": {"description": "A tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1,\u2009p2,\u2009...,\u2009pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent). For this rooted tree the array p is [2,\u20093,\u20093,\u20092]. Given a sequence p1,\u2009p2,\u2009...,\u2009pn, one is able to restore a tree: There must be exactly one index r that pr\u2009=\u2009r. A vertex r is a root of the tree. For all other n\u2009-\u20091 vertices i, there is an edge between vertex i and vertex pi. A sequence p1,\u2009p2,\u2009...,\u2009pn is called valid if the described procedure generates some (any) rooted tree. For example, for n\u2009=\u20093 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.You are given a sequence a1,\u2009a2,\u2009...,\u2009an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of vertices in the tree. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n).", "output_spec": "In the first line print the minimum number of elements to change, in order to get a valid sequence. In the second line, print any valid sequence possible to get from (a1,\u2009a2,\u2009...,\u2009an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.", "sample_inputs": ["4\n2 3 3 4", "5\n3 2 2 5 3", "8\n2 3 5 4 1 6 6 7"], "sample_outputs": ["1\n2 3 4 4", "0\n3 2 2 5 3", "2\n2 3 7 8 1 6 6 7"], "notes": "NoteIn the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4\u2009=\u20094), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. In the second sample, the given sequence is already valid."}, "positive_code": [{"source_code": "/**\n * Created by allen on 16-7-22.\n */\n\nimport scala.io._\n\n/**\n * Cheat Sheet:\n * Input: scala.io.StdIn\n * Output: println\n */\n\nobject main {\n val MAXN = 200010\n var n = 0\n var p = new Array[Int](MAXN)\n\n var vis = new Array[Boolean](MAXN)\n var tag = new Array[Int](MAXN)\n var rep = new Array[Int](MAXN)\n var tag_now = 0\n\n // Variables\n\n def readNInts(n: Int): Seq[Int] = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n\n def dfs(root: Int, tag_now: Int): Boolean = {\n vis(root) = true\n\n val parent = p(root - 1)\n if(vis(parent)) {\n if(tag(parent) == -1) {\n tag(root) = tag_now\n rep(tag_now) = root\n true\n } else {\n tag(root) = tag(parent)\n false\n }\n } else {\n val ret = dfs(parent, tag_now)\n tag(root) = tag(parent)\n ret\n }\n }\n\n def run() = {\n try {\n n = StdIn.readInt()\n readNInts(n).copyToArray(p, 0, n)\n\n (1 to MAXN).map(x => -1).copyToArray(tag)\n (1 to MAXN).map(x => false).copyToArray(vis)\n for (i <- 1 to n) if (!vis(i)) if (dfs(i, tag_now)) tag_now = tag_now + 1\n\n var new_root: Int = -1\n val rt = (0 until tag_now).filter(x => p(rep(x) - 1) == rep(x))\n\n if(rt.nonEmpty)\n new_root = rep(rt.head)\n\n if(new_root == -1) {\n p(rep(tag_now - 1) - 1) = rep(tag_now - 1)\n rep.toList.take(tag_now - 1).foreach(x => p(x - 1) = rep(tag_now - 1))\n println(tag_now)\n }\n else {\n println(tag_now - 1)\n rep.toList.take(tag_now).foreach(x => if(x != new_root) p(x - 1) = new_root)\n }\n println(p.take(n).mkString(\" \"))\n } catch {\n case e: Exception => println(e.getMessage())\n }\n }\n\n def main(args: Array[String])= {\n run()\n }\n}\n"}], "negative_code": [{"source_code": "/**\n * Created by allen on 16-7-22.\n */\n\nimport scala.io._\n\n/**\n * Cheat Sheet:\n * Input: scala.io.StdIn\n * Output: println\n */\n\nobject main {\n val MAXN = 200010\n var n = 0\n var p = new Array[Int](MAXN)\n\n var vis = new Array[Boolean](MAXN)\n var tag = new Array[Int](MAXN)\n var rep = new Array[Int](MAXN)\n var tag_now = 0\n\n // Variables\n\n def readNInts(n: Int): Seq[Int] = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n\n def dfs(root: Int, tag_now: Int): Boolean = {\n vis(root) = true\n\n val parent = p(root - 1)\n if(vis(parent)) {\n if(tag(parent) == -1) {\n tag(root) = tag_now\n rep(tag_now) = root\n true\n } else {\n tag(root) = tag(parent)\n false\n }\n } else {\n val ret = dfs(parent, tag_now)\n tag(root) = tag(parent)\n ret\n }\n }\n\n def run() = {\n try {\n n = StdIn.readInt()\n readNInts(n).copyToArray(p, 0, n)\n\n (1 to MAXN).map(x => -1).copyToArray(tag)\n (1 to MAXN).map(x => false).copyToArray(vis)\n for (i <- 1 to n) if (!vis(i)) if (dfs(i, tag_now)) tag_now = tag_now + 1\n if(p(rep(tag_now - 1) - 1) != rep(tag_now - 1)) {\n p(rep(tag_now - 1) - 1) = rep(tag_now - 1)\n println(tag_now)\n } else {\n println(tag_now - 1)\n }\n rep.toList.take(tag_now - 1).map(x => p(x - 1) = rep(tag_now - 1))\n println(p.take(n).mkString(\" \"))\n } catch {\n case e: Exception => println(e.getMessage())\n }\n }\n\n def main(args: Array[String])= {\n run()\n }\n}\n"}, {"source_code": "/**\n * Created by allen on 16-7-22.\n */\n\nimport scala.io._\n\n/**\n * Cheat Sheet:\n * Input: scala.io.StdIn\n * Output: println\n */\n\nobject main {\n val MAXN = 200010\n var n = 0\n var p = new Array[Int](MAXN)\n\n var vis = new Array[Boolean](MAXN)\n var tag = new Array[Int](MAXN)\n var rep = new Array[Int](MAXN)\n var tag_now = 0\n\n // Variables\n\n def readNInts(n: Int): Seq[Int] = StdIn.readLine().split(' ').map(x => x.toInt).toSeq\n\n def dfs(root: Int, tag_now: Int): Boolean = {\n vis(root) = true\n\n val parent = p(root - 1)\n if(vis(parent)) {\n if(tag(parent) == -1) {\n tag(root) = tag_now\n rep(tag_now) = root\n true\n } else {\n tag(root) = tag(parent)\n false\n }\n } else {\n val ret = dfs(parent, tag_now)\n tag(root) = tag(parent)\n ret\n }\n }\n\n def run() = {\n try {\n n = StdIn.readInt()\n readNInts(n).copyToArray(p, 0, n)\n\n (1 to MAXN).map(x => -1).copyToArray(tag)\n (1 to MAXN).map(x => false).copyToArray(vis)\n for (i <- 1 to n) if (!vis(i)) if (dfs(i, tag_now)) tag_now = tag_now + 1\n\n println(tag_now - 1)\n rep.toList.take(tag_now - 1).map(x => p(x - 1) = rep(tag_now - 1))\n println(p.take(n).mkString(\" \"))\n } catch {\n case e: Exception => println(e.getMessage())\n }\n }\n\n def main(args: Array[String])= {\n run()\n }\n}\n"}], "src_uid": "148a5ecd4afa1c7c60c46d9cb4a57208"} {"nl": {"description": "Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.", "input_spec": "The first line contains a single integer n\u00a0\u2014 the number of items (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105)\u00a0\u2014 the initial inventory numbers of the items.", "output_spec": "Print n numbers\u00a0\u2014 the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.", "sample_inputs": ["3\n1 3 2", "4\n2 2 3 3", "1\n2"], "sample_outputs": ["1 3 2", "2 1 3 4", "1"], "notes": "NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one."}, "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 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"}, {"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"} {"nl": {"description": "Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move. Help Anton and write the program that for the given position determines whether the white king is in check.Remainder, on how do chess pieces move: Bishop moves any number of cells diagonally, but it can't \"leap\" over the occupied cells. Rook moves any number of cells horizontally or vertically, but it also can't \"leap\" over the occupied cells. Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't \"leap\". ", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000)\u00a0\u2014 the number of black pieces. The second line contains two integers x0 and y0 (\u2009-\u2009109\u2009\u2264\u2009x0,\u2009y0\u2009\u2264\u2009109)\u00a0\u2014 coordinates of the white king. Then follow n lines, each of them contains a character and two integers xi and yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109)\u00a0\u2014 type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.", "output_spec": "The only line of the output should contains \"YES\" (without quotes) if the white king is in check and \"NO\" (without quotes) otherwise.", "sample_inputs": ["2\n4 2\nR 1 1\nB 1 5", "2\n4 2\nR 3 3\nB 1 5"], "sample_outputs": ["YES", "NO"], "notes": "NotePicture for the first sample: White king is in check, because the black bishop can reach the cell with the white king in one move. The answer is \"YES\".Picture for the second sample: Here bishop can't reach the cell with the white king, because his path is blocked by the rook, and the bishop cant \"leap\" over it. Rook can't reach the white king, because it can't move diagonally. Hence, the king is not in check and the answer is \"NO\"."}, "positive_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(_.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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are playing a strange game with Li Chen. You have a tree with $$$n$$$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from $$$1$$$ to $$$n$$$. Neither of you know the other's labelling of the tree.You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled $$$x_1, x_2, \\ldots, x_{k_1}$$$ in your labeling, Li Chen's subtree consists of the vertices labeled $$$y_1, y_2, \\ldots, y_{k_2}$$$ in his labeling. The values of $$$x_1, x_2, \\ldots, x_{k_1}$$$ and $$$y_1, y_2, \\ldots, y_{k_2}$$$ are known to both of you. The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most $$$5$$$ questions, each of which is in one of the following two forms: A x: Andrew will look at vertex $$$x$$$ in your labeling and tell you the number of this vertex in Li Chen's labeling. B y: Andrew will look at vertex $$$y$$$ in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.", "input_spec": null, "output_spec": null, "sample_inputs": ["1\n3\n1 2\n2 3\n1\n1\n1\n2\n2\n1", "2\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n4\n1 3 4 5\n3\n3 5 2\n3\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n3\n1 2 3\n3\n4 1 6\n5"], "sample_outputs": ["A 1\nB 2\nC 1", "B 2\nC 1\nA 1\nC -1"], "notes": "NoteFor the first sample, Li Chen's hidden permutation is $$$[2, 3, 1]$$$, and for the second, his hidden permutation is $$$[5, 3, 2, 4, 1, 6]$$$ for both cases.In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose: In the first question, you ask Andrew to look at node $$$1$$$ in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with $$$2$$$. At this point, you know that both of your subtrees contain the same node (i.e. node $$$1$$$ according to your labeling), so you can output \"C 1\" and finish. However, you can also ask Andrew to look at node $$$2$$$ in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with $$$1$$$ (this step was given with the only reason\u00a0\u2014 to show you how to ask questions).For the second sample, there are two test cases. The first looks is the one from the statement: We first ask \"B 2\", and Andrew will tell us $$$3$$$. In this case, we know $$$3$$$ is a common vertex, and moreover, any subtree with size $$$3$$$ that contains node $$$3$$$ must contain node $$$1$$$ as well, so we can output either \"C 1\" or \"C 3\" as our answer.In the second case in the second sample, the situation looks as follows: In this case, you know that the only subtree of size $$$3$$$ that doesn't contain node $$$1$$$ is subtree $$$4,5,6$$$. You ask Andrew for the label of node $$$1$$$ in Li Chen's labelling and Andrew says $$$5$$$. In this case, you know that Li Chen's subtree doesn't contain node $$$1$$$, so his subtree must be consist of the nodes $$$4,5,6$$$ (in your labelling), thus the two subtrees have no common nodes."}, "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 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 \u30ce\u30fc\u30c9\u6570\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}"}, {"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": "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}"}], "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 \u30ce\u30fc\u30c9\u6570\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"} {"nl": {"description": "Alice lives on a flat planet that can be modeled as a square grid of size $$$n \\times n$$$, with rows and columns enumerated from $$$1$$$ to $$$n$$$. We represent the cell at the intersection of row $$$r$$$ and column $$$c$$$ with ordered pair $$$(r, c)$$$. Each cell in the grid is either land or water. An example planet with $$$n = 5$$$. It also appears in the first sample test. Alice resides in land cell $$$(r_1, c_1)$$$. She wishes to travel to land cell $$$(r_2, c_2)$$$. At any moment, she may move to one of the cells adjacent to where she is\u2014in one of the four directions (i.e., up, down, left, or right).Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells $$$(r_s, c_s)$$$ and $$$(r_t, c_t)$$$ is $$$(r_s-r_t)^2 + (c_s-c_t)^2$$$.For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from $$$(r_1, c_1)$$$ to $$$(r_2, c_2)$$$. If no tunnel needs to be created, the cost is $$$0$$$.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$) \u2014 the width of the square grid. The second line contains two space-separated integers $$$r_1$$$ and $$$c_1$$$ ($$$1 \\leq r_1, c_1 \\leq n$$$) \u2014 denoting the cell where Alice resides. The third line contains two space-separated integers $$$r_2$$$ and $$$c_2$$$ ($$$1 \\leq r_2, c_2 \\leq n$$$) \u2014 denoting the cell to which Alice wishes to travel. Each of the following $$$n$$$ lines contains a string of $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th such line ($$$1 \\leq i, j \\leq n$$$) is 0 if $$$(i, j)$$$ is land or 1 if $$$(i, j)$$$ is water. It is guaranteed that $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are land.", "output_spec": "Print an integer that is the minimum possible cost of creating at most one tunnel so that Alice could travel from $$$(r_1, c_1)$$$ to $$$(r_2, c_2)$$$.", "sample_inputs": ["5\n1 1\n5 5\n00001\n11111\n00111\n00110\n00110", "3\n1 3\n3 1\n010\n101\n010"], "sample_outputs": ["10", "8"], "notes": "NoteIn the first sample, a tunnel between cells $$$(1, 4)$$$ and $$$(4, 5)$$$ should be created. The cost of doing so is $$$(1-4)^2 + (4-5)^2 = 10$$$, which is optimal. This way, Alice could walk from $$$(1, 1)$$$ to $$$(1, 4)$$$, use the tunnel from $$$(1, 4)$$$ to $$$(4, 5)$$$, and lastly walk from $$$(4, 5)$$$ to $$$(5, 5)$$$.In the second sample, clearly a tunnel between cells $$$(1, 3)$$$ and $$$(3, 1)$$$ needs to be created. The cost of doing so is $$$(1-3)^2 + (3-1)^2 = 8$$$."}, "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 r1, c1, r2, c2 = ni() - 1\n val g = Array.ofDim[Array[Boolean]](N) // land\u304b\u3069\u3046\u304b\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 // \u9023\u7d50\u3055\u308c\u3066\u308b\u306e\u3067\u30c8\u30f3\u30cd\u30eb\u3044\u3089\u306a\u3044\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 // \u5468\u8fba\u3060\u3051\u306b\u3057\u3066\u3082\u3044\u3044\u3051\u30692500 * 2500\u3067\u307e\u306b\u3042\u3046\u304b\u3089\u3084\u3089\u306a\u3044\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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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"}, {"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"} {"nl": {"description": "Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: \u2009+\u2009 ai\u00a0\u2014 add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer. \u2009-\u2009 ai\u00a0\u2014 delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s\u00a0\u2014 count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s\u2009=\u2009010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.", "input_spec": "The first line of the input contains an integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci\u00a0\u2014 the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0\u2009\u2264\u2009ai\u2009<\u20091018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.", "output_spec": "For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.", "sample_inputs": ["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"], "sample_outputs": ["2\n1\n2\n1\n1", "1"], "notes": "NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000. "}, "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": "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"}, {"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"} {"nl": {"description": "It is the easy version of the problem. The only difference is that in this version $$$k = 3$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \\ldots, a_k$$$, such that: $$$a_1 + a_2 + \\ldots + a_k = n$$$ $$$LCM(a_1, a_2, \\ldots, a_k) \\le \\frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \\ldots, a_k$$$.We can show that for given constraints the answer always exists.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 10^4)$$$ \u00a0\u2014 the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \\le n \\le 10^9$$$, $$$k = 3$$$).", "output_spec": "For each test case print $$$k$$$ positive integers $$$a_1, a_2, \\ldots, a_k$$$, for which all conditions are satisfied.", "sample_inputs": ["3\n3 3\n8 3\n14 3"], "sample_outputs": ["1 1 1\n4 2 2\n2 6 6"], "notes": null}, "positive_code": [{"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 xs = readLine.split(' ').toList.map(x => x.toInt)\r\n val n = xs(0)\r\n val k = xs(1)\r\n val values = n match {\r\n case k if k % 2 == 1 => List(1, (k-1)/2, (k-1)/2)\r\n case k if k % 4 == 2 => List(2, (k-2)/2, (k-2)/2)\r\n case k if k % 4 == 0 => List(k/4, k/4, k/2)\r\n }\r\n println(values.map(x => x.toString()).mkString(\" \"))\r\n }\r\n}\r\n"}], "negative_code": [{"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 xs = readLine.split(' ').toList.map(x => x.toInt)\r\n val n = xs(0)\r\n val k = xs(1)\r\n val values = n match {\r\n case k if k % 2 == 1 => List(1, (k-1)/2, (k-1)/2)\r\n case k if k % 4 == 2 => List(2, (k-2)/2, (k-2)/2)\r\n case k if k % 4 == 0 => List(k/4, k/4, k/2)\r\n }\r\n println(values)\r\n }\r\n}"}], "src_uid": "842a0587147591ea38a20638f3a7960d"} {"nl": {"description": "You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \\le x \\le 10^9$$$; $$$1 \\le y, k \\le 10^9$$$) \u2014 the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.", "output_spec": "For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.", "sample_inputs": ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"], "sample_outputs": ["14\n33\n25\n2000000003\n1000000001999999999"], "notes": null}, "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 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}"}, {"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": "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"}, {"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"}], "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"} {"nl": {"description": "A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) is displayed, squares 1,\u20092,\u2009... ,\u2009i\u2009-\u20091 has the saturation k, squares i\u2009+\u20091,\u2009i\u2009+\u20092,\u2009... ,\u2009n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture. For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.", "input_spec": "We are given 3 space-separated integers n, k, t (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100, 0\u2009\u2264\u2009t\u2009\u2264\u2009100).", "output_spec": "Print n numbers. The i-th of them should be equal to ai.", "sample_inputs": ["10 10 54", "11 13 37"], "sample_outputs": ["10 10 10 10 10 4 0 0 0 0", "13 13 13 13 0 0 0 0 0 0 0"], "notes": null}, "positive_code": [{"source_code": "object P71B extends App {\n val Array(n, k, t) = readLine().split(\" \").map(_.toInt)\n val c = (n * t / 100.0)\n print((k + \" \") * c.toInt + (((c - c.toInt.toFloat) * k).toInt + \" \") * (if (t < 100) 1 else 0) +\n \"0 \" * (n - c.toInt - 1))\n}"}], "negative_code": [{"source_code": "object P71B extends App {\n val Array(n,k,t) = readLine.split(\" \").map(_.toInt)\n val p = (n * t / 100.0)\n val c = p.toInt\n val r = p - c.toFloat\n print((k + \" \") * c + (if (r*k > 0 || t == 0) (r*k).toInt + \" \" else \"\") + (\"0 \" * (n-c-1)))\n}"}, {"source_code": "object P71B extends App {\n \n val Array(n,k,t) = readLine.split(\" \").map(_.toInt)\n \n val p = (n * t / 100.0)\n val c = p.toInt\n val r = p - c.toFloat\n \n print((k + \" \") * c + (r*k).toInt + \" \" + (\"0 \" * (n-c-1)))\n\n}"}, {"source_code": "object P71B extends App {\n \n val Array(n,k,t) = readLine.split(\" \").map(_.toInt)\n \n val c = (n * t / 100.0).toInt\n \n print((k + \" \") * c + \"1 \" + (\"0 \" * (n-c-1)))\n\n}"}, {"source_code": "object P71B extends App {\n \n val Array(n,k,t) = readLine.split(\" \").map(_.toInt)\n \n val c = (n * t / 100.0).toInt\n \n print((k + \" \") * c) + \"1 \" + (\"0 \" * (n-c-1))\n\n}"}, {"source_code": "object P71B extends App {\n val Array(n,k,t) = readLine.split(\" \").map(_.toInt)\n val p = (n * t / 100.0)\n val c = p.toInt\n val r = p - c.toFloat\n print((k + \" \") * c + (if (r*k > 0) (r*k).toInt + \" \" else \"\") + (\"0 \" * (n-c-1)))\n}"}, {"source_code": "object P71B extends App {\n val Array(n,k,t) = readLine.split(\" \").map(_.toInt)\n val p = (n * t / 100.0)\n val c = p.toInt\n val r = p - c.toFloat\n print((k + \" \") * c + (if (r*k > 0) (r*k).toInt + \" \") + (\"0 \" * (n-c-1)))\n}"}], "src_uid": "0ad96b6a8032d70df400bf2ad72174bf"} {"nl": {"description": "A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0,\u20090,\u20090,\u20091,\u20091,\u20091,\u20090,\u20090,\u20090] can be a photo of zebra, while the photo [0,\u20090,\u20090,\u20091,\u20091,\u20091,\u20091] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the width of the photo. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u20091) \u2014 the description of the photo. If ai is zero, the i-th column is all black. If ai is one, then the i-th column is all white.", "output_spec": "If the photo can be a photo of zebra, print \"YES\" (without quotes). Otherwise, print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["9\n0 0 0 1 1 1 0 0 0", "7\n0 0 0 1 1 1 1", "5\n1 1 1 1 1", "8\n1 1 1 0 0 0 1 1", "9\n1 1 0 1 1 0 1 1 0"], "sample_outputs": ["YES", "NO", "YES", "NO", "NO"], "notes": "NoteThe first two examples are described in the statements.In the third example all pixels are white, so the photo can be a photo of zebra.In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra."}, "positive_code": [{"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": "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 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"} {"nl": {"description": "You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n). In other words, let's consider all n2 pairs of numbers, picked from the given array.For example, in sequence a\u2009=\u2009{3,\u20091,\u20095} are 9 pairs of numbers: (3,\u20093),\u2009(3,\u20091),\u2009(3,\u20095),\u2009(1,\u20093),\u2009(1,\u20091),\u2009(1,\u20095),\u2009(5,\u20093),\u2009(5,\u20091),\u2009(5,\u20095).Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (p1, q1) is lexicographically less than pair (p2, q2) only if either p1 < p2, or p1 = p2 and q1 < q2.Then the sequence, mentioned above, will be sorted like that: (1,\u20091),\u2009(1,\u20093),\u2009(1,\u20095),\u2009(3,\u20091),\u2009(3,\u20093),\u2009(3,\u20095),\u2009(5,\u20091),\u2009(5,\u20093),\u2009(5,\u20095)Let's number all the pair in the sorted list from 1 to n2. Your task is formulated like this: you should find the k-th pair in the ordered list of all possible pairs of the array you've been given.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n2). The second line contains the array containing n integers a1, a2, ..., an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). The numbers in the array can coincide. All numbers are separated with spaces. Please do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout, streams or the %I64d specificator instead.", "output_spec": "In the single line print two numbers \u2014 the sought k-th pair.", "sample_inputs": ["2 4\n2 1", "3 2\n3 1 5"], "sample_outputs": ["2 2", "1 3"], "notes": "NoteIn the first sample the sorted sequence for the given array looks as: (1,\u20091),\u2009(1,\u20092),\u2009(2,\u20091),\u2009(2,\u20092). The 4-th of them is pair (2,\u20092).The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1,\u20093)."}, "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[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"}, {"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"} {"nl": {"description": "There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \\le i \\le r$$$. This move can be done only if $$$r+1 \\le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \\le i \\le r$$$. This move can be done only if $$$l-1 \\ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.", "output_spec": "For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).", "sample_inputs": ["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"], "sample_outputs": ["2\n0\n2\n4\n1"], "notes": "NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$."}, "positive_code": [{"source_code": "//package codeforces.contests._1433\n\n\nobject YetAnotherBookshelf {\n\n import scala.annotation.tailrec\n \n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt()) {\n val n = io.StdIn.readInt()\n\n val digits = io.StdIn.readLine.split(\" \").map(_.toInt)\n\n @tailrec\n def loop(ls: List[Int], acc: List[Int] = Nil): List[Int] = {\n if (ls.isEmpty) acc else {\n val afterOnesDropped = ls.dropWhile(_ == 1)\n if (afterOnesDropped.isEmpty) acc else {\n val (zeroes, afterZeroesDropped) = afterOnesDropped.span(_ == 0)\n if (afterZeroesDropped.isEmpty) acc else {\n loop(afterZeroesDropped, zeroes.length :: acc)\n }\n }\n }\n }\n\n val zeroesInThMiddle = loop(digits.toList.dropWhile(_ == 0))\n\n println {\n zeroesInThMiddle.sum\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "1c07882651ef6ebfc05e777d562e28b9"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to say the number of such positive integers $$$x$$$ such that $$$x$$$ divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.For example, if the array $$$a$$$ will be $$$[2, 4, 6, 2, 10]$$$, then $$$1$$$ and $$$2$$$ divide each number from the array (so the answer for this test is $$$2$$$).", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 4 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^{12}$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer \u2014 the number of such positive integers $$$x$$$ such that $$$x$$$ divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array).", "sample_inputs": ["5\n1 2 3 4 5", "6\n6 90 12 18 30 18"], "sample_outputs": ["1", "4"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together. Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of width wi pixels and height hi pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is W\u2009\u00d7\u2009H, where W is the total sum of all widths and H is the maximum height of all the photographed friends.As is usually the case, the friends made n photos \u2014 the j-th (1\u2009\u2264\u2009j\u2009\u2264\u2009n) photo had everybody except for the j-th friend as he was the photographer.Print the minimum size of each made photo in pixels. ", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000) \u2014 the number of friends. Then n lines follow: the i-th line contains information about the i-th friend. The line contains a pair of integers wi,\u2009hi (1\u2009\u2264\u2009wi\u2009\u2264\u200910,\u20091\u2009\u2264\u2009hi\u2009\u2264\u20091000) \u2014 the width and height in pixels of the corresponding rectangle.", "output_spec": "Print n space-separated numbers b1,\u2009b2,\u2009...,\u2009bn, where bi \u2014 the total number of pixels on the minimum photo containing all friends expect for the i-th one.", "sample_inputs": ["3\n1 10\n5 5\n10 1", "3\n2 1\n1 2\n2 1"], "sample_outputs": ["75 110 60", "6 4 6"], "notes": null}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given three positive (i.e. strictly greater than zero) integers $$$x$$$, $$$y$$$ and $$$z$$$.Your task is to find positive integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$x = \\max(a, b)$$$, $$$y = \\max(a, c)$$$ and $$$z = \\max(b, c)$$$, or determine that it is impossible to find such $$$a$$$, $$$b$$$ and $$$c$$$.You have to answer $$$t$$$ independent test cases. Print required $$$a$$$, $$$b$$$ and $$$c$$$ in any (arbitrary) order.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \\le x, y, z \\le 10^9$$$).", "output_spec": "For each test case, print the answer: \"NO\" in the only line of the output if a solution doesn't exist; or \"YES\" in the first line and any valid triple of positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\le a, b, c \\le 10^9$$$) in the second line. You can print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. ", "sample_inputs": ["5\n3 2 3\n100 100 100\n50 49 49\n10 30 20\n1 1000000000 1000000000"], "sample_outputs": ["YES\n3 2 1\nYES\n100 100 100\nNO\nNO\nYES\n1 1 1000000000"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": " \u2014 Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? \u2014 Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai \u2014 some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?", "input_spec": "The first line contains a single integer n \u2014 the initial number of trees in the woodland belt, 2\u2009\u2264\u2009n. The second line contains space-separated integers ai \u2014 the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value. to get 30 points, you need to solve the problem with constraints: n\u2009\u2264\u2009100 (subproblem A1); to get 100 points, you need to solve the problem with constraints: n\u2009\u2264\u20093\u00b7105 (subproblems A1+A2). ", "output_spec": "In the first line print two integers \u2014 the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k. In the next line print k integers \u2014 the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right. If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.", "sample_inputs": ["5\n1 2 3 1 2", "5\n1 -2 3 1 -2"], "sample_outputs": ["8 1\n1", "5 2\n2 5"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!When building the graph, he needs four conditions to be satisfied: It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. The number of vertices must be exactly $$$n$$$\u00a0\u2014 a number he selected. This number is not necessarily prime. The total number of edges must be prime. The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for $$$n = 4$$$. The first graph (left one) is invalid as the degree of vertex $$$2$$$ (and $$$4$$$) equals to $$$1$$$, which is not prime. The second graph (middle one) is invalid as the total number of edges is $$$4$$$, which is not a prime number. The third graph (right one) is a valid answer for $$$n = 4$$$. Note that the graph can be disconnected.Please help Bob to find any such graph!", "input_spec": "The input consists of a single integer $$$n$$$ ($$$3 \\leq n \\leq 1\\,000$$$)\u00a0\u2014 the number of vertices.", "output_spec": "If there is no graph satisfying the conditions, print a single line containing the integer $$$-1$$$. Otherwise, first print a line containing a prime number $$$m$$$ ($$$2 \\leq m \\leq \\frac{n(n-1)}{2}$$$)\u00a0\u2014 the number of edges in the graph. Then, print $$$m$$$ lines, the $$$i$$$-th of which containing two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \\leq u_i, v_i \\leq n$$$)\u00a0\u2014 meaning that there is an edge between vertices $$$u_i$$$ and $$$v_i$$$. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected.", "sample_inputs": ["4", "8"], "sample_outputs": ["5\n1 2\n1 3\n2 3\n2 4\n3 4", "13\n1 2\n1 3\n2 3\n1 4\n2 4\n1 5\n2 5\n1 6\n2 6\n1 7\n1 8\n5 8\n7 8"], "notes": "NoteThe first example was described in the statement.In the second example, the degrees of vertices are $$$[7, 5, 2, 2, 3, 2, 2, 3]$$$. Each of these numbers is prime. Additionally, the number of edges, $$$13$$$, is also a prime number, hence both conditions are satisfied. "}, "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 LIMIT = 10000\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 Array(n) = readInts(1)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n var p = n\n while (!isPrime(p)) p += 1\n\n println(p)\n for (i <- 1 to n) {\n val j = i % n + 1\n println(s\"$i $j\")\n }\n\n i = 1\n var c = 1\n while (c <= p - n) {\n val j = i % n + 2\n println(s\"$i $j\")\n if ((i - 1) % 4 == 0) i += 1 else i += 3\n c += 1\n }\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "17d29a0c2ab4e4be14fe3bdeb10d1e55"} {"nl": {"description": "This is an interactive problem.Imur Ishakov decided to organize a club for people who love to play the famous game \u00abThe hat\u00bb. The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i\u2009+\u20091 (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.You can ask questions of form \u00abwhich number was received by student i?\u00bb, and the goal is to determine whether the desired pair exists in no more than 60 questions.", "input_spec": "At the beginning the even integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) is given\u00a0\u2014 the total number of students. You are allowed to ask no more than 60 questions.", "output_spec": "To ask the question about the student i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), you should print \u00ab? i\u00bb. Then from standard output you can read the number ai received by student i (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). When you find the desired pair, you should print \u00ab! i\u00bb, where i is any student who belongs to the pair (1\u2009\u2264\u2009i\u2009\u2264\u2009n). If you determined that such pair doesn't exist, you should output \u00ab! -1\u00bb. In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the total number of students. In the second line print n integers ai (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or \u2009-\u20091. The hacked solution will not have direct access to the sequence ai.", "sample_inputs": ["8\n\n\n\n2\n\n\n\n2", "6\n\n\n\n1\n\n\n\n2\n\n\n\n3 \n\n\n\n2\n\n\n\n1\n\n\n\n0"], "sample_outputs": ["? 4\n\n\n\n? 8\n\n\n\n! 4", "? 1\n\n\n\n? 2\n\n\n\n? 3\n\n\n\n? 4\n\n\n\n? 5\n\n\n\n? 6\n\n\n\n! -1"], "notes": "NoteInput-output in statements illustrates example interaction.In the first sample the selected sequence is 1,\u20092,\u20091,\u20092,\u20093,\u20094,\u20093,\u20092In the second sample the selection sequence is 1,\u20092,\u20093,\u20092,\u20091,\u20090."}, "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\n def query(i: Int): Int = {\n out.println(s\"? $i\")\n out.flush()\n ni()\n }\n\n def answer(i: Int): Unit = {\n out.println(s\"! $i\")\n out.flush()\n }\n\n def f(i: Int): Int = {\n query(i + 1) - query((i + N / 2) % N + 1)\n }\n\n val V = Array.fill[Int](N)(1e9.toInt)\n\n var l = 0\n var r = N / 2\n V(0) = f(0)\n V(N / 2) = -V(0) // \u3061\u3087\u3046\u3069\u53cd\u5bfe\u306a\u306e\u3067\n\n while(r - l > 1) {\n val mid = (l + r) / 2\n V(mid) = f(mid)\n\n // \u7bc4\u56f2\u306b0\u3092\u542b\u307e\u306a\u3044\u5834\u5408\u306f\u3053\u3063\u3061\u5074\u3058\u3083\u306a\u3044\n if (V(l).toLong * V(mid) > 0) { // (+, +), (-, -) \u306e\u5834\u5408\u306f0\u3092\u542b\u307e\u306a\u3044\n l = mid\n } else {\n r = mid\n }\n }\n\n if (V(l) == 0) answer(l + 1)\n else if (V(r) == 0) answer(r + 1)\n else answer(-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[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\n def query(i: Int): Int = {\n out.println(s\"? $i\")\n out.flush()\n ni()\n }\n\n def answer(i: Int): Unit = {\n out.println(s\"! $i\")\n out.flush()\n }\n\n def f(i: Int): Int = {\n query(i) - query((i + N / 2) % N)\n }\n\n val V = Array.fill[Int](N)(1e9.toInt)\n\n var l = 0\n var r = N / 2\n V(0) = f(0)\n V(N / 2) = -V(0) // \u3061\u3087\u3046\u3069\u53cd\u5bfe\u306a\u306e\u3067\n\n while(r - l > 1) {\n val mid = (l + r) / 2\n V(mid) = f(mid)\n\n // \u7bc4\u56f2\u306b0\u3092\u542b\u307e\u306a\u3044\u5834\u5408\u306f\u3053\u3063\u3061\u5074\u3058\u3083\u306a\u3044\n if (V(l) > 0 && V(mid) > 0 || V(l) < 0 && V(0) < 0) {\n l = mid\n } else {\n r = mid\n }\n }\n\n if (V(l) == 0) answer(l)\n else if (V(r) == 0) answer(r)\n else answer(-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[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\n def query(i: Int): Int = {\n out.println(s\"? $i\")\n out.flush()\n ni()\n }\n\n def answer(i: Int): Unit = {\n out.println(s\"! $i\")\n out.flush()\n }\n\n def f(i: Int): Int = {\n query(i + 1) - query((i + N / 2) % N + 1)\n }\n\n val V = Array.fill[Int](N)(1e9.toInt)\n\n var l = 0\n var r = N / 2\n V(0) = f(0)\n V(N / 2) = -V(0) // \u3061\u3087\u3046\u3069\u53cd\u5bfe\u306a\u306e\u3067\n\n while(r - l > 1) {\n val mid = (l + r) / 2\n V(mid) = f(mid)\n\n // \u7bc4\u56f2\u306b0\u3092\u542b\u307e\u306a\u3044\u5834\u5408\u306f\u3053\u3063\u3061\u5074\u3058\u3083\u306a\u3044\n if (V(l) > 0 && V(mid) > 0 || V(l) < 0 && V(0) < 0) {\n l = mid\n } else {\n r = mid\n }\n }\n\n if (V(l) == 0) answer(l + 1)\n else if (V(r) == 0) answer(r + 1)\n else answer(-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[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": "49846b8fb0aea6b21e7986e19b8c8316"} {"nl": {"description": "You are given a line of $$$n$$$ colored squares in a row, numbered from $$$1$$$ to $$$n$$$ from left to right. The $$$i$$$-th square initially has the color $$$c_i$$$.Let's say, that two squares $$$i$$$ and $$$j$$$ belong to the same connected component if $$$c_i = c_j$$$, and $$$c_i = c_k$$$ for all $$$k$$$ satisfying $$$i < k < j$$$. In other words, all squares on the segment from $$$i$$$ to $$$j$$$ should have the same color.For example, the line $$$[3, 3, 3]$$$ has $$$1$$$ connected component, while the line $$$[5, 2, 4, 4]$$$ has $$$3$$$ connected components.The game \"flood fill\" is played on the given line as follows: At the start of the game you pick any starting square (this is not counted as a turn). Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 5000$$$)\u00a0\u2014 the number of squares. The second line contains integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\le c_i \\le 5000$$$)\u00a0\u2014 the initial colors of the squares.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of the turns needed.", "sample_inputs": ["4\n5 2 2 1", "8\n4 5 2 2 1 3 5 5", "1\n4"], "sample_outputs": ["2", "4", "0"], "notes": "NoteIn the first example, a possible way to achieve an optimal answer is to pick square with index $$$2$$$ as the starting square and then play as follows: $$$[5, 2, 2, 1]$$$ $$$[5, 5, 5, 1]$$$ $$$[1, 1, 1, 1]$$$ In the second example, a possible way to achieve an optimal answer is to pick square with index $$$5$$$ as the starting square and then perform recoloring into colors $$$2, 3, 5, 4$$$ in that order.In the third example, the line already consists of one color only."}, "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 C = na(N)\n\n val INF = 1e9.toInt\n // 2\u306f\u3001\u6700\u5f8c\u306e\u64cd\u4f5c\u3067\u3053\u306e\u30d6\u30ed\u30c3\u30af\u3092\u4e00\u756a\u5de6\u306e\u8272\u306b\u3057\u305f\u5834\u5408\u30920\u3001\u53f3\u306b\u3057\u305f\u5834\u5408\u30921\u3068\u3059\u308b\n val dp = Array.fill[Int](2, 2, N)(INF)\n\n // \u7bc4\u56f2\u304c1\u306e\u5834\u5408\u306f\u30b3\u30b9\u30c80\n REP(N) { i =>\n REP(2) { x =>\n dp(0)(x)(i) = 0\n }\n }\n\n // \u7bc4\u56f2DP\u306a\u306e\u3067\u7bc4\u56f2\u30922 -> N \u306b\u5e83\u3052\u3066\u3044\u304f\n REP(N - 1) { i =>\n val len = i + 2\n val p = i & 1\n REP(2) { x =>\n import java.util\n util.Arrays.fill(dp(p^1)(x), INF)\n }\n\n var l = 0\n while (l + len - 1 < N) {\n val r = l + len - 1\n\n REP(2) { x_old =>\n REP(2) { x_new =>\n val i_new = if (x_new == 0) l else r\n val l_old = if (x_new == 0) l + 1 else l\n val r_old = if (x_new == 1) r - 1 else r\n\n // \u7bc4\u56f2\u30c1\u30a7\u30c3\u30af\u91cd\u8981\n if (l_old >= 0 && l_old < N && r_old >= 0 && r_old < N) {\n val i_old = if (x_old == 0) l_old else r_old\n\n val cost = if (C(i_new) == C(i_old)) 0 else 1\n val v = dp(p)(x_old)(l_old) + cost\n dp(p^1)(x_new)(l) = min(dp(p^1)(x_new)(l), v)\n }\n }\n }\n l += 1\n }\n\n// debug(s\"DP $len\")\n// REP(2) { x =>\n// val v = ArrayBuffer[Int]()\n// REP(N) { j =>\n// v += dp(p^1)(x)(j)\n// }\n// debug(s\"[$x] ${v.mkString(\" \")}\")\n// }\n }\n\n val P = (N - 1) & 1\n val ans = min(dp(P)(0)(0), dp(P)(1)(0))\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": "4ee194d8dc1d25eb8b186603ee71125e"} {"nl": {"description": "Ilya lives in a beautiful city of Chordalsk.There are $$$n$$$ houses on the street Ilya lives, they are numerated from $$$1$$$ to $$$n$$$ from left to right; the distance between every two neighboring houses is equal to $$$1$$$ unit. The neighboring houses are $$$1$$$ and $$$2$$$, $$$2$$$ and $$$3$$$, ..., $$$n-1$$$ and $$$n$$$. The houses $$$n$$$ and $$$1$$$ are not neighboring.The houses are colored in colors $$$c_1, c_2, \\ldots, c_n$$$ so that the $$$i$$$-th house is colored in the color $$$c_i$$$. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.Ilya wants to select two houses $$$i$$$ and $$$j$$$ so that $$$1 \\leq i < j \\leq n$$$, and they have different colors: $$$c_i \\neq c_j$$$. He will then walk from the house $$$i$$$ to the house $$$j$$$ the distance of $$$(j-i)$$$ units.Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.Help Ilya, find this maximum possible distance.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 300\\,000$$$)\u00a0\u2014 the number of cities on the street. The second line contains $$$n$$$ integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\leq c_i \\leq n$$$)\u00a0\u2014 the colors of the houses. It is guaranteed that there is at least one pair of indices $$$i$$$ and $$$j$$$ so that $$$1 \\leq i < j \\leq n$$$ and $$$c_i \\neq c_j$$$.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible distance Ilya can walk.", "sample_inputs": ["5\n1 2 3 2 3", "3\n1 2 1", "7\n1 1 3 1 1 1 1"], "sample_outputs": ["4", "1", "4"], "notes": "NoteIn the first example the optimal way is to walk from the first house to the last one, where Ilya can walk the distance of $$$5-1 = 4$$$ units.In the second example the optimal way is to either walk from the first house to the second or from the second to the third. Both these ways have the distance of $$$1$$$ unit.In the third example the optimal way is to walk from the third house to the last one, where Ilya can walk the distance of $$$7-3 = 4$$$ units. "}, "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": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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"}, {"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"} {"nl": {"description": "Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:There are $$$n$$$ new cities located in Prefecture X. Cities are numbered from $$$1$$$ to $$$n$$$. City $$$i$$$ is located $$$x_i$$$ km North of the shrine and $$$y_i$$$ km East of the shrine. It is possible that $$$(x_i, y_i) = (x_j, y_j)$$$ even when $$$i \\ne j$$$.Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. Building a power station in City $$$i$$$ will cost $$$c_i$$$ yen; Making a connection between City $$$i$$$ and City $$$j$$$ will cost $$$k_i + k_j$$$ yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City $$$i$$$ and City $$$j$$$ are connected by a wire, the wire will go through any shortest path from City $$$i$$$ to City $$$j$$$. Thus, the length of the wire if City $$$i$$$ and City $$$j$$$ are connected is $$$|x_i - x_j| + |y_i - y_j|$$$ km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.", "input_spec": "First line of input contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 2000$$$) \u2014 the number of cities. Then, $$$n$$$ lines follow. The $$$i$$$-th line contains two space-separated integers $$$x_i$$$ ($$$1 \\leq x_i \\leq 10^6$$$) and $$$y_i$$$ ($$$1 \\leq y_i \\leq 10^6$$$) \u2014 the coordinates of the $$$i$$$-th city. The next line contains $$$n$$$ space-separated integers $$$c_1, c_2, \\dots, c_n$$$ ($$$1 \\leq c_i \\leq 10^9$$$) \u2014 the cost of building a power station in the $$$i$$$-th city. The last line contains $$$n$$$ space-separated integers $$$k_1, k_2, \\dots, k_n$$$ ($$$1 \\leq k_i \\leq 10^9$$$).", "output_spec": "In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer $$$v$$$ \u2014 the number of power stations to be built. Next, print $$$v$$$ space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from $$$1$$$ to $$$n$$$ and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer $$$e$$$ \u2014 the number of connections to be made. Finally, print $$$e$$$ pairs of integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le n$$$, $$$a \\ne b$$$), denoting that a connection between City $$$a$$$ and City $$$b$$$ will be made. Each unordered pair of cities should be included at most once (for each $$$(a, b)$$$ there should be no more $$$(a, b)$$$ or $$$(b, a)$$$ pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.", "sample_inputs": ["3\n2 3\n1 1\n3 2\n3 2 3\n3 2 3", "3\n2 1\n1 2\n3 3\n23 2 23\n3 2 3"], "sample_outputs": ["8\n3\n1 2 3 \n0", "27\n1\n2 \n2\n1 2\n2 3"], "notes": "NoteFor the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red):For the first example, the cost of building power stations in all cities is $$$3 + 2 + 3 = 8$$$. It can be shown that no configuration costs less than 8 yen.For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is $$$2 \\cdot (3 + 2) = 10$$$. The cost of connecting City 2 and City 3 is $$$3 \\cdot (2 + 3) = 15$$$. Thus the total cost is $$$2 + 10 + 15 = 27$$$. It can be shown that no configuration costs less than 27 yen."}, "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 Method(tpe: Int, connectTo: Int)\n case class Visit(node: Int, cost: Long, method: Method) extends Comparable[Visit] {\n override def compareTo(o: Visit): Int = java.lang.Long.compare(cost, o.cost)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val (x, y) = na2(n)\n val c, k = na(n)\n\n def dijk(): (Array[Method], Long) = {\n val d = Array.fill[Long](n)(Long.MaxValue / 2)\n val methods = Array.ofDim[Method](n)\n val visited = Array.ofDim[Boolean](n)\n val queue = new java.util.PriorityQueue[Visit]()\n REP(n) { i =>\n queue.add(Visit(i, c(i), Method(0, -1)))\n d(i) = c(i)\n }\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (d(v.node) == v.cost) {\n visited(v.node) = true\n methods(v.node) = v.method\n REP(n) { u =>\n if (!visited(u)) {\n val next = (k(u) + k(v.node)).toLong * (abs(x(u)-(x(v.node))) + abs(y(u)-y(v.node)))\n if (d(u) > next) {\n d(u) = next\n queue.add(Visit(u, next, Method(1, v.node)))\n }\n }\n }\n }\n }\n\n (methods, d.sum)\n }\n\n val (methods, total) = dijk()\n out.println(total)\n\n val build = ArrayBuffer[Int]()\n val connect = ArrayBuffer[(Int, Int)]()\n REP(n) { i =>\n if (methods(i).tpe == 0) {\n build += i + 1\n } else {\n connect += ((i + 1, methods(i).connectTo + 1))\n }\n }\n out.println(build.length)\n out.println(build.mkString(\" \"))\n out.println(connect.length)\n REP(connect.length) { i =>\n out.println(s\"${connect(i)._1} ${connect(i)._2}\")\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 case class Method(tpe: Int, connectTo: Int)\n case class Visit(node: Int, cost: Long, method: Method) extends Comparable[Visit] {\n override def compareTo(o: Visit): Int = java.lang.Long.compare(cost, o.cost)\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val (x, y) = na2(n)\n val c, k = na(n)\n\n def dijk(): (Array[Method], Long) = {\n val d = Array.fill[Long](n)(Long.MaxValue / 2)\n val methods = Array.ofDim[Method](n)\n val queue = new java.util.PriorityQueue[Visit]()\n REP(n) { i =>\n queue.add(Visit(i, c(i), Method(0, -1)))\n d(i) = c(i)\n }\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (d(v.node) == v.cost) {\n methods(v.node) = v.method\n REP(n) { u =>\n if (u != v.node) {\n val next = (k(u) + k(v.node)).toLong * (abs(x(u)-(x(v.node))) + abs(y(u)-y(v.node)))\n if (d(u) > next) {\n d(u) = next\n queue.add(Visit(u, next, Method(1, v.node)))\n }\n }\n }\n }\n }\n\n (methods, d.sum)\n }\n\n val (methods, total) = dijk()\n out.println(total)\n\n val build = ArrayBuffer[Int]()\n val connect = ArrayBuffer[(Int, Int)]()\n REP(n) { i =>\n if (methods(i).tpe == 0) {\n build += i + 1\n } else {\n connect += ((i + 1, methods(i).connectTo + 1))\n }\n }\n out.println(build.length)\n out.println(build.mkString(\" \"))\n out.println(connect.length)\n REP(connect.length) { i =>\n out.println(s\"${connect(i)._1} ${connect(i)._2}\")\n }\n }\n}"}], "src_uid": "4750f5a5aaa1ef727ebf2376641bd8ed"} {"nl": {"description": "Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109.In the evening after the conference, all n scientists decided to go to the cinema. There are m movies in the cinema they came to. Each of the movies is characterized by two distinct numbers\u00a0\u2014 the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different). Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of scientists. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the index of a language, which the i-th scientist knows. The third line contains a positive integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of movies in the cinema. The fourth line contains m positive integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009109), where bj is the index of the audio language of the j-th movie. The fifth line contains m positive integers c1,\u2009c2,\u2009...,\u2009cm (1\u2009\u2264\u2009cj\u2009\u2264\u2009109), where cj is the index of subtitles language of the j-th movie. It is guaranteed that audio languages and subtitles language are different for each movie, that is bj\u2009\u2260\u2009cj. ", "output_spec": "Print the single integer\u00a0\u2014 the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists. If there are several possible answers print any of them.", "sample_inputs": ["3\n2 3 2\n2\n3 2\n2 3", "6\n6 3 1 1 3 7\n5\n1 2 3 4 5\n2 3 4 5 1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied.In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied. "}, "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"}, {"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"}], "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"} {"nl": {"description": "Sereja has an n\u2009\u00d7\u2009m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h\u2009\u00d7\u2009w, then the component must contain exactly hw cells.A connected component of the same values is a set of cells of the table that meet the following conditions: every two cells of the set have the same value; the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table); it is impossible to add any cell to the set unless we violate the two previous conditions. Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?", "input_spec": "The first line contains integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100;\u00a01\u2009\u2264\u2009k\u2009\u2264\u200910). Next n lines describe the table a: the i-th of them contains m integers ai1,\u2009ai2,\u2009...,\u2009aim (0\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u20091) \u2014 the values in the cells of the i-th row.", "output_spec": "Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed.", "sample_inputs": ["5 5 2\n1 1 1 1 1\n1 1 1 1 1\n1 1 0 1 1\n1 1 1 1 1\n1 1 1 1 1", "3 4 1\n1 0 0 0\n0 1 1 1\n1 1 1 0", "3 4 1\n1 0 0 1\n0 1 1 0\n1 0 0 1"], "sample_outputs": ["1", "-1", "0"], "notes": null}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "The only difference between easy and hard versions are constraints on $$$n$$$ and $$$k$$$.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $$$k$$$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $$$0$$$).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive $$$n$$$ messages, the $$$i$$$-th message will be received from the friend with ID $$$id_i$$$ ($$$1 \\le id_i \\le 10^9$$$).If you receive a message from $$$id_i$$$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with $$$id_i$$$ on the screen): Firstly, if the number of conversations displayed on the screen is $$$k$$$, the last conversation (which has the position $$$k$$$) is removed from the screen. Now the number of conversations on the screen is guaranteed to be less than $$$k$$$ and the conversation with the friend $$$id_i$$$ is not displayed on the screen. The conversation with the friend $$$id_i$$$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $$$n$$$ messages.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 200)$$$ \u2014 the number of messages and the number of conversations your smartphone can show. The second line of the input contains $$$n$$$ integers $$$id_1, id_2, \\dots, id_n$$$ ($$$1 \\le id_i \\le 10^9$$$), where $$$id_i$$$ is the ID of the friend which sends you the $$$i$$$-th message.", "output_spec": "In the first line of the output print one integer $$$m$$$ ($$$1 \\le m \\le min(n, k)$$$) \u2014 the number of conversations shown after receiving all $$$n$$$ messages. In the second line print $$$m$$$ integers $$$ids_1, ids_2, \\dots, ids_m$$$, where $$$ids_i$$$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $$$i$$$ after receiving all $$$n$$$ messages.", "sample_inputs": ["7 2\n1 2 3 2 1 3 2", "10 4\n2 3 3 1 1 2 1 2 3 3"], "sample_outputs": ["2\n2 1", "3\n1 3 2"], "notes": "NoteIn the first example the list of conversations will change in the following way (in order from the first to last message): $$$[]$$$; $$$[1]$$$; $$$[2, 1]$$$; $$$[3, 2]$$$; $$$[3, 2]$$$; $$$[1, 3]$$$; $$$[1, 3]$$$; $$$[2, 1]$$$. In the second example the list of conversations will change in the following way: $$$[]$$$; $$$[2]$$$; $$$[3, 2]$$$; $$$[3, 2]$$$; $$$[1, 3, 2]$$$; and then the list will not change till the end. "}, "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\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"}, {"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": "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"} {"nl": {"description": "The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type \u2014 the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.", "input_spec": "The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) \u2014 the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \\dots, t_n$$$ ($$$1 \\le t_i \\le 2 \\cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot10^5$$$.", "output_spec": "Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ \u2014 the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$1 \\le c_i \\le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.", "sample_inputs": ["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"], "sample_outputs": ["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $$$2 \\cdot n$$$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $$$n$$$ people in each row). Students are numbered from $$$1$$$ to $$$n$$$ in each row in order from left to right. Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $$$2n$$$ students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of students in each row. The second line of the input contains $$$n$$$ integers $$$h_{1, 1}, h_{1, 2}, \\ldots, h_{1, n}$$$ ($$$1 \\le h_{1, i} \\le 10^9$$$), where $$$h_{1, i}$$$ is the height of the $$$i$$$-th student in the first row. The third line of the input contains $$$n$$$ integers $$$h_{2, 1}, h_{2, 2}, \\ldots, h_{2, n}$$$ ($$$1 \\le h_{2, i} \\le 10^9$$$), where $$$h_{2, i}$$$ is the height of the $$$i$$$-th student in the second row.", "output_spec": "Print a single integer \u2014 the maximum possible total height of players in a team Demid can choose.", "sample_inputs": ["5\n9 3 5 7 3\n5 8 1 4 5", "3\n1 2 9\n10 1 1", "1\n7\n4"], "sample_outputs": ["29", "19", "7"], "notes": "NoteIn the first example Demid can choose the following team as follows: In the second example Demid can choose the following team as follows: "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val A = nm(2, N)\n val dp = Array.ofDim[Long](N + 1, 3)\n dp(0)(2) = 0\n REP(N) { i =>\n REP(3) { j => // \u76f4\u524d\u306b\u9078\u3070\u308c\u3066\u3044\u308b\u72b6\u614b\n if (j == 2) {\n dp(i + 1)(0) = max(dp(i + 1)(0), dp(i)(j) + A(0)(i))\n dp(i + 1)(1) = max(dp(i + 1)(1), dp(i)(j) + A(1)(i))\n } else {\n dp(i + 1)(j^1) = max(dp(i + 1)(j^1), dp(i)(j) + A(j^1)(i)) // A(i, j^1)\u3092\u9078\u3093\u3060\n }\n dp(i + 1)(j) = max(dp(i + 1)(j), dp(i)(j)) // \u9078\u3070\u306a\u304b\u3063\u305f\n }\n }\n\n val ans = dp(N).max\n out.println(ans)\n }\n}"}], "negative_code": [], "src_uid": "667e8938b964d7a24500003f6b89717b"} {"nl": {"description": "If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat. However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat. You have met a cat. Can you figure out whether it's normal or grumpy?", "input_spec": null, "output_spec": null, "sample_inputs": [], "sample_outputs": [], "notes": "NotePlease make sure to use the stream flushing operation after each query in order not to leave part of your output in some buffer."}, "positive_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val normal = Set(\"cool\", \"great\", \"not bad\", \"don't think so\", \"don't touch me\")\n val grumpy = Set(\"terrible\", \"worse\", \"don't even\", \"go die in a hole\", \"are you serious\")\n \n for (i <- 0 to 9) {\n println(i)\n val reaction = readLine\n if (normal.contains(reaction)) {\n println(\"normal\")\n } else if (grumpy.contains(reaction)) {\n println(\"grumpy\")\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n var res = \"normal\"\n print(\"9\\n\")\n val sequen = List(\"go die in a hole\",\"are you serious?\",\"terrible\",\"worse\",\"no way\",\"don't even\")\n val nk = StdIn.readLine()\n if (sequen.contains(nk)){\n res = \"grumpy\"\n }\n \n print(res)\n\n }\n}"}], "negative_code": [{"source_code": "object Solution {\n def main(args: Array[String]) {\n val reactions = (0 to 9).map(i => { println(i); Console.flush(); readLine }).filter(_ == \"cool\")\n println(if (reactions.isEmpty) \"grumpy\" else \"normal\")\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val normal = Set(\"cool\", \"great!\", \"not bad\", \"don't think so\", \"don't touch me!\")\n val grumpy = Set(\"terrible\", \"worse\", \"don't even\", \"go die in a hole\", \"are you serious?\")\n \n for (i <- 0 to 9) {\n println(i)\n val reaction = readLine\n if (normal.contains(reaction)) {\n println(\"normal\")\n } else if (grumpy.contains(reaction)) {\n println(\"grumpy\")\n }\n }\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val normal = Set(\"cool\", \"great\", \"not bad\", \"don't think so\", \"don't even\")\n val grumpy = Set(\"terrible\", \"worse\", \"don't even\", \"go die in a hole\", \"are you serious\")\n \n for (i <- 0 to 9) {\n println(i)\n val reaction = readLine\n if (normal.contains(reaction)) {\n println(\"normal\")\n } else if (grumpy.contains(reaction)) {\n println(\"grumpy\")\n }\n }\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n (0 to 9).foreach(println)\n val reactions = (0 to 9).map(_ => readLine).filter(_ == \"cool\")\n println(if (reactions.isEmpty) \"grumpy\" else \"normal\")\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val flag = false\n (0 to 9).foreach{ x => println(x); Console.flush() }\n val reactions = (0 to 9).map(_ => readLine).filter(_ == \"cool\")\n println(if (reactions.isEmpty) \"grumpy\" else \"normal\")\n }\n}"}, {"source_code": "object Solution {\n def main(args: Array[String]) {\n val normal = Set(\"cool\", \"great!\", \"not bad\", \"don't think so\")\n val grumpy = Set(\"terrible\", \"worse\", \"don't even\", \"go die in a hole\")\n \n for (i <- 0 to 9) {\n println(i)\n val reaction = readLine\n if (normal.contains(reaction)) {\n println(\"normal\")\n } else if (grumpy.contains(reaction)) {\n println(\"grumpy\")\n }\n }\n }\n}"}, {"source_code": "import scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n print(\"9\\n\")\n val nk = StdIn.readLine()\n val read = nk.split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n if(read(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n print(\"9\\n\")\n val nk = StdIn.readLine()\n val read = nk.split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n\n if(read(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n\n }\n}\n"}, {"source_code": "\nimport scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n print(\"9\")\n print(\"\\n\\n\\n\")\n val nk = StdIn.readLine()\n val read = nk.split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n\n if(read(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n println(\"9\\n\")\n\n val nk = StdIn.readLine()\n val read = nk.split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n\n if(read(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n }\n}\n"}, {"source_code": "\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n print(\"normal\")\n }\n\n}\n"}, {"source_code": "\nimport scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n print(\"9\")\n print(\"0\\n\")\n val nk = StdIn.readLine()\n val read = nk.split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n\n if(read(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n\n }\n}\n"}, {"source_code": "\n\nimport scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n print(\"9\\n\")\n val nk = StdIn.readLine().split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n\n if(nk(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n\n }\n}\n"}, {"source_code": "import scala.io.StdIn\n\nobject GrumpyCat {\n def main(args:Array[String]): Unit={\n println(\"9\")\n val nk = StdIn.readLine().split(\" \").map(_.toInt)\n var res = \"normal\"\n for(iterator <-0 to 9){\n\n if(nk(iterator) > 9){\n res = \"grumpy\"\n }\n }\n\n print(res)\n\n }\n}\n"}], "src_uid": "465eae7567d12a40a05e0f258d963838"} {"nl": {"description": "One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R\u2009-\u2009R,\u20090), (4R\u2009-\u2009R,\u20090), ..., (2Rm\u2009-\u2009R,\u20090), respectively. Circles with numbers from m\u2009+\u20091 to 2m had centers at points (2R\u2009-\u2009R,\u20092R), (4R\u2009-\u2009R,\u20092R), ..., (2Rm\u2009-\u2009R,\u20092R), respectively. Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2\u2009-\u20091, inclusive. On the day number i the following things happened: The fly arrived at the coordinate plane at the center of the circle with number ( is the result of dividing number x by number y, rounded down to an integer). The fly went along the coordinate plane to the center of the circle number ( is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction. Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days.", "input_spec": "The first line contains two integers m,\u2009R (1\u2009\u2264\u2009m\u2009\u2264\u2009105, 1\u2009\u2264\u2009R\u2009\u2264\u200910).", "output_spec": "In a single line print a single real number \u2014 the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["1 1", "2 2"], "sample_outputs": ["2.0000000000", "5.4142135624"], "notes": "NoteFigure to the second sample"}, "positive_code": [{"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(m, r) = readInts\n val d = Array.ofDim[Double](m + 1)\n def sqr(i: Long) = i * i\n d(1) = Math.sqrt(2.0) + 2\n for(i <- 2 to m) {\n d(i) = d(i - 1) + 2 * (Math.sqrt(2.0) + i - 1) \n }\n val ans = (for(i <- 1 to m) yield 2 + d(i - 1) + d(m - i)).sum * r\n\n def main(a: Array[String]) {\n println(\"%.10f\".formatLocal(Locale.US, ans / sqr(m)))\n }\n}\n"}], "negative_code": [{"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(m, r) = readInts\n val d = Array.ofDim[Double](m + 1)\n def sqr(i: Long) = i * i\n def dist(l: Int) = Math.sqrt(2.0) + 2 * l\n for(i <- 1 to m) {\n d(i) = d(i - 1) + dist(i)\n }\n val ans = (for(i <- 1 to m) yield 2 + d(i - 1) + d(m - i)).sum * r\n\n def main(a: Array[String]) {\n println(\"%.10f\".formatLocal(Locale.US, ans / sqr(m)))\n }\n}\n"}], "src_uid": "f827ea399e6b801c0392eac53710d950"} {"nl": {"description": "Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \\neq b$$$; There exists an integer $$$1 \\le i \\le \\min{(|a|, |b|)}$$$ such that $$$a_i < b_i$$$ and $$$a_j = b_j$$$ for $$$1 \\le j < i$$$. ", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \\le |s| \\le 5000, 1 \\le |c| \\le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.", "output_spec": "For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string \"---\" without quotes) if it is impossible. ", "sample_inputs": ["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"], "sample_outputs": ["AMAZON\n---\nAPPLE"], "notes": "NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string \"AMAZON\" is lexicographically smaller than \"APPLE\".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name \"APPLE\" is lexicographically smaller than \"BANANA\". Note that there are other valid answers, e.g., \"APPEL\". "}, "positive_code": [{"source_code": "import scala.util.Random\n\ncase class Pair(amazonName: String, nonAmazonName: String)\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n println(stdin.take(t).map(_.split(' ')).map(pair => Pair(pair.head, pair.last)).map(solve).mkString(\"\\n\"))\n\n def solve(pair: Pair) = {\n val newName = updateName(pair.amazonName)\n if (newName < pair.nonAmazonName) newName else \"---\"\n }\n\n def updateName(str: String): String = {\n val sorted = str.sorted\n val res = (0 until str.length).find(i => str(i) != sorted(i))\n res match {\n case None => str\n case Some(i) =>\n val ch = sorted(i)\n val index = str.lastIndexOf(ch)\n val arr = str.toCharArray\n val tmp = str(i)\n arr(i) = ch\n arr(index) = tmp\n arr.mkString(\"\")\n }\n }\n\n}\n\n"}], "negative_code": [], "src_uid": "88743b7acb4a95dc0d5bb2e073714c49"} {"nl": {"description": "For an array $$$[b_1, b_2, \\ldots, b_m]$$$ define its number of inversions as the number of pairs $$$(i, j)$$$ of integers such that $$$1 \\le i < j \\le m$$$ and $$$b_i>b_j$$$. Let's call array $$$b$$$ odd if its number of inversions is odd. For example, array $$$[4, 2, 7]$$$ is odd, as its number of inversions is $$$1$$$, while array $$$[2, 1, 4, 3]$$$ isn't, as its number of inversions is $$$2$$$.You are given a permutation $$$[p_1, p_2, \\ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$ (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible. What largest number of these subarrays may be odd?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u00a0\u2014 the size of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\le p_i \\le n$$$, all $$$p_i$$$ are distinct) \u00a0\u2014 the elements of the permutation. The sum of $$$n$$$ over all test cases doesn't exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case output a single integer \u00a0\u2014 the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.", "sample_inputs": ["5\n\n3\n\n1 2 3\n\n4\n\n4 3 2 1\n\n2\n\n1 2\n\n2\n\n2 1\n\n6\n\n4 5 6 1 2 3"], "sample_outputs": ["0\n2\n0\n1\n1"], "notes": "NoteIn the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.In the second test case, we can split our permutation into subarrays $$$[4, 3], [2, 1]$$$, both of which are odd since their numbers of inversions are $$$1$$$.In the fourth test case, we can split our permutation into a single subarray $$$[2, 1]$$$, which is odd.In the fifth test case, we can split our permutation into subarrays $$$[4, 5], [6, 1, 2, 3]$$$. The first subarray has $$$0$$$ inversions, and the second has $$$3$$$, so it is odd."}, "positive_code": [{"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 var arr = readLine.split(\" \").map(_.toInt)\r\n var ans = 0\r\n var i = 1\r\n while (i < arr.length) {\r\n if (arr(i) < arr(i-1)) {\r\n ans += 1\r\n i += 1\r\n }\r\n i += 1\r\n }\r\n\r\n println(ans)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "80e21bfe08a3ef156d0404d4fe07bccd"} {"nl": {"description": "Pchelyonok decided to give Mila a gift. Pchelenok has already bought an array $$$a$$$ of length $$$n$$$, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array!Pchelyonok wants his gift to be beautiful, so he decided to choose $$$k$$$ non-overlapping segments of the array $$$[l_1,r_1]$$$, $$$[l_2,r_2]$$$, $$$\\ldots$$$ $$$[l_k,r_k]$$$ such that: the length of the first segment $$$[l_1,r_1]$$$ is $$$k$$$, the length of the second segment $$$[l_2,r_2]$$$ is $$$k-1$$$, $$$\\ldots$$$, the length of the $$$k$$$-th segment $$$[l_k,r_k]$$$ is $$$1$$$ for each $$$i<j$$$, the $$$i$$$-th segment occurs in the array earlier than the $$$j$$$-th (i.e. $$$r_i<l_j$$$) the sums in these segments are strictly increasing (i.e. let $$$sum(l \\ldots r) = \\sum\\limits_{i=l}^{r} a_i$$$ \u2014 the sum of numbers in the segment $$$[l,r]$$$ of the array, then $$$sum(l_1 \\ldots r_1) < sum(l_2 \\ldots r_2) < \\ldots < sum(l_k \\ldots r_k)$$$). Pchelenok also wants his gift to be as beautiful as possible, so he asks you to find the maximal value of $$$k$$$ such that he can give Mila a gift!", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$2 \\cdot t$$$ lines contain the descriptions of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the maximum possible value of $$$k$$$.", "sample_inputs": ["5\n1\n1\n3\n1 2 3\n5\n1 1 2 2 3\n7\n1 2 1 1 3 2 6\n5\n9 6 7 9 7"], "sample_outputs": ["1\n1\n2\n3\n1"], "notes": null}, "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 val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val k = 2 * sqrt(n).toInt\n val arr = new Array[Long](n+1)\n val sum = Array.ofDim[Long](n+2, 2)\n val mx = Array.ofDim[Int](n+2, 2)\n for (i <- 1 to n)\n arr(i) = readInt()\n var ans = 0\n for (j <- 1 to k) {\n for (i <- (j to n).reverse) {\n sum(i)((j)%2) = arr(i) + sum(i-1)((j-1)%2)\n mx(i)((j)%2) = mx(i+1)((j)%2)\n if ((i+j-1 <= n && mx(i+j-1)((j-1)%2) > 0 && sum(mx(i+j-1)((j-1)%2))((j-1)%2) > sum(i)((j)%2)) || j == 1) {\n ans = j\n if (sum(i)((j)%2) > sum(mx(i)((j)%2))((j)%2))\n mx(i)((j)%2) = i\n }\n }\n }\n/*\n for (j <- 1 to k) {\n for (i <- 1 to n)\n print(mx(i)(j) + \" \")\n println()\n }\n*/\n writer.println(ans)\n }\n writer.flush()\n}\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 val rem = 1000000007\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val k = sqrt(n).toInt + 1\n val arr = new Array[Long](n+1)\n val sum = Array.ofDim[Long](n+2, k+1)\n val mx = Array.ofDim[Int](n+2, k+1)\n val d = Array.ofDim[Boolean](n+2, k+1)\n for (i <- 1 to n)\n arr(i) = readInt()\n var ans = 0\n for (j <- 1 to k) {\n for (i <- (j to n).reverse) {\n sum(i)(j) = arr(i) + sum(i-1)(j-1)\n mx(i)(j) = mx(i+1)(j)\n if ((i+j-1 <= n && mx(i+j-1)(j-1) > 0 && sum(mx(i+j-1)(j-1))(j-1) > sum(i)(j)) || j == 1) {\n ans = j\n if (sum(i)(j) > sum(mx(i)(j))(j))\n mx(i)(j) = i\n }\n }\n }\n/*\n for (j <- 1 to k) {\n for (i <- 1 to n)\n print(mx(i)(j) + \" \")\n println()\n }\n*/\n writer.println(ans)\n }\n writer.flush()\n}\n"}], "src_uid": "cc21fe2f33fed13e6fe0fb25f197ca8f"} {"nl": {"description": "Polycarpus has been working in the analytic department of the \"F.R.A.U.D.\" company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai\u2009<\u20090), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), n is the number of days. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.", "output_spec": "Print an integer k \u2014 the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder. If there are multiple ways to sort the reports into k days, print any of them.", "sample_inputs": ["11\n1 2 3 -4 -5 -6 5 -5 -6 -7 6", "5\n0 -1 100 -1 0"], "sample_outputs": ["3\n5 3 3", "1\n5"], "notes": "NoteHere goes a way to sort the reports from the first sample into three folders: 1 2 3 -4 -5 | -6 5 -5 | -6 -7 6 In the second sample you can put all five reports in one folder."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "3f320920a023c3bc10ba1525e8c89044"} {"nl": {"description": "You are given a string $$$s$$$. You have to determine whether it is possible to build the string $$$s$$$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.For example: aaaabbb can be built as aa $$$+$$$ aa $$$+$$$ bbb; bbaaaaabbb can be built as bb $$$+$$$ aaa $$$+$$$ aa $$$+$$$ bbb; aaaaaa can be built as aa $$$+$$$ aa $$$+$$$ aa; abab cannot be built from aa, aaa, bb and/or bbb. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \\le |s| \\le 50$$$), consisting of characters a and/or b.", "output_spec": "For each test case, print YES if it is possible to build the string $$$s$$$. Otherwise, print NO. You may print each letter in any case (for example, YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).", "sample_inputs": ["8\n\naaaabbb\n\nbbaaaaabbb\n\naaaaaa\n\nabab\n\na\n\nb\n\naaaab\n\nbbaaa"], "sample_outputs": ["YES\nYES\nYES\nNO\nNO\nNO\nNO\nYES"], "notes": "NoteThe first four test cases of the example are described in the statement."}, "positive_code": [{"source_code": "import scala.io.StdIn\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 chars = StdIn.readLine().toCharArray\r\n var pos = 0\r\n var counter = 1\r\n var finishedWithFail = false\r\n\r\n if (chars.length < 2) {\r\n println(\"NO\")\r\n } else {\r\n do {\r\n if (chars(pos) == chars(pos + 1)) {\r\n counter += 1\r\n } else {\r\n if (counter == 1) {\r\n finishedWithFail = true\r\n } else {\r\n counter = 1\r\n }\r\n }\r\n\r\n pos += 1\r\n } while (pos < chars.length - 1 && !finishedWithFail)\r\n\r\n if (counter > 1) println(\"YES\")\r\n else println(\"NO\")\r\n }\r\n\r\n }\r\n}"}], "negative_code": [], "src_uid": "e95e2d21777c1d686bede1b0a5dacbf5"} {"nl": {"description": "You are given a string $$$s$$$, consisting only of characters '0' and '1'.You have to choose a contiguous substring of $$$s$$$ and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains a non-empty string $$$s$$$, consisting only of characters '0' and '1'. The length of $$$s$$$ doesn't exceed $$$2 \\cdot 10^5$$$. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the maximum amount of characters that can be removed after applying the operation exactly once.", "sample_inputs": ["4\n01\n1010101010111\n00110001000\n1"], "sample_outputs": ["0\n5\n3\n0"], "notes": "NoteIn the first testcase, you can choose substrings \"0\", \"1\" or \"01\". In \"0\" the amount of '0' is $$$1$$$, the amount of '1' is $$$0$$$. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were $$$0$$$ of them, nothing changes. Same for \"1\". And in \"01\" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring \"10101010101\". It contains $$$5$$$ characters '0' and $$$6$$$ characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring \"011000100\". It contains $$$6$$$ characters '0' and $$$3$$$ characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences."}, "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"}, {"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}"}], "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"} {"nl": {"description": "There are $$$n$$$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $$$i$$$-th emote increases the opponent's happiness by $$$a_i$$$ units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only $$$m$$$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $$$k$$$ times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes $$$i$$$ and $$$j$$$ ($$$i \\ne j$$$) such that $$$a_i = a_j$$$ are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.", "input_spec": "The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le m \\le 2 \\cdot 10^9$$$) \u2014 the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is value of the happiness of the $$$i$$$-th emote.", "output_spec": "Print one integer \u2014 the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.", "sample_inputs": ["6 9 2\n1 3 3 7 4 2", "3 1000000000 1\n1000000000 987654321 1000000000"], "sample_outputs": ["54", "1000000000000000000"], "notes": "NoteIn the first example you may use emotes in the following sequence: $$$4, 4, 5, 4, 4, 5, 4, 4, 5$$$."}, "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, K = nl()\n val A = na(N)\n sort(A)\n val mx = A(N - 1).toLong\n val mx2 = A(N - 2).toLong\n val ans = if (mx == mx2) {\n M * mx\n } else {\n val remain = M % (K + 1) // [0, K]\n M / (K + 1) * (mx * K + mx2) + remain * mx\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"}], "negative_code": [], "src_uid": "96dee17800e147350bd37e60f66f49dd"} {"nl": {"description": "During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence $$$a$$$, consisting of $$$n$$$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. First element $$$a_1$$$ becomes the root of the tree. Elements $$$a_2, a_3, \\ldots, a_n$$$ are added one by one. To add element $$$a_i$$$ one needs to traverse the tree starting from the root and using the following rules: The pointer to the current node is set to the root. If $$$a_i$$$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. If at some point there is no required child, the new node is created, it is assigned value $$$a_i$$$ and becomes the corresponding child of the current node. ", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100\\,000$$$)\u00a0\u2014 the length of the sequence $$$a$$$. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the sequence $$$a$$$ itself.", "output_spec": "Output $$$n - 1$$$ integers. For all $$$i > 1$$$ print the value written in the node that is the parent of the node with value $$$a_i$$$ in it.", "sample_inputs": ["3\n1 2 3", "5\n4 2 3 1 6"], "sample_outputs": ["1 2", "4 2 2 4"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.immutable.TreeMap\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(_.toInt)\n val ans = new Array[Int](n)\n var par = TreeMap[Int, Int]()\n val INF = 2000000000\n par += (INF -> a(0))\n for (i <- 1 until n) {\n val r = par.from(a(i)).firstKey\n val p = par(r)\n ans(i) = p\n par -= r\n if (a(i) < p) {\n par += (p -> a(i))\n if (r != p) par += (r -> p)\n } else if (a(i) > p) {\n if (!(par contains p)) par += (p -> p)\n par += (r -> a(i))\n } else {\n assert(false)\n }\n }\n println(ans.drop(1).mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.immutable.TreeMap\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(_.toInt)\n val ans = new Array[Int](n)\n var par = TreeMap[Int, Int]()\n val INF = 2000000000\n par += (INF -> a(0))\n for (i <- 1 until n) {\n val r = par.from(a(i)).firstKey\n val p = par(r)\n ans(i) = p\n par -= r\n if (a(i) < p) {\n if (!(par contains p)) par += (p -> a(i))\n par += (r -> p)\n } else if (a(i) > p) {\n if (!(par contains p)) par += (p -> p)\n par += (r -> a(i))\n } else {\n assert(false)\n }\n }\n println(ans.drop(1).mkString(\" \"))\n }\n}\n"}], "src_uid": "d2d21871c068e04469047e959dcf0d09"} {"nl": {"description": "Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\\{1, 1, 2, 3, 3, 3, 4\\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).", "input_spec": "The first line contains a single integer $$$n~(2 \\le n \\le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \\dots s_n~(1 \\le s_i \\le 100)$$$ \u2014 the multiset $$$s$$$.", "output_spec": "If there exists no split of $$$s$$$ to satisfy the given requirements, then print \"NO\" in the first line. Otherwise print \"YES\" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.", "sample_inputs": ["4\n3 5 7 1", "3\n3 5 1"], "sample_outputs": ["YES\nBABA", "NO"], "notes": null}, "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 = na(N)\n val cnt = Array.ofDim[Int](101)\n S foreach (a => cnt(a) += 1)\n val ones = cnt.zipWithIndex collect { case (1, i) => i }\n val twos = cnt.zipWithIndex collect { case (2, i) => i }\n val threes = cnt.zipWithIndex collect { case (cnt, i) if cnt >= 3 => i }\n\n if (ones.length % 2 == 1 && threes.length == 0) {\n out.println(\"NO\")\n } else {\n out.println(\"YES\")\n\n val X = Array.fill[ArrayBuffer[Int]](2)(ArrayBuffer())\n rep(ones.length) { i =>\n val x = i % 2\n X(x) += ones(i)\n }\n\n rep(twos.length) { i =>\n X(0) += twos(i)\n X(0) += twos(i)\n }\n\n if (ones.length % 2 == 1) {\n val h = threes.head\n\n // one\u306fX(0)\u306b\uff11\u3053\u4f59\u8a08\u306b\u306f\u3044\u3063\u3066\u3044\u308b\u306e\u3067\u8abf\u6574\u3059\u308b\n X(1) += h\n rep(cnt(h) - 1)(_ => X(0) += h)\n\n rep(threes.length - 1, 1) { i =>\n val s = threes(i)\n rep(cnt(s))(_ => X(0) += s)\n }\n } else {\n rep(threes.length) { i =>\n val s = threes(i)\n rep(cnt(s))(_ => X(0) += s)\n }\n }\n\n rep(N) { i =>\n val s = S(i)\n if (X(0) contains s) {\n X(0) -= s\n out.print('A')\n } else {\n X(1) -= s\n out.print('B')\n }\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): 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": "d126ef6b94e9ab55624cf7f2a96c7ed1"} {"nl": {"description": "You are given an array $$$a$$$, consisting of $$$n$$$ positive integers.Let's call a concatenation of numbers $$$x$$$ and $$$y$$$ the number that is obtained by writing down numbers $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, a concatenation of numbers $$$12$$$ and $$$3456$$$ is a number $$$123456$$$.Count the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \\neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$2 \\le k \\le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print a single integer \u2014 the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \\neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.", "sample_inputs": ["6 11\n45 1 10 12 11 7", "4 2\n2 78 4 10", "5 2\n3 7 19 3 3"], "sample_outputs": ["7", "12", "0"], "notes": "NoteIn the first example pairs $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 1)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ suffice. They produce numbers $$$451$$$, $$$4510$$$, $$$110$$$, $$$1045$$$, $$$1012$$$, $$$121$$$, $$$1210$$$, respectively, each of them is divisible by $$$11$$$.In the second example all $$$n(n - 1)$$$ pairs suffice.In the third example no pair is sufficient."}, "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 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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((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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"} {"nl": {"description": "There are $$$n$$$ warriors in a row. The power of the $$$i$$$-th warrior is $$$a_i$$$. All powers are pairwise distinct.You have two types of spells which you may cast: Fireball: you spend $$$x$$$ mana and destroy exactly $$$k$$$ consecutive warriors; Berserk: you spend $$$y$$$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be $$$[2, 3, 7, 8, 11, 5, 4]$$$, and $$$k = 3$$$. If you cast Berserk on warriors with powers $$$8$$$ and $$$11$$$, the resulting sequence of powers becomes $$$[2, 3, 7, 11, 5, 4]$$$. Then, for example, if you cast Fireball on consecutive warriors with powers $$$[7, 11, 5]$$$, the resulting sequence of powers becomes $$$[2, 3, 4]$$$.You want to turn the current sequence of warriors powers $$$a_1, a_2, \\dots, a_n$$$ into $$$b_1, b_2, \\dots, b_m$$$. Calculate the minimum amount of mana you need to spend on it.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of sequence $$$a$$$ and the length of sequence $$$b$$$ respectively. The second line contains three integers $$$x, k, y$$$ ($$$1 \\le x, y, \\le 10^9; 1 \\le k \\le n$$$)\u00a0\u2014 the cost of fireball, the range of fireball and the cost of berserk respectively. The third line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that all integers $$$a_i$$$ are pairwise distinct. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \\dots, b_m$$$ ($$$1 \\le b_i \\le n$$$). It is guaranteed that all integers $$$b_i$$$ are pairwise distinct.", "output_spec": "Print the minimum amount of mana for turning the sequnce $$$a_1, a_2, \\dots, a_n$$$ into $$$b_1, b_2, \\dots, b_m$$$, or $$$-1$$$ if it is impossible.", "sample_inputs": ["5 2\n5 2 3\n3 1 4 5 2\n3 5", "4 4\n5 1 4\n4 3 1 2\n2 4 3 1", "4 4\n2 1 11\n1 3 2 4\n1 3 2 4"], "sample_outputs": ["8", "-1", "0"], "notes": null}, "positive_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val Array(x, k, y) = readLine().split(\" \").map(_.toLong)\n val cheap = x.min(y * k)\n val an = readLine().split(\" \").map(_.toInt) :+ 0\n val bn = readLine().split(\" \").map(_.toInt) :+ 0\n\n private def destroy(from: Int, until: Int): Long = {\n val range = until - from\n val count = range / k\n val over = range % k\n\n// println(s\"from:$from until:$until count:$count over:$over range:$range\")\n\n val warrior = if (from == 0) an(until) else an(until).max(an(from - 1))\n val i = an.indexWhere(_ > warrior, from)\n val j = if (i == -1) until else until.min(i)\n val strongest = an(j)\n\n// println(s\"warrior:$warrior strongest:$strongest\")\n\n if (strongest > warrior) {\n if (count == 0 && over != 0) -1L\n else x + y * over + cheap * (count - 1)\n } else y * over + cheap * count\n }\n\n// println()\n\n val ans = bn\n .foldLeft((0L, 0)) {\n case ((-1L, _), _) => (-1L, 0)\n case ((amount, from), b) =>\n val until = an.indexOf(b, from)\n\n if (until == -1) (-1L, 0)\n else {\n val cost = destroy(from, until)\n\n if (cost == -1L) (-1L, 0)\n else (amount + cost, until + 1)\n }\n }\n ._1\n\n println(ans)\n}\n"}], "negative_code": [{"source_code": "object D extends App {\n import scala.io.StdIn._\n\n val Array(n, m) = readLine().split(\" \").map(_.toInt)\n val Array(x, k, y) = readLine().split(\" \").map(_.toLong)\n val cheap = x.min(y * k)\n val an = readLine().split(\" \").map(_.toInt) :+ 0\n val bn = readLine().split(\" \").map(_.toInt) :+ 0\n\n private def destroy(from: Int, until: Int): Long = {\n val range = until - from\n val count = range / k\n val over = range % k\n\n// println(s\"from:$from until:$until count:$count over:$over range:$range\")\n\n val warrior = if (from == 0) an(until) else an(until).max(an(from - 1))\n val i = an.indexWhere(_ > warrior, from)\n val j = if (i == -1) until else until.min(i)\n val strongest = an(j)\n\n// println(s\"warrior:$warrior strongest:$strongest\")\n\n if (strongest > warrior) x + y * over + cheap * (count - 1)\n else y * over + cheap * count\n }\n\n// println()\n\n val ans = bn\n .foldLeft((0L, 0)) {\n case ((-1L, _), _) => (-1L, 0)\n case ((amount, from), b) =>\n val until = an.indexOf(b, from)\n\n if (until == -1) (-1L, 0)\n else {\n val cost = destroy(from, until)\n\n if (cost == -1L) (-1L, 0)\n else (amount + cost, until + 1)\n }\n }\n ._1\n\n println(ans)\n}\n"}], "src_uid": "461666a075cd830496f919557b8122a4"} {"nl": {"description": "To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height $$$h$$$ and width $$$w$$$, divided into $$$h \\times w$$$ cells. Let $$$(i, j)$$$ denote the cell in the $$$i$$$-th row and the $$$j$$$-th column of the rectangle ($$$1 \\le i \\le h$$$; $$$1 \\le j \\le w$$$).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table\u00a0\u2014 into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $$$(i, j)$$$ you put a plate into, at least one of the following conditions must be satisfied: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $$$(i, j)$$$ contains a plate, you can't put plates into cells $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.Put as many plates on the table as possible without violating the rules above.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Each of the following $$$t$$$ lines describes one test case and contains two integers $$$h$$$ and $$$w$$$ ($$$3 \\le h, w \\le 20$$$)\u00a0\u2014 the height and the width of the table.", "output_spec": "For each test case, print $$$h$$$ lines containing $$$w$$$ characters each. Character $$$j$$$ in line $$$i$$$ must be equal to $$$1$$$ if you are putting a plate into cell $$$(i, j)$$$, and $$$0$$$ otherwise. If there are multiple answers, print any. All plates must be put on the edge of the table. No two plates can be put into cells that have a common side or corner. The number of plates put on the table under these conditions must be as large as possible. You are allowed to print additional empty lines.", "sample_inputs": ["3\n3 5\n4 4\n5 6"], "sample_outputs": ["10101\n00000\n10101\n\n0100\n0001\n1000\n0010\n\n010101\n000000\n100001\n000000\n101010"], "notes": "NoteFor the first test case, example output contains the only way to put $$$6$$$ plates on the table.For the second test case, there are many ways to put $$$4$$$ plates on the table, example output contains one of them.Putting more than $$$6$$$ plates in the first test case or more than $$$4$$$ plates in the second test case is impossible."}, "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 => 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"}, {"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"} {"nl": {"description": "During the hypnosis session, Nicholas suddenly remembered a positive integer $$$n$$$, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one?For some numbers doing so is impossible: for example, for number $$$53$$$ it's impossible to delete some of its digits to obtain a not prime integer. However, for all $$$n$$$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number.Note that you cannot remove all the digits from the number.A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $$$1$$$ is neither a prime nor a composite number.", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$k$$$ ($$$1 \\le k \\le 50$$$)\u00a0\u2014 the number of digits in the number. The second line of each test case contains a positive integer $$$n$$$, which doesn't contain zeros in decimal notation ($$$10^{k-1} \\le n < 10^{k}$$$). It is guaranteed that it is always possible to remove less than $$$k$$$ digits to make the number not prime. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions. If there are multiple solutions, print any.", "sample_inputs": ["7\n3\n237\n5\n44444\n3\n221\n2\n35\n3\n773\n1\n4\n30\n626221626221626221626221626221"], "sample_outputs": ["2\n27\n1\n4\n1\n1\n2\n35\n2\n77\n1\n4\n1\n6"], "notes": "NoteIn the first test case, you can't delete $$$2$$$ digits from the number $$$237$$$, as all the numbers $$$2$$$, $$$3$$$, and $$$7$$$ are prime. However, you can delete $$$1$$$ digit, obtaining a number $$$27 = 3^3$$$.In the second test case, you can delete all digits except one, as $$$4 = 2^2$$$ is a composite number."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Let's call the following process a transformation of a sequence of length $$$n$$$.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $$$n$$$ integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence $$$1, 2, \\dots, n$$$. Find the lexicographically maximum result of its transformation.A sequence $$$a_1, a_2, \\ldots, a_n$$$ is lexicographically larger than a sequence $$$b_1, b_2, \\ldots, b_n$$$, if there is an index $$$i$$$ such that $$$a_j = b_j$$$ for all $$$j < i$$$, and $$$a_i > b_i$$$.", "input_spec": "The first and only line of input contains one integer $$$n$$$ ($$$1\\le n\\le 10^6$$$).", "output_spec": "Output $$$n$$$ integers \u00a0\u2014 the lexicographically maximum result of the transformation.", "sample_inputs": ["3", "2", "1"], "sample_outputs": ["1 1 3", "1 2", "1"], "notes": "NoteIn the first sample the answer may be achieved this way: Append GCD$$$(1, 2, 3) = 1$$$, remove $$$2$$$. Append GCD$$$(1, 3) = 1$$$, remove $$$1$$$. Append GCD$$$(3) = 3$$$, remove $$$3$$$. We get the sequence $$$[1, 1, 3]$$$ as the result."}, "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 val pow2 = Array.ofDim[Int](21)\n pow2(0) = 1\n rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2)\n\n def solve(): Unit = {\n val N = ni()\n N match {\n case 1 => out.println(\"1\")\n case 2 => out.println(\"1 2\")\n case 3 => out.println(\"1 1 3\")\n case _ =>\n val cnt = Array.ofDim[Int](21)\n rep(20, 1) { i =>\n cnt(i) = N / pow2(i)\n }\n\n val lastK = cnt.lastIndexWhere(_ > 1)\n var ix = N - 1\n val ans = Array.fill[Int](N)(1)\n def write(x: Int): Unit = {\n ans(ix) = x\n ix -= 1\n }\n\n write(N / pow2(lastK) * pow2(lastK))\n rep_r(lastK, 1) { k =>\n N - cnt(k) to ix foreach (_ => write(pow2(k)))\n }\n\n out.println(ans.mkString(\" \"))\n }\n }\n\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): 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": "cadff0864835854f4f1e0234f2fd3edf"} {"nl": {"description": "An array $$$b$$$ of length $$$k$$$ is called good if its arithmetic mean is equal to $$$1$$$. More formally, if $$$$$$\\frac{b_1 + \\cdots + b_k}{k}=1.$$$$$$Note that the value $$$\\frac{b_1+\\cdots+b_k}{k}$$$ is not rounded up or down. For example, the array $$$[1,1,1,2]$$$ has an arithmetic mean of $$$1.25$$$, which is not equal to $$$1$$$.You are given an integer array $$$a$$$ of length $$$n$$$. In an operation, you can append a non-negative integer to the end of the array. What's the minimum number of operations required to make the array good?We have a proof that it is always possible with finitely many operations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$) \u2014 the length of the initial array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\\ldots,a_n$$$ ($$$-10^4\\leq a_i \\leq 10^4$$$), the elements of the array.", "output_spec": "For each test case, output a single integer \u2014 the minimum number of non-negative integers you have to append to the array so that the arithmetic mean of the array will be exactly $$$1$$$.", "sample_inputs": ["4\n3\n1 1 1\n2\n1 2\n4\n8 4 6 2\n1\n-2"], "sample_outputs": ["0\n1\n16\n1"], "notes": "NoteIn the first test case, we don't need to add any element because the arithmetic mean of the array is already $$$1$$$, so the answer is $$$0$$$.In the second test case, the arithmetic mean is not $$$1$$$ initially so we need to add at least one more number. If we add $$$0$$$ then the arithmetic mean of the whole array becomes $$$1$$$, so the answer is $$$1$$$.In the third test case, the minimum number of elements that need to be added is $$$16$$$ since only non-negative integers can be added.In the fourth test case, we can add a single integer $$$4$$$. The arithmetic mean becomes $$$\\frac{-2+4}{2}$$$ which is equal to $$$1$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100). The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the numbers that Roma has. The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["3 4\n1 2 4", "3 2\n447 44 77"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first sample all numbers contain at most four lucky digits, so the answer is 3.In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2."}, "positive_code": [{"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}"}, {"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 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"}, {"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"}], "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"} {"nl": {"description": "While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.", "input_spec": "The first line of input contains string s containing lowercase English letters (1\u2009\u2264\u2009|s|\u2009\u2264\u20091000). The second line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091000).", "output_spec": "Print \"YES\"(without quotes) if he has worn his own back-bag or \"NO\"(without quotes) otherwise.", "sample_inputs": ["saba\n2", "saddastavvat\n2"], "sample_outputs": ["NO", "YES"], "notes": "NotePalindrome is a string reading the same forward and backward.In the second sample, the faxes in his back-bag can be \"saddas\" and \"tavvat\"."}, "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 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"}, {"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"} {"nl": {"description": "A positive integer is called composite if it can be represented as a product of two positive integers, both greater than $$$1$$$. For example, the following numbers are composite: $$$6$$$, $$$4$$$, $$$120$$$, $$$27$$$. The following numbers aren't: $$$1$$$, $$$2$$$, $$$3$$$, $$$17$$$, $$$97$$$.Alice is given a sequence of $$$n$$$ composite numbers $$$a_1,a_2,\\ldots,a_n$$$.She wants to choose an integer $$$m \\le 11$$$ and color each element one of $$$m$$$ colors from $$$1$$$ to $$$m$$$ so that: for each color from $$$1$$$ to $$$m$$$ there is at least one element of this color; each element is colored and colored exactly one color; the greatest common divisor of any two elements that are colored the same color is greater than $$$1$$$, i.e. $$$\\gcd(a_i, a_j)>1$$$ for each pair $$$i, j$$$ if these elements are colored the same color. Note that equal elements can be colored different colors\u00a0\u2014 you just have to choose one of $$$m$$$ colors for each of the indices from $$$1$$$ to $$$n$$$.Alice showed already that if all $$$a_i \\le 1000$$$ then she can always solve the task by choosing some $$$m \\le 11$$$.Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $$$m$$$ from $$$1$$$ to $$$11$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the amount of numbers in a sequence $$$a$$$. The second line of the test case contains $$$n$$$ composite integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$4 \\le a_i \\le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^4$$$.", "output_spec": "For each test case print $$$2$$$ lines. The first line should contain a single integer $$$m$$$ ($$$1 \\le m \\le 11$$$) \u2014 the number of used colors. Consider colors to be numbered from $$$1$$$ to $$$m$$$. The second line should contain any coloring that satisfies the above conditions. Print $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$1 \\le c_i \\le m$$$), where $$$c_i$$$ is the color of the $$$i$$$-th element. If there are multiple solutions then you can print any of them. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $$$m$$$ from $$$1$$$ to $$$11$$$. Remember that each color from $$$1$$$ to $$$m$$$ should be used at least once. Any two elements of the same color should not be coprime (i.e. their GCD should be greater than $$$1$$$).", "sample_inputs": ["3\n3\n6 10 15\n2\n4 9\n23\n437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961"], "sample_outputs": ["1\n1 1 1\n2\n2 1\n11\n4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6"], "notes": "NoteIn the first test case, $$$\\gcd(6,10)=2$$$, $$$\\gcd(6,15)=3$$$ and $$$\\gcd(10,15)=5$$$. Therefore, it's valid to color all elements the same color. Note that there are other colorings which satisfy Alice's requirement in this test case.In the second test case there is only one element of each color, so the coloring definitely satisfies Alice's requirement."}, "positive_code": [{"source_code": "object B extends App {\n private val ps = List(31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2)\n\n private def colorize(ns: List[Int]): List[Int] = {\n\n val cs = ns.foldLeft(List.empty[Int]) { (cs, n) =>\n val p = ps.find(n % _ == 0).get\n\n p :: cs\n }\n\n val p2c = Map(cs.distinct.zipWithIndex: _*)\n\n cs.map(1 + p2c(_)).reverse\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[List[Int]] = (0 until t)\n .foldLeft(List.empty[List[Int]]) {\n case (input, _) =>\n val _ = scala.io.StdIn.readInt()\n val ns = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n ns :: input\n }\n .reverse\n\n val output = input.map(colorize)\n\n output.foreach(cs => {\n println(cs.distinct.length)\n println(cs.mkString(\" \"))\n })\n}"}], "negative_code": [{"source_code": "object B extends App {\n private val primesToColor = Map[Int, Int](31 -> 11,\n 29 -> 10,\n 23 -> 9,\n 19 -> 8,\n 17 -> 7,\n 13 -> 6,\n 11 -> 5,\n 7 -> 4,\n 5 -> 3,\n 2 -> 2,\n 3 -> 1)\n\n private val primes = Map[Int, List[Int]](31 -> List(),\n 29 -> List(),\n 23 -> List(),\n 19 -> List(),\n 17 -> List(),\n 13 -> List(),\n 11 -> List(),\n 7 -> List(),\n 5 -> List(),\n 2 -> List(),\n 3 -> List())\n\n private def colorize(ns: List[Int]): List[Int] =\n ns.foldLeft((List.empty[Int], primes)) {\n case ((cs, ps), n) =>\n val (p, ls) = ps.filter {\n case (k, vs) => n % k == 0 && !vs.contains(n)\n }.head\n\n val c = primesToColor(p)\n\n (c :: cs, ps + (p -> (n :: ls)))\n }._1.reverse\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[List[Int]] = (0 until t)\n .foldLeft(List.empty[List[Int]]) {\n case (input, _) =>\n scala.io.StdIn.readInt()\n val ns = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n ns :: input\n }\n .reverse\n\n val output = input.map(colorize)\n\n output.foreach(cs => {\n println(cs.distinct.length)\n println(cs.mkString(\" \"))\n })\n}"}], "src_uid": "c3cd949c99e96c9da186a34d49bd6197"} {"nl": {"description": "You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.", "input_spec": "The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1\u2009000\u2009000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.", "output_spec": "The first line of the output should contain \"Possible\" (without quotes) if rebus has a solution and \"Impossible\" (without quotes) otherwise. If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.", "sample_inputs": ["? + ? - ? + ? + ? = 42", "? - ? = 1", "? = 1000000"], "sample_outputs": ["Possible\n9 + 13 - 39 + 28 + 31 = 42", "Impossible", "Possible\n1000000 = 1000000"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = \"+\" + readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n for (s1 <- positivies * n to Math.max(positivies * 1, n) by -1) {\n val s2 = s1 - n\n if (s2 >= 0 && s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)\n }\n\n None\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n var leftPos = positivies - 1\n var leftNeg = negatives - 1\n\n // println(S1 + \" \" + S2)\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 - leftPos <= n) {\n val tmp = S1 - leftPos\n leftPos -= 1\n S1 -= tmp\n \"+\"+tmp\n } else {\n S1 -= n\n leftPos -= 1\n \"+\"+n\n }\n } else {\n if (S2 - leftNeg <= n) {\n val tmp = S2 - leftNeg\n leftNeg -= 1\n S2 -= tmp\n \"-\"+tmp\n } else {\n S2 -= n\n leftNeg -= 1\n \"-\"+n\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n if (negatives == 0) Some(n, 0)\n else {\n for {\n s1 <- positivies * n to Math.max(positivies * 1, n) by -1\n } {\n val s2 = s1 - n\n if (s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)\n }\n\n None\n }\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n var leftPos = positivies - 1\n var leftNeg = negatives - 1\n\n// println(S1 + \" \" + S2)\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 - leftPos <= n) {\n val tmp = S1 - leftPos\n leftPos -= 1\n S1 -= tmp\n \"+\"+tmp\n } else {\n S1 -= n\n leftPos -= 1\n \"+\"+n\n }\n } else {\n if (S2 - leftNeg <= n) {\n val tmp = S2 - leftNeg\n leftNeg -= 1\n S2 -= tmp\n \"-\"+tmp\n } else {\n S2 -= n\n leftNeg -= 1\n \"-\"+n\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n for {\n s1 <- positivies * n to positivies * 1 by -1\n s2 = s1 - n\n if s2 >= 0 && s2 >= negatives * 1 && s2 <= negatives * n\n } {\n return Some(s1, s2)\n }\n\n None\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n// println(S1 + \" \" + S2)\n\n val posDiv = S1 / positivies + 1\n val negDiv = if (negatives == 0) 0 else {\n S2 / negatives + 1\n }\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 >= posDiv) {\n S1 -= posDiv\n \"+\"+posDiv\n } else {\n \"+\"+S1\n }\n } else {\n if (S2 >= negDiv) {\n S2 -= negDiv\n \"-\"+negDiv\n } else {\n \"-\"+S2\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n if (negatives == 0) Some(n, 0)\n else {\n for {\n s1 <- positivies * n to Math.max(positivies * 1, n + 1) by -1\n } {\n val s2 = s1 - n\n if (s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)\n }\n\n None\n }\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n var leftPos = positivies - 1\n var leftNeg = negatives - 1\n\n// println(S1 + \" \" + S2)\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 - leftPos <= n) {\n val tmp = S1 - leftPos\n leftPos -= 1\n S1 -= tmp\n \"+\"+tmp\n } else {\n S1 -= n\n leftPos -= 1\n \"+\"+n\n }\n } else {\n if (S2 - leftNeg <= n) {\n val tmp = S2 - leftNeg\n leftNeg -= 1\n S2 -= tmp\n \"-\"+tmp\n } else {\n S2 -= n\n leftNeg -= 1\n \"-\"+n\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n if (negatives == 0) Some(n, 0)\n else {\n for {\n s1 <- positivies * n to positivies * 1 by -1\n } {\n val s2 = s1 - n\n if (s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)\n }\n\n None\n }\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n var leftPos = positivies - 1\n var leftNeg = negatives - 1\n\n// println(S1 + \" \" + S2)\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 - leftPos <= n) {\n val tmp = S1 - leftPos\n leftPos -= 1\n S1 -= tmp\n \"+\"+tmp\n } else {\n S1 -= n\n leftPos -= 1\n \"+\"+n\n }\n } else {\n if (S2 - leftNeg <= n) {\n val tmp = S2 - leftNeg\n leftNeg -= 1\n S2 -= tmp\n \"-\"+tmp\n } else {\n S2 -= n\n leftNeg -= 1\n \"-\"+n\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n if (negatives == 0) Some(n, 0)\n else {\n for {\n s1 <- positivies * n to positivies * 1 by -1\n s2 = s1 - n\n if s2 >= 0 && s2 >= negatives * 1 && s2 <= negatives * n\n } {\n return Some(s1, s2)\n }\n\n None\n }\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n var leftPos = positivies - 1\n var leftNeg = negatives - 1\n\n // println(S1 + \" \" + S2)\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 - leftPos <= n) {\n val tmp = S1 - leftPos\n leftPos -= 1\n S1 -= tmp\n \"+\"+tmp\n } else {\n S1 -= n\n leftPos -= 1\n \"+\"+n\n }\n } else {\n if (S2 - leftNeg <= n) {\n val tmp = S2 - leftNeg\n leftNeg -= 1\n S2 -= tmp\n \"-\"+tmp\n } else {\n S2 -= n\n leftNeg -= 1\n \"-\"+n\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = normalized.count(_ == '+') // m\n val negatives = normalized.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n for {\n s1 <- positivies * n to Math.max(positivies * 1, n + 1) by -1\n s2 = s1 - n\n if s2 >= negatives * 1 && s2 <= negatives * n\n } {\n return Some(s1, s2)\n }\n\n None\n }\n\n findFirst match {\n case None =>\n println(\"Impossible\")\n case Some((s1, s2)) =>\n println(\"Possible\")\n\n var S1 = s1\n var S2 = s2\n var leftPos = positivies - 1\n var leftNeg = negatives - 1\n\n// println(S1 + \" \" + S2)\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n if (S1 - leftPos <= n) {\n val tmp = S1 - leftPos\n leftPos -= 1\n S1 -= tmp\n \"+\"+tmp\n } else {\n S1 -= n\n leftPos -= 1\n \"+\"+n\n }\n } else {\n if (S2 - leftNeg <= n) {\n val tmp = S2 - leftNeg\n leftNeg -= 1\n S2 -= tmp\n \"-\"+tmp\n } else {\n S2 -= n\n leftNeg -= 1\n \"-\"+n\n }\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \") + \" = \" + n)\n }\n\n}\n"}, {"source_code": "import scala.io.StdIn._\n\nobject B extends App {\n val str = readLine().replace(\" \", \"\")\n val rebus = str.toCharArray\n val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')\n val positivies = 1 + rebus.count(_ == '+') // m\n val negatives = rebus.count(_ == '-') // k\n val n = str.split(\"=\").tail.head.toInt\n\n def findFirst: Option[(Int, Int)] = {\n for (s1 <- positivies * n to positivies by -1) {\n val s2 = s1 - n\n if (s2 >= negatives && s2 <= negatives * n) return Some(s1, s2)\n }\n\n None\n }\n\n findFirst match {\n case None => println(\"Impossible\")\n case Some((s1, s2)) =>\n var S1 = s1\n var positivesLeft = positivies\n var S2 = s2\n var negativesLeft = negatives\n\n println(\"Possible\")\n\n val values = normalized.map { sign =>\n if (sign == '+') {\n val v = Math.min(S1 - positivesLeft + 1, n - positivesLeft + 1)\n positivesLeft -= 1\n S1 -= v\n \"+\"+v\n } else {\n val v = Math.min(S2 - negativesLeft + 1, n - negativesLeft + 1)\n negativesLeft -= 1\n S2 -= v\n \"-\"+v\n }\n }\n\n println(values.mkString(\"\").drop(1).mkString(\"\").replaceAll(\"\\\\-\", \" - \").replaceAll(\"\\\\+\", \" + \"))\n }\n\n}\n"}], "src_uid": "35a97c47182916aaafe4c6e4b69bc79f"} {"nl": {"description": "Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,\u2009\u2009-\u20092,\u20091,\u20093,\u2009\u2009-\u20094. Suppose the mother suggested subarrays (1,\u2009\u2009-\u20092), (3,\u2009\u2009-\u20094), (1,\u20093), (1,\u2009\u2009-\u20092,\u20091,\u20093). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1\u00b71\u2009=\u20091 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (\u2009-\u20092)\u00b71\u2009=\u2009\u2009-\u20092, because he is in one of chosen subarrays, the third flower adds 1\u00b72\u2009=\u20092, because he is in two of chosen subarrays, the fourth flower adds 3\u00b72\u2009=\u20096, because he is in two of chosen subarrays, the fifth flower adds (\u2009-\u20094)\u00b70\u2009=\u20090, because he is in no chosen subarrays. Thus, in total 1\u2009+\u2009(\u2009-\u20092)\u2009+\u20092\u2009+\u20096\u2009+\u20090\u2009=\u20097 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moods\u00a0\u2014 n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009100\u2009\u2264\u2009ai\u2009\u2264\u2009100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) denoting the subarray a[li],\u2009a[li\u2009+\u20091],\u2009...,\u2009a[ri]. Each subarray can encounter more than once.", "output_spec": "Print single integer\u00a0\u2014 the maximum possible value added to the Alyona's happiness.", "sample_inputs": ["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"], "sample_outputs": ["7", "16", "0"], "notes": "NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Let's call a string \"s-palindrome\" if it is symmetric about the middle of the string. For example, the string \"oHo\" is \"s-palindrome\", but the string \"aa\" is not. The string \"aa\" is not \"s-palindrome\", because the second half of it is not a mirror reflection of the first half. English alphabet You are given a string s. Check if the string is \"s-palindrome\".", "input_spec": "The only line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20091000) which consists of only English letters.", "output_spec": "Print \"TAK\" if the string s is \"s-palindrome\" and \"NIE\" otherwise.", "sample_inputs": ["oXoxoXo", "bod", "ER"], "sample_outputs": ["TAK", "TAK", "NIE"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Alyona has recently bought a miniature fridge that can be represented as a matrix with $$$h$$$ rows and $$$2$$$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part. An example of a fridge with $$$h = 7$$$ and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has $$$n$$$ bottles of milk that she wants to put in the fridge. The $$$i$$$-th bottle is $$$a_i$$$ cells tall and $$$1$$$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer $$$k$$$ such that she can put bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. Find this largest $$$k$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$h$$$ ($$$1 \\le n \\le 10^3$$$, $$$1 \\le h \\le 10^9$$$)\u00a0\u2014 the number of bottles and the height of the fridge. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le h$$$)\u00a0\u2014 the heights of the bottles.", "output_spec": "Print the single integer $$$k$$$\u00a0\u2014 the maximum integer such that Alyona can put the bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. If Alyona can put all bottles in the fridge, print $$$n$$$. It is easy to see that Alyona can always put at least one bottle in the fridge.", "sample_inputs": ["5 7\n2 3 5 4 1", "10 10\n9 1 1 1 1 1 1 1 1 1", "5 10\n3 1 4 2 4"], "sample_outputs": ["3", "4", "5"], "notes": "NoteOne of optimal locations in the first example is shown on the picture in the statement.One of optimal locations in the second example is shown on the picture below. One of optimal locations in the third example is shown on the picture below. "}, "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, H = ni()\n val A = na(N)\n\n REP(N) { i =>\n Arrays.sort(A, 0, i + 1)\n var cnt = 0\n val l = i / 2 + 1\n debug(s\"l:$l\")\n debug(A)\n REP(l) { j =>\n debug(s\"ix:${i - 2 * j}\")\n cnt += A(i - 2 * j)\n }\n if (cnt > H) {\n out.println(i)\n return\n }\n }\n\n out.println(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": "2ff0919ee7dfdfb916b23c26fb2caf20"} {"nl": {"description": "When Masha came to math classes today, she saw two integer sequences of length $$$n - 1$$$ on the blackboard. Let's denote the elements of the first sequence as $$$a_i$$$ ($$$0 \\le a_i \\le 3$$$), and the elements of the second sequence as $$$b_i$$$ ($$$0 \\le b_i \\le 3$$$).Masha became interested if or not there is an integer sequence of length $$$n$$$, which elements we will denote as $$$t_i$$$ ($$$0 \\le t_i \\le 3$$$), so that for every $$$i$$$ ($$$1 \\le i \\le n - 1$$$) the following is true: $$$a_i = t_i | t_{i + 1}$$$ (where $$$|$$$ denotes the bitwise OR operation) and $$$b_i = t_i \\& t_{i + 1}$$$ (where $$$\\&$$$ denotes the bitwise AND operation). The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $$$t_i$$$ of length $$$n$$$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the sequence $$$t_i$$$. The second line contains $$$n - 1$$$ integers $$$a_1, a_2, \\ldots, a_{n-1}$$$ ($$$0 \\le a_i \\le 3$$$)\u00a0\u2014 the first sequence on the blackboard. The third line contains $$$n - 1$$$ integers $$$b_1, b_2, \\ldots, b_{n-1}$$$ ($$$0 \\le b_i \\le 3$$$)\u00a0\u2014 the second sequence on the blackboard.", "output_spec": "In the first line print \"YES\" (without quotes), if there is a sequence $$$t_i$$$ that satisfies the conditions from the statements, and \"NO\" (without quotes), if there is no such sequence. If there is such a sequence, on the second line print $$$n$$$ integers $$$t_1, t_2, \\ldots, t_n$$$ ($$$0 \\le t_i \\le 3$$$)\u00a0\u2014 the sequence that satisfies the statements conditions. If there are multiple answers, print any of them.", "sample_inputs": ["4\n3 3 2\n1 2 0", "3\n1 3\n3 2"], "sample_outputs": ["YES\n1 3 2 0", "NO"], "notes": "NoteIn the first example it's easy to see that the sequence from output satisfies the given conditions: $$$t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1$$$ and $$$t_1 \\& t_2 = (01_2) \\& (11_2) = (01_2) = 1 = b_1$$$; $$$t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2$$$ and $$$t_2 \\& t_3 = (11_2) \\& (10_2) = (10_2) = 2 = b_2$$$; $$$t_3 | t_4 = (10_2) | (00_2) = (10_2) = 2 = a_3$$$ and $$$t_3 \\& t_4 = (10_2) \\& (00_2) = (00_2) = 0 = b_3$$$. In the second example there is no such sequence."}, "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 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}"}, {"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"} {"nl": {"description": "The problem uses a simplified TCP/IP address model, please read the statement carefully.An IP address is a 32-bit integer, represented as a group of four decimal 8-bit integers (without leading zeroes), separated by commas. For example, record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In the given problem an arbitrary group of four 8-bit integers is a correct IP address.Our hero Polycarpus still works as a system administrator in some large corporation. He likes beautiful IP addresses. To check if some IP address is beautiful, he should do the following: write out in a line four 8-bit numbers of the IP address, without the commas; check if the resulting string is a palindrome. Let us remind you that a palindrome is a string that reads the same from right to left and from left to right.For example, IP addresses 12.102.20.121 and 0.3.14.130 are beautiful (as strings \"1210220121\" and \"0314130\" are palindromes), and IP addresses 1.20.20.1 and 100.4.4.1 are not.Polycarpus wants to find all beautiful IP addresses that have the given set of digits. Each digit from the set must occur in the IP address at least once. IP address must not contain any other digits. Help him to cope with this difficult task.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910) \u2014 the number of digits in the set. The second line contains the set of integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u20099). It is guaranteed that all digits in the set are distinct.", "output_spec": "In the first line print a single integer k \u2014 the number of beautiful IP addresses that contain the given set of digits. In the following k lines print the IP addresses, one per line in the arbitrary order.", "sample_inputs": ["6\n0 1 2 9 8 7", "1\n4"], "sample_outputs": ["6\n78.190.209.187\n79.180.208.197\n87.190.209.178\n89.170.207.198\n97.180.208.179\n98.170.207.189", "16\n4.4.4.4\n4.4.4.44\n4.4.44.4\n4.4.44.44\n4.44.4.4\n4.44.4.44\n4.44.44.4\n4.44.44.44\n44.4.4.4\n44.4.4.44\n44.4.44.4\n44.4.44.44\n44.44.4.4\n44.44.4.44\n44.44.44.4\n44.44.44.44"], "notes": null}, "positive_code": [{"source_code": "import io.Source\nimport java.io.PrintWriter\nimport scala.collection.mutable.ArrayBuffer\n\nobject CF292C {\n\n val pow10 = Array(1, 10, 100)\n var ds = Array(0)\n var ans = ArrayBuffer.empty[Array[Int]]\n\n def gen2(ar: Array[Int], id: ArrayBuffer[Int], mul: ArrayBuffer[Int], i: Int, mask: Int) {\n val j = id.length - i - 1\n if (i > j) {\n if (Integer.bitCount(mask) == ds.length) {\n ans += ar.clone()\n }\n } else if (Integer.bitCount(mask) + (j - i) / 2 + 1 >= ds.length) {\n for (d <- ds if d != 0 || (i > 0 && id(i) == id(i - 1) || mul(i) == 1) && (id(j) == id(j - 1) || mul(j) == 1)) {\n ar(id(i)) += d * mul(i)\n if (i != j) {\n ar(id(j)) += d * mul(j)\n }\n if (ar(id(i)) < 256 && ar(id(j)) < 256) {\n gen2(ar, id, mul, i + 1, mask | (1 << d))\n }\n ar(id(i)) -= d * mul(i)\n if (i != j) {\n ar(id(j)) -= d * mul(j)\n }\n }\n }\n }\n\n def gen(lens: Array[Int], i: Int) {\n if (i == lens.length) {\n val id = ArrayBuffer.empty[Int]\n val mul = ArrayBuffer.empty[Int]\n for (i <- 0 until 4; j <- 0 until lens(i)) {\n id += i\n mul += pow10(lens(i) - j - 1)\n }\n gen2(Array.ofDim[Int](4), id, mul, 0, 0)\n } else {\n for (v <- 1 to 3) {\n lens(i) = v\n gen(lens, i + 1)\n }\n }\n }\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n ds = Array.fill(n)(in().toInt)\n gen(Array.ofDim[Int](4), 0)\n out.println(ans.size)\n for (a <- ans) {\n out.println(a.mkString(\".\"))\n }\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 }, \"thread\", 64000000).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": [{"source_code": "import io.Source\nimport java.io.PrintWriter\nimport scala.collection.mutable.ArrayBuffer\n\nobject CD292C {\n\n val pow10 = Array(1, 10, 100)\n var ds = Array(0)\n var ans = ArrayBuffer.empty[Array[Int]]\n\n def gen2(ar: Array[Int], id: ArrayBuffer[Int], mul: ArrayBuffer[Int], i: Int, mask: Int) {\n val j = id.length - i - 1\n if (i > j) {\n if (Integer.bitCount(mask) == ds.length) {\n ans += ar.clone()\n }\n } else if (Integer.bitCount(mask) + (j - i) / 2 + 1 >= ds.length) {\n for (d <- ds if d != 0 || i > 0 && id(i) == id(i - 1) && id(j) == id(j - 1)) {\n ar(id(i)) += d * mul(i)\n if (i != j) {\n ar(id(j)) += d * mul(j)\n }\n if (ar(id(i)) < 256 && ar(id(j)) < 256) {\n gen2(ar, id, mul, i + 1, mask | (1 << d))\n }\n ar(id(i)) -= d * mul(i)\n if (i != j) {\n ar(id(j)) -= d * mul(j)\n }\n }\n }\n }\n\n def gen(lens: Array[Int], i: Int) {\n if (i == lens.length) {\n val id = ArrayBuffer.empty[Int]\n val mul = ArrayBuffer.empty[Int]\n for (i <- 0 until 4; j <- 0 until lens(i)) {\n id += i\n mul += pow10(lens(i) - j - 1)\n }\n gen2(Array.ofDim[Int](4), id, mul, 0, 0)\n } else {\n for (v <- 1 to 3) {\n lens(i) = v\n gen(lens, i + 1)\n }\n }\n }\n\n def solve(in: In, out: PrintWriter) {\n val n = in().toInt\n ds = Array.fill(n)(in().toInt)\n gen(Array.ofDim[Int](4), 0)\n out.println(ans.size)\n for (a <- ans) {\n out.println(a.mkString(\".\"))\n }\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 }, \"thread\", 64000000).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}"}], "src_uid": "4cb1927ce961aa5370276044f3be2f4a"} {"nl": {"description": "Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a \"plus\") and negative (a \"minus\"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000) \u2014 the number of magnets. Then n lines follow. The i-th line (1\u2009\u2264\u2009i\u2009\u2264\u2009n) contains either characters \"01\", if Mike put the i-th magnet in the \"plus-minus\" position, or characters \"10\", if Mike put the magnet in the \"minus-plus\" position.", "output_spec": "On the single line of the output print the number of groups of magnets.", "sample_inputs": ["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"], "sample_outputs": ["3", "2"], "notes": "NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets."}, "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 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}"}, {"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"} {"nl": {"description": "Everybody knows that opposites attract. That is the key principle of the \"Perfect Matching\" dating agency. The \"Perfect Matching\" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti (\u2009-\u200910\u2009\u2264\u2009ti\u2009\u2264\u200910). Of course, one number can be assigned to any number of customers.\"Perfect Matching\" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1,\u2009t2,\u2009...,\u2009tn. For example, if t\u2009=\u2009(1,\u2009\u2009-\u20091,\u20091,\u2009\u2009-\u20091), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.Of course, a client can't form a couple with him/herself.", "input_spec": "The first line of the input data contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) which represents the number of registered clients of the \"Couple Matching\". The second line contains a sequence of integers t1,\u2009t2,\u2009...,\u2009tn (\u2009-\u200910\u2009\u2264\u2009ti\u2009\u2264\u200910), ti \u2014 is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.", "output_spec": "Print the number of couples of customs with opposite t. The opposite number for x is number \u2009-\u2009x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specificator.", "sample_inputs": ["5\n-3 3 0 0 3", "3\n0 0 0"], "sample_outputs": ["3", "3"], "notes": "NoteIn the first sample the couples of opposite clients are: (1,2), (1,5) \u0438 (3,4).In the second sample any couple of clients is opposite."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Vanya is doing his maths homework. He has an expression of form , where x1,\u2009x2,\u2009...,\u2009xn are digits from 1 to 9, and sign represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.", "input_spec": "The first line contains expression s (1\u2009\u2264\u2009|s|\u2009\u2264\u20095001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs \u2009+\u2009 and \u2009*\u2009. The number of signs \u2009*\u2009 doesn't exceed 15.", "output_spec": "In the first line print the maximum possible value of an expression.", "sample_inputs": ["3+5*7+8*4", "2+3*5", "3*4*5"], "sample_outputs": ["303", "25", "60"], "notes": "NoteNote to the first sample test. 3\u2009+\u20095\u2009*\u2009(7\u2009+\u20098)\u2009*\u20094\u2009=\u2009303.Note to the second sample test. (2\u2009+\u20093)\u2009*\u20095\u2009=\u200925.Note to the third sample test. (3\u2009*\u20094)\u2009*\u20095\u2009=\u200960 (also many other variants are valid, for instance, (3)\u2009*\u20094\u2009*\u20095\u2009=\u200960)."}, "positive_code": [{"source_code": "object E{\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 var h=Array.ofDim[Long](31,3)\n var state=0\n var cs=0L\n var ch=0L\n var p=0\n for(i<-0 until s.length/2){\n var t=(s(i*2)-'0').toLong\n if(s(i*2+1)=='+'){\n if(state==0){\n cs+=t\n }\n else{\n h(p)(0)=cs*t\n h(p)(1)=ch\n h(p)(2)=t\n cs=0L\n ch=1L\n p+=1\n state=0\n }\n }\n else{\n if(state==1){\n cs*=t\n }\n else{\n if(cs!=0){\n h(p)(0)=cs\n h(p)(1)=cs\n h(p)(2)=cs\n p+=1\n }\n cs=t\n ch=t\n state=1\n\n\n }\n }\n }\n val t=(s(s.length-1)-'0').toLong\n if(state==0){\n cs+=t\n h(p)(0)=cs\n h(p)(1)=cs\n h(p)(2)=cs\n }else{\n cs*=t\n h(p)(0)=cs\n h(p)(1)=ch\n h(p)(2)=t\n }\n\n p+=1\n var sum0=0L\n for(i<-0 until p){\n sum0+=h(i)(0)\n }\n var max=sum0\n for(i<-0 until p-1){\n val l=h(i)(0)/h(i)(2)\n val l0=h(i)(2)\n for(j<-i+1 until p){\n val r=h(j)(0)/h(j)(1)\n val r0=h(j)(1)\n var sumc=0L\n for(k<-i+1 until j){\n sumc+=h(k)(0)\n }\n val sum=sum0-sumc-h(i)(0)-h(j)(0)+l*r*(r0+l0+sumc)\n\n if(sum>max){\n max=sum\n\n }\n }\n }\n out.println(max)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [{"source_code": "object E{\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 var h=Array.ofDim[Int](31,3)\n var state=0\n var cs=0\n var ch=0\n var p=0\n for(i<-0 until s.length/2){\n var t=s(i*2)-'0'\n if(s(i*2+1)=='+'){\n if(state==0){\n cs+=t\n }\n else{\n h(p)(0)=cs*t\n h(p)(1)=ch\n h(p)(2)=t\n cs=0\n ch=1\n p+=1\n state=0\n }\n }\n else{\n if(state==1){\n cs*=t\n }\n else{\n if(cs!=0){\n h(p)(0)=cs\n h(p)(1)=cs\n h(p)(2)=cs\n p+=1\n }\n cs=t\n ch=t\n state=1\n\n\n }\n }\n }\n val t=s(s.length-1)-'0'\n if(state==0){\n cs+=t\n h(p)(0)=cs\n h(p)(1)=cs\n h(p)(2)=cs\n }else{\n cs*=t\n h(p)(0)=cs\n h(p)(1)=ch\n h(p)(2)=t\n }\n\n p+=1\n var sum0=0\n for(i<-0 until p){\n sum0+=h(i)(0)\n }\n var max=sum0\n for(i<-0 until p){\n val l=h(i)(0)/h(i)(2)\n val l0=h(i)(2)\n for(j<-i+1 until p){\n val r=h(j)(0)/h(j)(1)\n val r0=h(j)(1)\n var sumc=0\n for(k<-i+1 until j){\n sumc+=h(k)(0)\n }\n val sum=sum0-sumc-h(i)(0)-h(j)(0)+l*r*(r0+l0+sumc)\n\n if(sum>max){\n max=sum\n\n }\n }\n }\n out.println(max)\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "src_uid": "39dbd405be19c5a56c2b97b28e0edf06"} {"nl": {"description": "The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.", "input_spec": "The only line of the input contains a pair of integers n (1000\u2009\u2264\u2009n\u2009\u2264\u200910\u00a0000) and t (0\u2009\u2264\u2009t\u2009\u2264\u20092\u00a0000\u00a0000\u00a0000)\u00a0\u2014 the number of transistors in the initial time and the number of seconds passed since the initial time.", "output_spec": "Output one number \u2014 the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10\u2009-\u20096.", "sample_inputs": ["1000 1000000"], "sample_outputs": ["1011.060722383550382782399454922040"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \\le hh < 24$$$ and $$$0 \\le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1439$$$) \u2014 the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \\le h < 24$$$, $$$0 \\le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros.", "output_spec": "For each test case, print the answer on it \u2014 the number of minutes before the New Year.", "sample_inputs": ["5\n23 55\n23 0\n0 1\n4 20\n23 59"], "sample_outputs": ["5\n60\n1439\n1180\n1"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "f4982de28aca7080342eb1d0ff87734c"} {"nl": {"description": "Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3\u2009\u00d7\u20095 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3\u2009\u00d7\u20095 table is 15\u2009+\u20098\u2009+\u20093\u2009=\u200926.", "input_spec": "The first line of the input contains a single integer x (1\u2009\u2264\u2009x\u2009\u2264\u20091018)\u00a0\u2014 the number of squares inside the tables Spongebob is interested in.", "output_spec": "First print a single integer k\u00a0\u2014 the number of tables with exactly x distinct squares inside. Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality\u00a0\u2014 in the order of increasing m.", "sample_inputs": ["26", "2", "8"], "sample_outputs": ["6\n1 26\n2 9\n3 5\n5 3\n9 2\n26 1", "2\n1 2\n2 1", "4\n1 8\n2 3\n3 2\n8 1"], "notes": "NoteIn a 1\u2009\u00d7\u20092 table there are 2 1\u2009\u00d7\u20091 squares. So, 2 distinct squares in total. In a 2\u2009\u00d7\u20093 table there are 6 1\u2009\u00d7\u20091 squares and 2 2\u2009\u00d7\u20092 squares. That is equal to 8 squares in total. "}, "positive_code": [{"source_code": "object D{\n //import scala.collection.mutable.PriorityQueue\n import scala.collection.mutable.ArrayBuffer\n //import scala.collection.mutable.Stack\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=nextLong\n val a=ArrayBuffer.empty[(Long,Long)]\n for(n:Long<-1L to (math.pow(3*x,1.0/3.0) toLong )){\n val u=6*x+n*(n+1)*(n-1)\n val d=3*n*(n+1)\n if(u%d==0){\n \n a+=((n,u/d))\n\n }\n }\n val last=a(a.length-1)\n if(last._1!=last._2){\n out.println(a.length*2)\n }else{\n out.println(a.length*2-1)\n }\n for(i<-0 until a.length){\n out.println(a(i)._1+\" \"+a(i)._2)\n }\n if(last._1!=last._2){\n out.println(last._2+\" \"+last._1)\n }\n for(i<-a.length-2 to 0 by -1){\n out.println(a(i)._2+\" \"+a(i)._1)\n }\n\n\n //code ends here\n out.flush\n out.close\n }\n}\n\n"}], "negative_code": [], "src_uid": "5891432c43cfee35a212ad92d7da2a64"} {"nl": {"description": "Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $$$n$$$ numbers from $$$1$$$ to $$$200$$$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:$$$a_{1} \\le a_{2}$$$,$$$a_{n} \\le a_{n-1}$$$ and$$$a_{i} \\le max(a_{i-1}, \\,\\, a_{i+1})$$$ for all $$$i$$$ from $$$2$$$ to $$$n-1$$$.Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from $$$1$$$ to $$$200$$$. Since the number of ways can be big, print it modulo $$$998244353$$$.", "input_spec": "First line of input contains one integer $$$n$$$ ($$$2 \\le n \\le 10^{5}$$$)\u00a0\u2014 size of the array. Second line of input contains $$$n$$$ integers $$$a_{i}$$$\u00a0\u2014 elements of array. Either $$$a_{i} = -1$$$ or $$$1 \\le a_{i} \\le 200$$$. $$$a_{i} = -1$$$ means that $$$i$$$-th element can't be read.", "output_spec": "Print number of ways to restore the array modulo $$$998244353$$$.", "sample_inputs": ["3\n1 -1 2", "2\n-1 -1"], "sample_outputs": ["1", "200"], "notes": "NoteIn the first example, only possible value of $$$a_{2}$$$ is $$$2$$$.In the second example, $$$a_{1} = a_{2}$$$ so there are $$$200$$$ different values because all restored elements should be integers between $$$1$$$ and $$$200$$$. "}, "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 = na(N)\n val dp = Array.ofDim[Long](2, 201, 2)\n\n // i = 1 \u304b\u3089\u59cb\u3081\u305f\u3044\u306e\u3067\u521d\u671f\u5316\u3059\u308bxor\u306f1\u306e\u65b9\u306b\u306a\u308b\n if (A(0) == -1) {\n rep(200, 1) { a => dp(1)(a)(0) = 1 }\n } else {\n dp(1)(A(0))(0) = 1\n }\n\n rep(N - 1, 1) { i =>\n val x = i % 2\n\n // flag = 0, { x < a; \u03a3(x, 0) + \u03a3(x, 1) }\n rep(200, 1) { a =>\n if (a > 0) {\n val cum = dp(x ^ 1)(a - 1)(0) // a - 2 \u307e\u3067\u306e\u7d2f\u7a4d\n dp(x ^ 1)(a)(0) = (cum + dp(x)(a - 1)(0) + dp(x)(a - 1)(1)) % MOD // a - 1 \u306e\u5206\n }\n }\n\n // flag = 1, { x > a; \u03a3(x, 1) + (a, 0) + (a, 1) }\n rep_r(200, 1) { a =>\n if (a < 200) {\n val cum = dp(x ^ 1)(a + 1)(1) // a + 2 \u307e\u3067\u306e\u7d2f\u7a4d\n dp(x ^ 1)(a)(1) = (cum + dp(x)(a + 1)(1)) % MOD // a + 1 \u306e\u5206\n }\n }\n\n rep(200, 1) { a =>\n dp(x ^ 1)(a)(1) += dp(x)(a)(0) + dp(x)(a)(1)\n dp(x ^ 1)(a)(1) %= MOD\n }\n\n // a\u304c\u56fa\u5b9a\u306e\u3068\u304d\u306fa\u4ee5\u5916\u306e\u5024\u3092\u6d88\u3059\n // if-else\u3067\u51e6\u7406\u5206\u3051\u308b\u3088\u308a\u30b7\u30f3\u30d7\u30eb\n if (A(i) != -1) {\n rep(200, 1) { a =>\n if (a != A(i)) {\n dp(x ^ 1)(a)(0) = 0\n dp(x ^ 1)(a)(1) = 0\n }\n }\n }\n\n rep(200, 1) { a =>\n dp(x)(a)(0) = 0\n dp(x)(a)(1) = 0\n }\n }\n\n val ans = map(200)(i => dp(N % 2)(i + 1)(1)).sum % MOD\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": "e4c9774939343984bcfdeaf19e393807"} {"nl": {"description": "A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?More formally, if we denote the handle of the i-th person as hi, then the following condition must hold: .", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of people. The next n lines each contains two strings. The i-th line contains strings fi and si (1\u2009\u2264\u2009|fi|,\u2009|si|\u2009\u2264\u200950) \u2014 the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct. The next line contains n distinct integers: p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n).", "output_spec": "If it is possible, output \"YES\", otherwise output \"NO\".", "sample_inputs": ["3\ngennady korotkevich\npetr mitrichev\ngaoyuan chen\n1 2 3", "3\ngennady korotkevich\npetr mitrichev\ngaoyuan chen\n3 1 2", "2\ngalileo galilei\nnicolaus copernicus\n2 1", "10\nrean schwarzer\nfei claussell\nalisa reinford\neliot craig\nlaura arseid\njusis albarea\nmachias regnitz\nsara valestin\nemma millstein\ngaius worzel\n1 2 3 4 5 6 7 8 9 10", "10\nrean schwarzer\nfei claussell\nalisa reinford\neliot craig\nlaura arseid\njusis albarea\nmachias regnitz\nsara valestin\nemma millstein\ngaius worzel\n2 4 9 6 5 7 1 3 8 10"], "sample_outputs": ["NO", "YES", "YES", "NO", "YES"], "notes": "NoteIn example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist and Petr must be the last.In example 3, if Copernicus uses \"copernicus\" as his handle, everything will be alright."}, "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": "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}"}, {"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"} {"nl": {"description": "Let $$$s$$$ be some string consisting of symbols \"0\" or \"1\". Let's call a string $$$t$$$ a substring of string $$$s$$$, if there exists such number $$$1 \\leq l \\leq |s| - |t| + 1$$$ that $$$t = s_l s_{l+1} \\ldots s_{l + |t| - 1}$$$. Let's call a substring $$$t$$$ of string $$$s$$$ unique, if there exist only one such $$$l$$$. For example, let $$$s = $$$\"1010111\". A string $$$t = $$$\"010\" is an unique substring of $$$s$$$, because $$$l = 2$$$ is the only one suitable number. But, for example $$$t = $$$\"10\" isn't a unique substring of $$$s$$$, because $$$l = 1$$$ and $$$l = 3$$$ are suitable. And for example $$$t =$$$\"00\" at all isn't a substring of $$$s$$$, because there is no suitable $$$l$$$.Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols \"0\" and \"1\", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.You are given $$$2$$$ positive integers $$$n$$$ and $$$k$$$, such that $$$(n \\bmod 2) = (k \\bmod 2)$$$, where $$$(x \\bmod 2)$$$ is operation of taking remainder of $$$x$$$ by dividing on $$$2$$$. Find any string $$$s$$$ consisting of $$$n$$$ symbols \"0\" or \"1\", such that the length of its minimal unique substring is equal to $$$k$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$, separated by spaces ($$$1 \\leq k \\leq n \\leq 100\\,000$$$, $$$(k \\bmod 2) = (n \\bmod 2)$$$).", "output_spec": "Print a string $$$s$$$ of length $$$n$$$, consisting of symbols \"0\" and \"1\". Minimal length of the unique substring of $$$s$$$ should be equal to $$$k$$$. You can find any suitable string. It is guaranteed, that there exists at least one such string.", "sample_inputs": ["4 4", "5 3", "7 3"], "sample_outputs": ["1111", "01010", "1011011"], "notes": "NoteIn the first test, it's easy to see, that the only unique substring of string $$$s = $$$\"1111\" is all string $$$s$$$, which has length $$$4$$$.In the second test a string $$$s = $$$\"01010\" has minimal unique substring $$$t =$$$\"101\", which has length $$$3$$$.In the third test a string $$$s = $$$\"1011011\" has minimal unique substring $$$t =$$$\"110\", which has length $$$3$$$."}, "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 Array(n, k) = readInts(2)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n// if (n >= 2 * k || n == k) {\n// println(\"0\" * k + \"1\" * (n - k))\n// } else /*if (n % 2 == 1) */{\n val l = (n - k) / 2\n val s0 = \"0\" * l + \"1\"\n// val d = n - k\n// val s0 = \"0\" * (d - 1) + \"1\"\n val s = s0 * (n / s0.length + 1)\n println(s.take(n))\n// }\n Console.flush\n\n// for (b <- 0 until (1 << n)) {\n// val bb = b.toBinaryString\n// val s = \"0\" * (n - bb.length) + bb\n// var bad = false\n// for (i <- 1 to n) {\n// for (j <- 0 to n - i) {\n// val ss = s.substring(j, j + i)\n// //println(ss)\n// if (s.indexOf(ss) == j && s.lastIndexOf(ss) == j) {\n// if (!bad && i == k) {\n// println(s, ss)\n// System.exit(0)\n// }\n// bad = true\n// }\n// }\n// }\n// }\n// Console.flush\n\n}\n"}], "negative_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 Array(n, k) = readInts(2)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n >= 2 * k || n == k) {\n println(\"0\" * k + \"1\" * (n - k))\n } else /*if (n % 2 == 1) */{\n// val l = (n - k) / 2\n// val s0 = \"0\" * l + \"1\" * l\n val d = n - k\n val s0 = \"0\" * (d - 1) + \"1\"\n val s = s0 * (n / s0.length + 1)\n println(s.take(n))\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n >= 2 * k || n == k) {\n println(\"0\" * k + \"1\" * (n - k))\n } else /*if (n % 2 == 1) */{\n val l = (n - k) / 2\n val s0 = \"0\" * l + \"1\"\n// val d = n - k\n// val s0 = \"0\" * (d - 1) + \"1\"\n val s = s0 * (n / s0.length + 1)\n println(s.take(n))\n }\n\n// for (b <- 0 until (1 << n)) {\n// val bb = b.toBinaryString\n// val s = \"0\" * (n - bb.length) + bb\n// var bad = false\n// for (i <- 1 to n) {\n// for (j <- 0 to n - i) {\n// val ss = s.substring(j, j + i)\n// if (s.indexOf(ss) == j && s.lastIndexOf(ss) == j) {\n// if (!bad && i == k) {\n// println(s, ss)\n// System.exit(0)\n// }\n// bad = true\n// }\n// }\n// }\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 def readLongs(n: Int) = { val tl = tokenizeLine; 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 Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (n >= 2 * k || n == k) {\n println(\"0\" * k + \"1\" * (n - k))\n } else /*if (n % 2 == 1) */{\n val l = (n - k) / 2\n val s0 = \"0\" * l + \"1\" * l\n val s = s0 * (n / s0.length + 1)\n println(s.take(n))\n }\n\n Console.flush\n}\n"}], "src_uid": "7e8baa4fb780f11e66bb2b7078e34c04"} {"nl": {"description": "There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi.Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence.The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants): If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) \u2009\u00d7\u2009 a. Otherwise, add (the value of the ball) \u2009\u00d7\u2009 b. You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a\u2009=\u2009ai and b\u2009=\u2009bi.Note that the new sequence can be empty, and the value of an empty sequence is defined as zero.", "input_spec": "The first line contains two integers n and q (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009q\u2009\u2264\u2009500). The second line contains n integers: v1,\u2009v2,\u2009...,\u2009vn (|vi|\u2009\u2264\u2009105). The third line contains n integers: c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009n). The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|,\u2009|bi|\u2009\u2264\u2009105). In each line integers are separated by single spaces.", "output_spec": "For each query, output a line containing an integer \u2014 the answer to the query. The i-th line contains the answer to the i-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["6 3\n1 -2 3 4 0 -1\n1 2 1 2 1 1\n5 1\n-2 1\n1 0", "4 1\n-3 6 -1 2\n1 2 3 1\n1 -1"], "sample_outputs": ["20\n9\n4", "5"], "notes": "NoteIn the first example, to achieve the maximal value: In the first query, you should select 1st, 3rd, and 4th ball. In the second query, you should select 3rd, 4th, 5th and 6th ball. In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value."}, "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 (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 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"}, {"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"}], "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"} {"nl": {"description": "Codeforces separates its users into $$$4$$$ divisions by their rating: For Division 1: $$$1900 \\leq \\mathrm{rating}$$$ For Division 2: $$$1600 \\leq \\mathrm{rating} \\leq 1899$$$ For Division 3: $$$1400 \\leq \\mathrm{rating} \\leq 1599$$$ For Division 4: $$$\\mathrm{rating} \\leq 1399$$$ Given a $$$\\mathrm{rating}$$$, print in which division the $$$\\mathrm{rating}$$$ belongs.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of testcases. The description of each test consists of one line containing one integer $$$\\mathrm{rating}$$$ ($$$-5000 \\leq \\mathrm{rating} \\leq 5000$$$).", "output_spec": "For each test case, output a single line containing the correct division in the format \"Division X\", where $$$X$$$ is an integer between $$$1$$$ and $$$4$$$ representing the division for the corresponding rating.", "sample_inputs": ["7\n-789\n1299\n1300\n1399\n1400\n1679\n2300"], "sample_outputs": ["Division 4\nDivision 4\nDivision 4\nDivision 4\nDivision 3\nDivision 2\nDivision 1"], "notes": "NoteFor test cases $$$1-4$$$, the corresponding ratings are $$$-789$$$, $$$1299$$$, $$$1300$$$, $$$1399$$$, so all of them are in division $$$4$$$.For the fifth test case, the corresponding rating is $$$1400$$$, so it is in division $$$3$$$.For the sixth test case, the corresponding rating is $$$1679$$$, so it is in division $$$2$$$.For the seventh test case, the corresponding rating is $$$2300$$$, so it is in division $$$1$$$."}, "positive_code": [{"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"}, {"source_code": "import scala.io.StdIn\r\n\r\n/**\r\n * \u041d\u0430 Codeforces \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0438 \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u044b \u043d\u0430 4 \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d\u0430 \u043f\u043e \u0438\u0445 \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0443:\r\n *\r\n * \u0414\u043b\u044f 1-\u0433\u043e \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d\u0430: 1900\u2264rating\r\n * \u0414\u043b\u044f 2-\u0433\u043e \u0438\u0432\u0438\u0437\u0438\u043e\u043d\u0430: 1600\u2264rating\u22641899\r\n * \u0414\u043b\u044f 3-\u0433\u043e \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d\u0430: 1400\u2264rating\u22641599\r\n * \u0414\u043b\u044f 4-\u0433\u043e \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d\u0430: rating\u22641399\r\n * \u0423\u0447\u0438\u0442\u044b\u0432\u0430\u044f rating, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435, \u043a \u043a\u0430\u043a\u043e\u043c\u0443 \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d\u0443 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0441\u044f rating.\r\n *\r\n * \u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\r\n * \u041f\u0435\u0440\u0432\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u0432\u0432\u043e\u0434\u0430 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \ud835\udc61 (1\u2264\ud835\udc61\u2264104) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043d\u0430\u0431\u043e\u0440\u043e\u0432 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0432 \u0442\u0435\u0441\u0442\u0435.\r\n *\r\n * \u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u043d\u0430\u0431\u043e\u0440\u0430 \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 \u043e\u0434\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438, \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0449\u0435\u0439 \u043e\u0434\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e rating (\u22125000\u2264rating\u22645000).\r\n *\r\n * \u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\r\n * \u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u043d\u0430\u0431\u043e\u0440\u0430 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443, \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0449\u0443\u044e \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 \u00abDivision X\u00bb, \u0433\u0434\u0435 \ud835\udc4b \u2014 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u043e\u0442 1 \u0434\u043e 4, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u044e\u0449\u0435\u0435 \u0434\u0438\u0432\u0438\u0437\u0438\u043e\u043d \u0434\u043b\u044f \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0430.\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"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$ and two integers $$$m$$$ and $$$k$$$.You can choose some subarray $$$a_l, a_{l+1}, \\dots, a_{r-1}, a_r$$$. The cost of subarray $$$a_l, a_{l+1}, \\dots, a_{r-1}, a_r$$$ is equal to $$$\\sum\\limits_{i=l}^{r} a_i - k \\lceil \\frac{r - l + 1}{m} \\rceil$$$, where $$$\\lceil x \\rceil$$$ is the least integer greater than or equal to $$$x$$$. The cost of empty subarray is equal to zero.For example, if $$$m = 3$$$, $$$k = 10$$$ and $$$a = [2, -4, 15, -3, 4, 8, 3]$$$, then the cost of some subarrays are: $$$a_3 \\dots a_3: 15 - k \\lceil \\frac{1}{3} \\rceil = 15 - 10 = 5$$$; $$$a_3 \\dots a_4: (15 - 3) - k \\lceil \\frac{2}{3} \\rceil = 12 - 10 = 2$$$; $$$a_3 \\dots a_5: (15 - 3 + 4) - k \\lceil \\frac{3}{3} \\rceil = 16 - 10 = 6$$$; $$$a_3 \\dots a_6: (15 - 3 + 4 + 8) - k \\lceil \\frac{4}{3} \\rceil = 24 - 20 = 4$$$; $$$a_3 \\dots a_7: (15 - 3 + 4 + 8 + 3) - k \\lceil \\frac{5}{3} \\rceil = 27 - 20 = 7$$$. Your task is to find the maximum cost of some subarray (possibly empty) of array $$$a$$$.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \\le n \\le 3 \\cdot 10^5, 1 \\le m \\le 10, 1 \\le k \\le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$).", "output_spec": "Print the maximum cost of some subarray of array $$$a$$$.", "sample_inputs": ["7 3 10\n2 -4 15 -3 4 8 3", "5 2 1000\n-13 -4 -9 -20 -11"], "sample_outputs": ["7", "0"], "notes": null}, "positive_code": [{"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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\n }\n }\n}"}], "src_uid": "529aed80a647d181f08d2c26bb14d65d"} {"nl": {"description": "Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends j\u2009-\u2009i\u2009+\u20091 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons?", "input_spec": "The first line contains three integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500, 0\u2009\u2264\u2009k\u2009\u2264\u2009500) \u2014 the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson).", "output_spec": "Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons.", "sample_inputs": ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"], "sample_outputs": ["5", "8"], "notes": "NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day."}, "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, k) = readInts(3)\n\n val days = Array.fill(n){ readLine }\n\n val dp = Array.fill(n, k + 1)(Int.MaxValue / 2)\n\n for {\n d <- 0 until n\n } {\n val day = days(d)\n var skipBefore = 0\n var start = 0\n val minThisDay = Array.fill(k + 1)(m + 1)\n\n while (start < m) {\n while (start < m && day(start) == '0') start += 1\n var skipAfter = 0\n var end = m - 1\n while (end >= start) {\n while (end >= start && day(end) == '0') end -= 1\n //println(day, start, skipBefore, end, skipAfter)\n val skipped = skipBefore + skipAfter\n val hours = end - start + 1\n if (skipped <= k && hours < minThisDay(skipped)) minThisDay(skipped) = hours\n if (end >= start) {\n skipAfter += 1\n end -= 1\n }\n }\n val skipped = skipBefore + skipAfter\n if (skipped <= k) minThisDay(skipped) = 0\n if (start < m) {\n skipBefore += 1\n start += 1\n }\n }\n if (d == 0) dp(d) = minThisDay\n else {\n var k1 = 0\n while (k1 <= k) {\n var k2 = 0\n while (k2 + k1 <= k) {\n dp(d)(k1 + k2) = Math.min(dp(d)(k1 + k2), dp(d - 1)(k1) + minThisDay(k2))\n k2 += 1\n }\n k1 += 1\n }\n }\n //println(dp(d).mkString(\" \"), minThisDay.mkString(\" \"))\n }\n\n println(dp(n - 1).min)\n}\n"}], "negative_code": [], "src_uid": "cf5650c13ce0404d2df10fa3196d7923"} {"nl": {"description": "Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as aij. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that aij\u2009=\u2009apq at (i,\u2009j)\u2009\u2260\u2009(p,\u2009q).Dima has already written a song \u2014 a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).We'll represent a way to play a song as a sequence of pairs (xi,\u2009yi) (1\u2009\u2264\u2009i\u2009\u2264\u2009s), such that the xi-th string on the yi-th fret produces the i-th note from the song. The complexity of moving between pairs (x1,\u2009y1) and (x2,\u2009y2) equals + . The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!", "input_spec": "The first line of the input contains four integers n, m, k and s (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092000,\u20091\u2009\u2264\u2009k\u2009\u2264\u20099,\u20092\u2009\u2264\u2009s\u2009\u2264\u2009105). Then follow n lines, each containing m integers aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009k). The number in the i-th row and the j-th column (aij) means a note that the guitar produces on the i-th string and the j-th fret. The last line of the input contains s integers qi (1\u2009\u2264\u2009qi\u2009\u2264\u2009k) \u2014 the sequence of notes of the song.", "output_spec": "In a single line print a single number \u2014 the maximum possible complexity of the song.", "sample_inputs": ["4 6 5 7\n3 1 2 2 3 1\n3 2 2 2 5 5\n4 2 2 2 5 3\n3 2 2 1 4 3\n2 3 1 4 1 5 1", "4 4 9 5\n4 7 9 5\n1 2 1 7\n8 3 4 9\n5 7 7 2\n7 1 9 2 5"], "sample_outputs": ["8", "4"], "notes": null}, "positive_code": [{"source_code": "import scala.collection._\n\nobject E 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, s) = readInts(4)\n val as = Array.fill(n) { readLine }\n val qs = readInts(s)\n\n def D1(x: Int, y: Int) = x + y\n def D2(x: Int, y: Int) = x - y\n\n val minD1, minD2 = Array.fill(k) { Int.MaxValue / 2 }\n val maxD1, maxD2 = Array.fill(k) { Int.MinValue / 2 }\n\n val maxD = Array.fill(k, k) { 0 }\n val seen = mutable.BitSet()\n\n var i = 0\n while (i < n) {\n var j = 0\n while (j < m) {\n val a = as(i)(2 * j) - '1'\n seen(a) = true\n val d1 = D1(i, j)\n val d2 = D2(i, j)\n minD1(a) = Math.min(minD1(a), d1)\n maxD1(a) = Math.max(maxD1(a), d1)\n minD2(a) = Math.min(minD2(a), d2)\n maxD2(a) = Math.max(maxD2(a), d2)\n\n var u = 0\n while (u < k) {\n if (seen(u)) {\n val max = Math.max(Math.max(Math.abs(minD1(u) - d1), Math.abs(maxD1(u) - d1)),\n Math.max(Math.abs(minD2(u) - d2), Math.abs(maxD2(u) - d2)))\n maxD(a)(u) = Math.max(maxD(a)(u), max)\n maxD(u)(a) = maxD(a)(u)\n }\n u += 1\n }\n\n j += 1\n }\n i += 1\n }\n\n var prev = qs(0)\n var ans = 0\n for (q <- qs.drop(1)) {\n if (maxD(prev - 1)(q - 1) > ans) {\n ans = maxD(prev - 1)(q - 1)\n }\n prev = q\n }\n\n println(ans)\n}\n"}], "negative_code": [], "src_uid": "5ff4275de91b65115666d4a98b9f3b8b"} {"nl": {"description": "A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.The traffic light on the crosswalk from the j-th house of the i-th row to the (j\u2009+\u20091)-th house of the same row has waiting time equal to aij (1\u2009\u2264\u2009i\u2009\u2264\u20092,\u20091\u2009\u2264\u2009j\u2009\u2264\u2009n\u2009-\u20091). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals bj (1\u2009\u2264\u2009j\u2009\u2264\u2009n). The city doesn't have any other crossings.The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing. Figure to the first sample. Help Laurenty determine the minimum total time he needs to wait at the crossroads.", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of houses in each row. Each of the next two lines contains n\u2009-\u20091 space-separated integer \u2014 values aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009100). The last line contains n space-separated integers bj (1\u2009\u2264\u2009bj\u2009\u2264\u2009100).", "output_spec": "Print a single integer \u2014 the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.", "sample_inputs": ["4\n1 2 3\n3 2 1\n3 2 2 3", "3\n1 2\n3 3\n2 1 3", "2\n1\n1\n1 1"], "sample_outputs": ["12", "11", "4"], "notes": "NoteThe first sample is shown on the figure above. In the second sample, Laurenty's path can look as follows: Laurenty crosses the avenue, the waiting time is 3; Laurenty uses the second crossing in the first row, the waiting time is 2; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty crosses the avenue, the waiting time is 1; Laurenty uses the second crossing in the second row, the waiting time is 3. In total we get that the answer equals 11.In the last sample Laurenty visits all the crossings, so the answer is 4."}, "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": "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 */"}, {"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"} {"nl": {"description": "Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i.\u00a0e. the two words mean the same) and antonymy (i.\u00a0e. the two words mean the opposite). From time to time he discovers a new relation between two words.He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.", "input_spec": "The first line of input contains three integers n, m and q (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m,\u2009q\u2009\u2264\u2009105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations. The second line contains n distinct words a1,\u2009a2,\u2009...,\u2009an consisting of small English letters with length not exceeding 20, which are the words in the dictionary. Then m lines follow, each of them contains an integer t (1\u2009\u2264\u2009t\u2009\u2264\u20092) followed by two different words xi and yi which has appeared in the dictionary words. If t\u2009=\u20091, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi. Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered. All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.", "output_spec": "First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print \"NO\" (without quotes) and ignore it, otherwise print \"YES\" (without quotes). After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3. See the samples for better understanding.", "sample_inputs": ["3 3 4\nhate love like\n1 love like\n2 love hate\n1 hate like\nlove like\nlove hate\nlike hate\nhate like", "8 6 5\nhi welcome hello ihateyou goaway dog cat rat\n1 hi welcome\n1 ihateyou goaway\n2 hello ihateyou\n2 hi goaway\n2 hi hello\n1 hi hello\ndog cat\ndog hi\nhi hello\nihateyou goaway\nwelcome ihateyou"], "sample_outputs": ["YES\nYES\nNO\n1\n2\n2\n2", "YES\nYES\nYES\nYES\nNO\nYES\n3\n3\n1\n1\n2"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject MadmudAndDictionary extends App{\n case class ParentRef(order: Int, set: DSet, negate: Boolean) {\n def ^(relation: Boolean) = copy(negate = negate ^ relation)\n def upgrade = copy(order = order + 1)\n }\n\n class DSet {\n var ref = ParentRef(0, this, negate = false)\n\n def upgrade() = ref = ref.upgrade\n\n def parent: ParentRef =\n if (ref.set == this) ref\n else {\n ref = ref.set.parent ^ ref.negate\n ref\n }\n\n def union(that: DSet, negate: Boolean): Boolean = {\n val thisParent = this.parent\n val thatParent = that.parent\n if (thisParent.order > thatParent.order) that.union(this, negate)\n else if (thisParent.set == thatParent.set) !thisParent.negate ^ thatParent.negate ^ negate\n else {\n parent.set.ref = that.parent.copy() ^ (negate ^ parent.negate)\n if (thisParent.order == thatParent.order) thatParent.set.upgrade()\n true\n }\n }\n\n def query(that: DSet) =\n if (this.parent.set != that.parent.set) 3\n else if (this.parent.negate ^ that.parent.negate) 2\n else 1\n }\n\n val Array(n, m, q) = readLine().split(' ').map(_.toInt)\n val sets = readLine().split(' ').map(_ \u2192 new DSet).toMap\n for (_ \u2190 1 to m) {\n val Array(op, left, right) = readLine().split(' ')\n println(if (sets(left).union(sets(right), op == \"2\")) \"YES\" else \"NO\")\n }\n for (_ \u2190 1 to q) {\n val Array(left, right) = readLine().split(' ')\n println(sets(left).query(sets(right)))\n }\n}\n"}], "negative_code": [], "src_uid": "c4f97a986dccc433835addca8efec972"} {"nl": {"description": "An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.", "input_spec": "The first line contains an integer $$$t$$$ $$$(1 \\le t \\le 100)$$$\u00a0\u2014 the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \\le n \\le 10^9)$$$\u00a0\u2014 the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.", "sample_inputs": ["3\n6\n4\n30"], "sample_outputs": ["2 3 6 \n1\n2 4 \n0\n2 30 6 3 15 5 10 \n0"], "notes": "NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime."}, "positive_code": [{"source_code": "import java.io._\nimport java.math.BigInteger\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject E {\n def solve(in: Input, out: PrintWriter): Unit = {\n val (primes, nonPrime) = makeSieve(100000)\n val myPrimes = new Array[Int](primes.length)\n for (_ <- 0 until in.nextInt()) {\n val v = in.nextInt()\n val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)\n if (firstPrimeIndex == -1) {\n println(s\"$v is prime\")\n } else {\n val firstPrime = primes(firstPrimeIndex)\n val rest = v / firstPrime\n if (BigInteger.valueOf(rest).isProbablePrime(25)) {\n // v is p1 * p2\n if (rest == firstPrime) {\n // easy\n out.println(firstPrime + \" \" + v)\n out.println(0)\n } else {\n out.println(firstPrime + \" \" + rest + \" \" + v)\n out.println(1)\n }\n } else {\n var primeCount = 1\n myPrimes(0) = firstPrime\n var tmp = drain(v, firstPrime)\n var primeIndex = firstPrimeIndex + 1\n while (primeIndex < primes.length && tmp > 1) {\n val pp = primes(primeIndex)\n primeIndex += 1\n if (tmp % pp == 0) {\n myPrimes(primeCount) = pp\n primeCount += 1\n tmp = drain(tmp, pp)\n }\n }\n if (tmp > 1) {\n myPrimes(primeCount) = tmp\n primeCount += 1\n }\n val used = new scala.collection.mutable.HashSet[Int]\n used.add(1)\n val lists = Array.fill(primeCount)(Array.newBuilder[Int])\n val postLists = new Array[Int](primeCount)\n for (i <- 0 until primeCount) {\n lists(i) += myPrimes(i)\n used.add(myPrimes(i))\n val nv = myPrimes(i) * myPrimes((i + 1) % primeCount)\n if (used.contains(nv)) {\n postLists(i) = v\n used.add(v)\n } else {\n postLists(i) = nv\n used.add(nv)\n }\n }\n\n var divisor = 1\n while (divisor <= v / divisor) {\n if (v % divisor == 0) {\n if (!used.contains(divisor)) {\n lists(findIndex(divisor, myPrimes, 0)) += divisor\n used.add(divisor)\n }\n val another = v / divisor\n if (!used.contains(another)) {\n lists(findIndex(another, myPrimes, 0)) += another\n used.add(another)\n }\n }\n divisor += 1\n }\n\n for (i <- 0 until primeCount) lists(i) += postLists(i)\n\n out.println(lists.flatMap(_.result()).mkString(\" \"))\n out.println(0)\n }\n }\n }\n }\n\n @tailrec\n private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int = {\n if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)\n }\n\n @tailrec\n private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"3\\n6\\n4\\n30\", \"2 3 6\\n1\\n2 4\\n0\\n2 30 6 3 15 5 10\\n0\", \"Sample\"),\n (\"1\\n12\", \"2 4 6 3 12\\n0\", \"Tricky case 1\"),\n (\"1\\n2000006\", \"2 1000003 2000006\\n1\", \"Special #1\"),\n (\"1\\n4000012\", \"2 4 2000006 1000003 4000012\\n0\", \"Special #2\"),\n )\n\n def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {\n val nonPrime = new Array[Boolean](limit + 1)\n val builder = Array.newBuilder[Int]\n var i = 2\n while (i <= limit) {\n if (!nonPrime(i)) {\n builder += i\n var j = 2 * i\n while (j <= limit) {\n nonPrime(j) = true\n j += i\n }\n }\n i += 1\n }\n (builder.result(), nonPrime)\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 E {\n def solve(in: Input, out: PrintWriter): Unit = {\n val (primes, nonPrime) = makeSieve(100000)\n val myPrimes = new Array[Int](primes.length)\n for (_ <- 0 until in.nextInt()) {\n val v = in.nextInt()\n val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)\n if (firstPrimeIndex == -1) {\n println(s\"$v is prime\")\n } else {\n val firstPrime = primes(firstPrimeIndex)\n val rest = v / firstPrime\n if (rest < nonPrime.length && !nonPrime(rest)) {\n // v is p1 * p2\n if (rest == firstPrime) {\n // easy\n out.println(firstPrime + \" \" + v)\n out.println(0)\n } else {\n out.println(firstPrime + \" \" + rest + \" \" + v)\n out.println(1)\n }\n } else {\n var primeCount = 1\n myPrimes(0) = firstPrime\n var tmp = drain(v, firstPrime)\n var primeIndex = firstPrimeIndex + 1\n while (primeIndex < primes.length && tmp > 1) {\n val pp = primes(primeIndex)\n primeIndex += 1\n if (tmp % pp == 0) {\n myPrimes(primeCount) = pp\n primeCount += 1\n tmp = drain(tmp, pp)\n }\n }\n if (tmp > 1) {\n myPrimes(primeCount) = tmp\n primeCount += 1\n }\n val used = new scala.collection.mutable.HashSet[Int]\n used.add(1)\n val lists = Array.fill(primeCount)(Array.newBuilder[Int])\n val postLists = new Array[Int](primeCount)\n for (i <- 0 until primeCount) {\n lists(i) += myPrimes(i)\n used.add(myPrimes(i))\n val nv = myPrimes(i) * myPrimes((i + 1) % primeCount)\n if (used.contains(nv)) {\n postLists(i) = v\n used.add(v)\n } else {\n postLists(i) = nv\n used.add(nv)\n }\n }\n\n var divisor = 1\n while (divisor <= v / divisor) {\n if (v % divisor == 0) {\n if (!used.contains(divisor)) {\n lists(findIndex(divisor, myPrimes, 0)) += divisor\n used.add(divisor)\n }\n val another = v / divisor\n if (!used.contains(another)) {\n lists(findIndex(another, myPrimes, 0)) += another\n used.add(another)\n }\n }\n divisor += 1\n }\n\n for (i <- 0 until primeCount) lists(i) += postLists(i)\n\n out.println(lists.flatMap(_.result()).mkString(\" \"))\n out.println(0)\n }\n }\n }\n }\n\n @tailrec\n private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int = {\n if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)\n }\n\n @tailrec\n private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"3\\n6\\n4\\n30\", \"2 3 6\\n1\\n2 4\\n0\\n2 30 6 3 15 5 10\\n0\", \"Sample\"),\n (\"1\\n12\", \"2 4 6 3 12\\n0\", \"Tricky case 1\")\n )\n\n def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {\n val nonPrime = new Array[Boolean](limit + 1)\n val builder = Array.newBuilder[Int]\n var i = 2\n while (i <= limit) {\n if (!nonPrime(i)) {\n builder += i\n var j = 2 * i\n while (j <= limit) {\n nonPrime(j) = true\n j += i\n }\n }\n i += 1\n }\n (builder.result(), nonPrime)\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": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject E {\n def solve(in: Input, out: PrintWriter): Unit = {\n val (primes, nonPrime) = makeSieve(100000)\n val myPrimes = new Array[Int](primes.length)\n for (_ <- 0 until in.nextInt()) {\n val v = in.nextInt()\n val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)\n val firstPrime = primes(firstPrimeIndex)\n val rest = v / firstPrime\n if (rest < nonPrime.length && !nonPrime(rest)) {\n // v is p1 * p2\n if (rest == firstPrime) {\n // easy\n out.println(firstPrime + \" \" + v)\n out.println(0)\n } else {\n out.println(firstPrime + \" \" + rest + \" \" + v)\n out.println(1)\n }\n } else {\n var primeCount = 1\n myPrimes(0) = firstPrime\n var tmp = drain(v, firstPrime)\n var primeIndex = firstPrimeIndex\n while (tmp > 1) {\n primeIndex += 1\n val pp = primes(primeIndex)\n if (tmp % pp == 0) {\n myPrimes(primeCount) = pp\n primeCount += 1\n tmp = drain(tmp, pp)\n }\n }\n val used = new scala.collection.mutable.HashSet[Int]\n used.add(1)\n val lists = Array.fill(primeCount)(Array.newBuilder[Int])\n for (i <- 0 until primeCount) {\n lists(i) += myPrimes(i)\n used.add(myPrimes(i))\n val nv = myPrimes(i) * myPrimes((i + 1) % primeCount)\n lists(i) += nv\n used.add(nv)\n }\n\n var divisor = 1\n while (divisor <= v / divisor) {\n if (v % divisor == 0) {\n if (!used.contains(divisor)) {\n lists(findIndex(divisor, myPrimes, 0)) += divisor\n used.add(divisor)\n }\n val another = v / divisor\n if (!used.contains(another)) {\n lists(findIndex(another, myPrimes, 0)) += another\n used.add(another)\n }\n }\n divisor += 1\n }\n\n out.println(lists.flatMap(_.result()).mkString(\" \"))\n out.println(0)\n }\n }\n }\n\n @tailrec\n private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int = {\n if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)\n }\n\n @tailrec\n private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"3\\n6\\n4\\n30\", \"2 3 6\\n1\\n2 4\\n0\\n2 6 30 3 15 5 10\\n0\", \"Sample\"),\n )\n\n def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {\n val nonPrime = new Array[Boolean](limit + 1)\n val builder = Array.newBuilder[Int]\n var i = 2\n while (i <= limit) {\n if (!nonPrime(i)) {\n builder += i\n var j = 2 * i\n while (j <= limit) {\n nonPrime(j) = true\n j += i\n }\n }\n i += 1\n }\n (builder.result(), nonPrime)\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": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.annotation.tailrec\n\nobject E {\n def solve(in: Input, out: PrintWriter): Unit = {\n val (primes, nonPrime) = makeSieve(100000)\n val myPrimes = new Array[Int](primes.length)\n for (_ <- 0 until in.nextInt()) {\n val v = in.nextInt()\n val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)\n val firstPrime = primes(firstPrimeIndex)\n val rest = v / firstPrime\n if (rest < nonPrime.length && !nonPrime(rest)) {\n // v is p1 * p2\n if (rest == firstPrime) {\n // easy\n out.println(firstPrime + \" \" + v)\n out.println(0)\n } else {\n out.println(firstPrime + \" \" + rest + \" \" + v)\n out.println(1)\n }\n } else {\n var primeCount = 1\n myPrimes(0) = firstPrime\n var tmp = drain(v, firstPrime)\n var primeIndex = firstPrimeIndex\n while (tmp > 1) {\n primeIndex += 1\n val pp = primes(primeIndex)\n if (tmp % pp == 0) {\n myPrimes(primeCount) = pp\n primeCount += 1\n tmp = drain(tmp, pp)\n }\n }\n val lists = Array.fill(primeCount)(Array.newBuilder[Int])\n for (i <- 0 until primeCount) lists(i) += myPrimes(i)\n\n var divisor = 1\n while (divisor <= v / divisor) {\n if (v % divisor == 0) {\n if (nonPrime(divisor)) {\n lists(findIndex(divisor, myPrimes, 0)) += divisor\n }\n val another = v / divisor\n if (another != divisor) {\n lists(findIndex(another, myPrimes, 0)) += another\n }\n }\n divisor += 1\n }\n\n out.println(lists.flatMap(_.result()).mkString(\" \"))\n out.println(0)\n }\n }\n }\n\n @tailrec\n private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int =\n if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)\n\n @tailrec\n private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v\n\n private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(\n (\"3\\n6\\n4\\n30\", \"2 3 6\\n1\\n2 4\\n0\\n2 30 10 6 3 15 5\\n0\", \"Sample\"),\n )\n\n def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {\n val nonPrime = new Array[Boolean](limit + 1)\n val builder = Array.newBuilder[Int]\n var i = 2\n while (i <= limit) {\n if (!nonPrime(i)) {\n builder += i\n var j = 2 * i\n while (j <= limit) {\n nonPrime(j) = true\n j += i\n }\n }\n i += 1\n }\n (builder.result(), nonPrime)\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": "406f8f662d2013d87b36dacca663bef5"} {"nl": {"description": "Mahmoud and Ehab are in the fourth stage now.Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length n, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.Help Mahmoud and Ehab find these two positions.You will get Wrong Answer verdict if Your queries doesn't satisfy interaction protocol described below. You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query. Your final answer is not correct. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .", "input_spec": "The first line of input will contain a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the length of the hidden binary string.", "output_spec": "To print the final answer, print \"! pos0 pos1\" (without quotes), where pos0 and pos1 are positions of some '0' and some '1' in the string (the string is 1-indexed). Don't forget to flush the output after printing the answer!", "sample_inputs": ["3\n2\n1\n3\n2\n1\n0"], "sample_outputs": ["? 000\n? 001\n? 010\n? 011\n? 100\n? 101\n! 2 1"], "notes": "NoteHamming distance definition: https://en.wikipedia.org/wiki/Hamming_distanceIn the first test case the hidden binary string is 101, The first query is 000, so the Hamming distance is 2. In the second query the hidden string is still 101 and query is 001, so the Hamming distance is 1.After some queries you find that symbol at position 2 is '0' and symbol at position 1 is '1', so you print \"! 2 1\"."}, "positive_code": [{"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)\n\n def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1\n\n def question(query: IndexedSeq[Int]): Int = {\n println(s\"? ${query.mkString(\"\")}\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - all\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (t == m - l + 1) guess(m + 1, r, l, pos1)\n else if (t == l - m - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n val n = scala.io.StdIn.readLine().toInt\n val all = question(query)\n answer(guess(1, n))\n}"}], "negative_code": [{"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)\n\n def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1\n\n def question(query: IndexedSeq[Int]): Int = {\n println(s\"? ${query.mkString(\"\")}\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - all\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (t == r - l + 1) guess(m + 1, r, l, pos1)\n else if (t == l - r - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n val n = scala.io.StdIn.readLine().toInt\n val all = question(query)\n answer(guess(1, n))\n}"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)\n\n def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1\n\n def question(query: IndexedSeq[Int]): Int = {\n println(s\"? ${query.mkString(\"\")}\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 2\n val t = zero(l, m)\n if (t == m - l + 1) guess(m + 1, r, l, pos1)\n else if (t == l - m - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n /**\n * 2\u2009\u2264\u2009n\u2009\u2264\u20091000\n */\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: IndexedSeq[Byte] = IndexedSeq.fill(n)(1)\n\n def query(l: Long, r: Long): IndexedSeq[Byte] = for (i <- 1 to n) yield if (i >= l && i <= r) 0:Byte else 1:Byte\n\n def question(query: IndexedSeq[Byte]): Long = {\n println(s\"? ${query.mkString(\"\")}\")\n Console.flush()\n n - scala.io.StdIn.readLine().toLong\n }\n\n def answer(pos: (Long, Long)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Long, r: Long): Long = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Long, r: Long, pos0: Long = 0, pos1: Long = 0): (Long, Long) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (pos0 == 0 && t == m - l + 1) guess(m + 1, r, l, pos1)\n else if (pos1 == 0 && t == l - m - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n /**\n * 2\u2009\u2264\u2009n\u2009\u2264\u20091000\n */\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: IndexedSeq[Byte] = IndexedSeq.fill(n)(1)\n\n def query(l: Long, r: Long): IndexedSeq[Byte] = for (i <- 1 to n) yield if (i >= l && i <= r) 0:Byte else 1:Byte\n\n def question(query: IndexedSeq[Byte]): Long = {\n println(s\"? ${query.mkString(\"\")}\")\n Console.flush()\n n - scala.io.StdIn.readLine().toLong\n }\n\n def answer(pos: (Long, Long)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Long, r: Long): Long = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Long, r: Long, pos0: Long = 0, pos1: Long = 0): (Long, Long) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (t == m - l + 1) guess(m + 1, r, l, pos1)\n else if (t == l - m - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n /**\n * 2\u2009\u2264\u2009n\u2009\u2264\u20091000\n */\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: String = \"1\" * n\n\n def query(l: Int, r: Int): String = \"1\" * (l - 1) + \"0\" * (r - l + 1) + \"1\" * (n - r)\n\n def question(query: String): Int = {\n println(s\"? $query\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (pos0 == 0 && t == r - l + 1) guess(m + 1, r, l, pos1)\n else if (pos1 == 0 && t == l - r - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n /**\n * 2\u2009\u2264\u2009n\u2009\u2264\u20091000\n */\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)\n\n def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1\n\n def question(query: IndexedSeq[Int]): Int = {\n println(s\"? ${query.mkString(\"\")}\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (t == m - l + 1) guess(m + 1, r, l, pos1)\n else if (t == l - m - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: String = \"1\" * n\n\n def query(l: Int, r: Int): String = \"1\" * (l - 1) + \"0\" * (r - l + 1) + \"1\" * (n - r)\n\n def question(query: String): Int = {\n println(s\"? $query\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (t == r - l + 1) guess(m + 1, r, l, pos1)\n else if (t == l - r - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n /**\n * 2\u2009\u2264\u2009n\u2009\u2264\u20091000\n */\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}, {"source_code": "import scala.annotation.tailrec\n\n/**\n * @see http://codeforces.com/contest/862/problem/D\n * Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw\n */\n\nobject DMahmoudAndEhabAndTheBinaryString extends App {\n def query: String = \"1\" * n\n\n def query(l: Int, r: Int): String = \"1\" * (l - 1) + \"0\" * (r - l + 1) + \"1\" * (n - r)\n\n def question(query: String): Int = {\n println(s\"? $query\")\n Console.flush()\n n - scala.io.StdIn.readLine().toInt\n }\n\n def answer(pos: (Int, Int)): Unit = {\n println(s\"! ${pos._1} ${pos._2}\")\n Console.flush()\n }\n\n def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)\n\n @tailrec\n def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {\n if (pos0 > 0 && pos1 > 0) (pos0, pos1)\n else {\n val m = (r + l) >> 1\n val t = zero(l, m)\n if (pos0 == 0 && t == m - l + 1) guess(m + 1, r, l, pos1)\n else if (pos1 == 0 && t == l - m - 1) guess(m + 1, r, pos0, l)\n else guess(l, m, pos0, pos1)\n }\n }\n\n /**\n * 2\u2009\u2264\u2009n\u2009\u2264\u20091000\n */\n val n = scala.io.StdIn.readLine().toInt\n answer(guess(1, n))\n}\n"}], "src_uid": "4dd91b32ea1a41d4ecb99bc5672ef1bc"} {"nl": {"description": "The marmots have prepared a very easy problem for this year's HC2 \u2013 this one. It involves numbers n, k and a sequence of n positive integers a1,\u2009a2,\u2009...,\u2009an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!", "input_spec": "The first line of the input contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20092200). The second line contains n space-separated integers a1,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104).", "output_spec": "Output one number.", "sample_inputs": ["8 5\n1 1 1 1 1 1 1 1", "10 3\n16 8 2 4 512 256 32 128 64 1", "5 1\n20 10 50 30 46", "6 6\n6 6 6 6 6 6", "1 1\n100"], "sample_outputs": ["5", "7", "10", "36", "100"], "notes": null}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nobject M 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\n val ans = readLine().split(' ').map(_.toInt).sorted.take(k).sum\n\n println(ans)\n}\n"}], "negative_code": [], "src_uid": "5097e92916e49cdc6fb4953b864186db"} {"nl": {"description": "The project of a data center of a Big Software Company consists of n computers connected by m cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is not yet approved, it wasn't determined yet in which direction information will go along each cable. The cables are put so that each computer is connected with each one, perhaps through some other computers.The person in charge of the cleaning the data center will be Claudia Ivanova, the janitor. She loves to tie cables into bundles using cable ties. For some reasons, she groups the cables sticking out of a computer into groups of two, and if it isn't possible, then she gets furious and attacks the computer with the water from the bucket.It should also be noted that due to the specific physical characteristics of the Very Important Information, it is strictly forbidden to connect in one bundle two cables where information flows in different directions.The management of the data center wants to determine how to send information along each cable so that Claudia Ivanova is able to group all the cables coming out of each computer into groups of two, observing the condition above. Since it may not be possible with the existing connections plan, you are allowed to add the minimum possible number of cables to the scheme, and then you need to determine the direction of the information flow for each cable (yes, sometimes data centers are designed based on the janitors' convenience...)", "input_spec": "The first line contains two numbers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000) \u2014 the number of computers and the number of the already present cables, respectively. Each of the next lines contains two numbers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n) \u2014 the indices of the computers connected by the i-th cable. The data centers often have a very complex structure, so a pair of computers may have more than one pair of cables between them and some cables may connect a computer with itself.", "output_spec": "In the first line print a single number p (p\u2009\u2265\u2009m) \u2014 the minimum number of cables in the final scheme. In each of the next p lines print a pair of numbers ci,\u2009di (1\u2009\u2264\u2009ci,\u2009di\u2009\u2264\u2009n), describing another cable. Such entry means that information will go along a certain cable in direction from ci to di. Among the cables you printed there should be all the cables presented in the original plan in some of two possible directions. It is guaranteed that there is a solution where p doesn't exceed 500\u2009000. If there are several posible solutions with minimum possible value of p, print any of them.", "sample_inputs": ["4 6\n1 2\n2 3\n3 4\n4 1\n1 3\n1 3", "3 4\n1 2\n2 3\n1 1\n3 3"], "sample_outputs": ["6\n1 2\n3 4\n1 4\n3 2\n1 3\n1 3", "6\n2 1\n2 3\n1 1\n3 3\n3 1\n1 1"], "notes": "NotePicture for the first sample test. The tied pairs of cables are shown going out from the same point. Picture for the second test from the statement. The added cables are drawin in bold. Alternative answer for the second sample test: "}, "positive_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 class GraphEdge(val from: Int, val to: Int, val id: Int) {\n }\n\n var graph: Array[List[GraphEdge]] = null\n var graphPos: Array[Iterator[GraphEdge]] = null\n var visit: Array[Boolean] = null\n var outputEdgeId: Int = 0\n\n def dfs(node: Int): Unit = {\n while (graphPos(node).hasNext) {\n val next = graphPos(node).next()\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n if ((outputEdgeId & 1) == 1) {\n out.println(node + 1 + \" \" + (next.to + 1))\n } else {\n out.println(next.to + 1 + \" \" + (node + 1))\n }\n outputEdgeId += 1\n }\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[List[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = Nil\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) = new GraphEdge(u, v, i) :: graph(u)\n graph(v) = new GraphEdge(v, u, i) :: graph(v)\n }\n val oddNode = {\n for (i <- 0 until n if (graph(i).size & 1) == 1) yield i\n }\n var edgeId = m\n for (i <- 0 until(oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i + 1), edgeId) :: graph(oddNode(i))\n graph(oddNode(i + 1)) = new GraphEdge(oddNode(i + 1), oddNode(i), edgeId) :: graph(oddNode(i + 1))\n } else {\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))\n }\n edgeId += 1\n }\n if ((edgeId & 1) != 0) {\n graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)\n graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)\n edgeId += 1\n }\n graphPos = new Array[Iterator[GraphEdge]](n)\n for (i <- 0 until n) {\n graphPos(i) = graph(i).iterator\n }\n visit = new Array[Boolean](edgeId)\n out.println(edgeId)\n dfs(0)\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\nimport collection.mutable.ArrayBuffer\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 class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {\n val from = fromNode\n val to = toNode\n val id = edgeId\n }\n\n var graph: Array[ArrayBuffer[GraphEdge]] = null\n var paths: ArrayBuffer[GraphEdge] = null\n var visit: Array[Boolean] = null\n\n def dfs(node: Int): Unit = {\n for (next <- graph(node)) {\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n paths += next\n }\n }\n }\n\n def solve(): Unit = {\n val a = new GraphEdge(1, 1,1 )\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayBuffer[GraphEdge]()\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) += new GraphEdge(u, v, i)\n graph(v) += new GraphEdge(v, u, i)\n }\n val oddNode = for (i <- 0 until n if ((graph(i).size & 1) == 1)) yield i\n var edgeId = m\n for (i <- 0 until (oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)\n graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)\n } else {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n }\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n paths = new ArrayBuffer[GraphEdge]\n dfs(0)\n out.println(edgeId)\n for (edge <- paths.reverse) {\n out.println((edge.from + 1) + \" \" + (edge.to + 1))\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"}, {"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 class GraphEdge(val from: Int, val to: Int, val id: Int) {\n }\n\n var graph: Array[List[GraphEdge]] = null\n var graphPos: Array[Int] = null\n var visit: Array[Boolean] = null\n var outputEdgeId: Int = 0\n\n def dfs(node: Int): Unit = {\n while (graphPos(node) < graph(node).length) {\n val next = graph(node)(graphPos(node))\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n if ((outputEdgeId & 1) == 1) {\n println(node + 1 + \" \" + (next.to + 1))\n } else {\n println(next.to + 1 + \" \" + (node + 1))\n }\n }\n graphPos(node) += 1\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[List[GraphEdge]](n)\n graphPos = new Array[Int](n)\n for (i <- 0 until n) {\n graph(i) = Nil\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) = new GraphEdge(u, v, i) :: graph(u)\n graph(v) = new GraphEdge(v, u, i) :: graph(v)\n }\n val oddNode = {\n for (i <- 0 until n if (graph(i).size & 1) == 1) yield i\n }\n var edgeId = m\n for (i <- 0 until(oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i + 1), edgeId) :: graph(oddNode(i))\n graph(oddNode(i + 1)) = new GraphEdge(oddNode(i + 1), oddNode(i), edgeId) :: graph(oddNode(i + 1))\n } else {\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))\n }\n edgeId += 1\n }\n if ((edgeId & 1) != 0) {\n graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)\n graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n out.println(edgeId)\n dfs(0)\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 collection.mutable.ArrayBuffer\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 class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {\n val from = fromNode\n val to = toNode\n val id = edgeId\n }\n\n var graph: Array[ArrayBuffer[GraphEdge]] = null\n var paths: ArrayBuffer[GraphEdge] = null\n var visit: Array[Boolean] = null\n\n def dfs(node: Int): Unit = {\n for (next <- graph(node)) {\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n paths += next\n }\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n println(n, m)\n graph = new Array[ArrayBuffer[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayBuffer[GraphEdge]()\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) += new GraphEdge(u, v, i)\n graph(v) += new GraphEdge(v, u, i)\n }\n val oddNode = for (i <- 0 until n if ((graph(i).size & 1) == 1)) yield i\n var edgeId = m\n for (i <- 0 until (oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)\n graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)\n } else {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n }\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n paths = new ArrayBuffer[GraphEdge]\n dfs(0)\n out.println(edgeId)\n for (edge <- paths.reverse) {\n out.println((edge.from + 1) + \" \" + (edge.to + 1))\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"}, {"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 class GraphEdge(val from: Int, val to: Int, val id: Int) {\n }\n\n var graph: Array[List[GraphEdge]] = null\n var graphPos: Array[Int] = null\n var visit: Array[Boolean] = null\n var outputEdgeId: Int = 0\n\n def dfs(node: Int): Unit = {\n while (graphPos(node) < graph(node).length) {\n val next = graph(node)(graphPos(node))\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n if ((outputEdgeId & 1) == 1) {\n println(node + 1 + \" \" + (next.to + 1))\n } else {\n println(next.to + 1 + \" \" + (node + 1))\n }\n outputEdgeId += 1\n }\n\n graphPos(node) += 1\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[List[GraphEdge]](n)\n graphPos = new Array[Int](n)\n for (i <- 0 until n) {\n graph(i) = Nil\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) = new GraphEdge(u, v, i) :: graph(u)\n graph(v) = new GraphEdge(v, u, i) :: graph(v)\n }\n val oddNode = {\n for (i <- 0 until n if (graph(i).size & 1) == 1) yield i\n }\n var edgeId = m\n for (i <- 0 until(oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i + 1), edgeId) :: graph(oddNode(i))\n graph(oddNode(i + 1)) = new GraphEdge(oddNode(i + 1), oddNode(i), edgeId) :: graph(oddNode(i + 1))\n } else {\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))\n graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))\n }\n edgeId += 1\n }\n if ((edgeId & 1) != 0) {\n graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)\n graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n out.println(edgeId)\n dfs(0)\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 collection.mutable.ArrayBuffer\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 class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {\n val from = fromNode\n val to = toNode\n val id = edgeId\n }\n\n var graph: Array[ArrayBuffer[GraphEdge]] = null\n var paths: ArrayBuffer[GraphEdge] = null\n var visit: Array[Boolean] = null\n\n def dfs(node: Int): Unit = {\n for (next <- graph(node)) {\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n paths += next\n }\n }\n }\n\n def solve(): Unit = {\n val a = new GraphEdge(1, 1,1 )\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayBuffer[GraphEdge]()\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) += new GraphEdge(u, v, i)\n graph(v) += new GraphEdge(v, u, i)\n }\n val oddNode = for (i <- 0 until n if ((graph(i).size & 1) == 1)) yield i\n var edgeId = m\n for (i <- 0 until (oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)\n graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)\n } else {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n }\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n paths = new ArrayBuffer[GraphEdge]\n dfs(0)\n out.println(edgeId)\n for (edge <- paths.reverse) {\n out.println(edge.from + 1 + \" \" + (edge.to + 1))\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"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\nimport collection.mutable.ArrayBuffer\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 class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {\n val from = fromNode\n val to = toNode\n val id = edgeId\n }\n\n var graph: Array[ArrayBuffer[GraphEdge]] = null\n var paths: ArrayBuffer[GraphEdge] = null\n var visit: Array[Boolean] = null\n\n def dfs(node: Int): Unit = {\n for (next <- graph(node)) {\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n paths += next\n println(next.from + \" \" + next.to)\n }\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayBuffer[GraphEdge]()\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) += new GraphEdge(u, v, i)\n graph(v) += new GraphEdge(v, u, i)\n }\n val oddNode = {\n for (i <- 0 until n if (graph(i).size & 1) == 1) yield i\n }\n var edgeId = m\n for (i <- 0 until (oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)\n graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)\n } else {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n }\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n paths = new ArrayBuffer[GraphEdge]\n dfs(0)\n out.println(edgeId)\n for (edge <- paths.reverse) {\n out.println((edge.from + 1) + \" \" + (edge.to + 1))\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"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\nimport collection.mutable.ArrayBuffer\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 class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {\n val from = fromNode\n val to = toNode\n val id = edgeId\n }\n\n var graph: Array[ArrayBuffer[GraphEdge]] = null\n var paths: ArrayBuffer[GraphEdge] = null\n var visit: Array[Boolean] = null\n\n def dfs(node: Int): Unit = {\n for (next <- graph(node)) {\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n paths += next\n }\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayBuffer[GraphEdge]()\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) += new GraphEdge(u, v, i)\n graph(v) += new GraphEdge(v, u, i)\n }\n val oddNode = {\n for (i <- 0 until n if (graph(i).size & 1) == 1) yield i\n }\n var edgeId = m\n for (i <- 0 until(oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)\n graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)\n } else {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n }\n edgeId += 1\n }\n if ((edgeId & 1) != 0) {\n graph(0) += new GraphEdge(0, 0, edgeId)\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n paths = new ArrayBuffer[GraphEdge]\n dfs(0)\n out.println(edgeId)\n for (i <- (0 until edgeId).reverse) {\n val edge = paths(i)\n if ((i & 1) == 0) {\n out.println((edge.from + 1) + \" \" + (edge.to + 1))\n } else {\n out.println((edge.to + 1) + \" \" + (edge.from + 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\n"}, {"source_code": "/**\n *\n * Created by ronaflx on 15-4-3.\n */\n\nimport java.io._\nimport java.util.StringTokenizer\nimport collection.mutable.ArrayBuffer\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 class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {\n val from = fromNode\n val to = toNode\n val id = edgeId\n }\n\n var graph: Array[ArrayBuffer[GraphEdge]] = null\n var paths: ArrayBuffer[GraphEdge] = null\n var visit: Array[Boolean] = null\n\n def dfs(node: Int): Unit = {\n for (next <- graph(node)) {\n if (!visit(next.id)) {\n visit(next.id) = true\n dfs(next.to)\n paths += next\n }\n }\n }\n\n def solve(): Unit = {\n val (n, m) = (nextInt, nextInt)\n graph = new Array[ArrayBuffer[GraphEdge]](n)\n for (i <- 0 until n) {\n graph(i) = new ArrayBuffer[GraphEdge]()\n }\n for (i <- 0 until m) {\n var (u, v) = (nextInt, nextInt)\n u -= 1\n v -= 1\n graph(u) += new GraphEdge(u, v, i)\n graph(v) += new GraphEdge(v, u, i)\n }\n val oddNode = {\n for (i <- 0 until n if (graph(i).size & 1) == 1) yield i\n }\n var edgeId = m\n for (i <- 0 until(oddNode.size, 2)) {\n if (i + 1 < oddNode.size) {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)\n graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)\n } else {\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)\n }\n edgeId += 1\n }\n if ((edgeId & 1) != 0) {\n graph(0) += new GraphEdge(0, 0, edgeId)\n edgeId += 1\n }\n visit = new Array[Boolean](edgeId)\n paths = new ArrayBuffer[GraphEdge]\n dfs(0)\n out.println(edgeId)\n for (i <- (1 until edgeId).reverse) {\n val edge = paths(i)\n if ((i & 1) == 0) {\n out.println((edge.from + 1) + \" \" + (edge.to + 1))\n } else {\n out.println((edge.to + 1) + \" \" + (edge.from + 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\n"}], "src_uid": "877ee29229b72d37a70c693ff504b5da"} {"nl": {"description": "The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri \u2014 the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1,\u2009y1) and (x2,\u2009y2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.", "input_spec": "The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa\u2009\u2260\u2009xb,\u2009ya\u2009\u2260\u2009yb). The second line contains integer n \u2014 the number of radiators (1\u2009\u2264\u2009n\u2009\u2264\u2009103). Then n lines contain the heaters' coordinates as \"xi yi ri\", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1\u2009\u2264\u2009ri\u2009\u2264\u20091000. Several radiators can be located at the same point.", "output_spec": "Print the only number \u2014 the number of blankets you should bring.", "sample_inputs": ["2 5 4 2\n3\n3 1 2\n5 3 1\n1 3 2", "5 2 6 3\n2\n6 2 2\n6 5 3"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first sample the generals are sitting at points: (2,\u20092), (2,\u20093), (2,\u20094), (2,\u20095), (3,\u20092), (3,\u20095), (4,\u20092), (4,\u20093), (4,\u20094), (4,\u20095). Among them, 4 generals are located outside the heating range. They are the generals at points: (2,\u20095), (3,\u20095), (4,\u20094), (4,\u20095).In the second sample the generals are sitting at points: (5,\u20092), (5,\u20093), (6,\u20092), (6,\u20093). All of them are located inside the heating range."}, "positive_code": [{"source_code": "import collection.JavaConversions._\n\nobject P144B extends App {\n val Array(xa,ya,xb,yb) = readLine.split(\" \").map(_.toInt)\n val coordinates = ((for (x <- math.min(xa,xb) to math.max(xa,xb); y <- List(ya,yb)) yield (x,y)) ++\n \t(for (y <- math.min(ya,yb) to math.max(ya,yb); x <- List(xa,xb)) yield (x,y)))\n val generals = new java.util.LinkedList[(Int,Int)]()\n for(e <- coordinates) generals.add(e)\n val n = readLine.toInt\n for (i <- 1 to n){\n val Array(x,y,r) = readLine.split(\" \").map(_.toInt)\n val iter = generals.iterator()\n while(iter.hasNext()){\n val e = iter.next()\n if(math.sqrt( math.pow(x-e._1,2) + math.pow(y-e._2,2) ) <= r) iter.remove()\n }\n }\n print(generals.toSet.size)\n}"}], "negative_code": [], "src_uid": "9e7fdc3261d312e7578da7f14c259e43"} {"nl": {"description": "Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that: the government chooses some subset of people (maybe all of them); the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of test cases. Next $$$2T$$$ lines contain the test cases \u2014 two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le x \\le 10^9$$$) \u2014 the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.", "sample_inputs": ["4\n4 3\n5 1 2 1\n4 10\n11 9 11 9\n2 5\n4 3\n3 7\n9 4 9"], "sample_outputs": ["2\n4\n0\n3"], "notes": "NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\\underline{11}, \\underline{9}, 11, 9] \\rightarrow [10, 10, \\underline{11}, \\underline{9}] \\rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\\underline{9}, \\underline{4}, \\underline{9}] \\rightarrow [7\\frac{1}{3}, 7\\frac{1}{3}, 7\\frac{1}{3}]$$$."}, "positive_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: 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}"}, {"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"} {"nl": {"description": "Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$)\u00a0\u2014 the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10\\,000$$$) \u2014 the lengths of the sticks.", "output_spec": "Print one integer\u00a0\u2014 the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.", "sample_inputs": ["3\n1 2 3", "4\n1 1 2 2"], "sample_outputs": ["26", "20"], "notes": "NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \\cdot 5 + 1 \\cdot 1 = 26$$$, and in the second example $$$4 \\cdot 4 + 2 \\cdot 2 = 20$$$. "}, "positive_code": [{"source_code": "object GrowTree extends App {\n val (n, boards) = readFromTerminal()\n println(compute(n, boards))\n\n def readFromTerminal() = {\n val n = readInt()\n val boards = readLine().split(' ').map(x => x.toInt).toList\n// val boards = List.range(1, n)\n (n, boards)\n }\n\n def compute(n: Int, boards: List[Int]): BigInt = {\n if (n == 0)\n return 0\n if (n == 1)\n return Math.pow(boards.head, 2).toInt\n val sortedBoards = boards.sorted\n var boundary = n/2\n val lowNumber = BigInt.int2bigInt(sortedBoards.take(boundary).sum)\n val highNumber = BigInt.int2bigInt(sortedBoards.takeRight(n - boundary).sum)\n (lowNumber * lowNumber) + (highNumber * highNumber)\n }\n}"}], "negative_code": [{"source_code": "object GrowTree extends App {\n val (n, boards) = readFromTerminal()\n println(compute(n, boards))\n\n def readFromTerminal() = {\n val n = readInt()\n val boards = readLine().split(' ').map(x => x.toInt).toList\n (n, boards)\n }\n\n def compute(n: Int, boards: List[Int]): Int = {\n if (n == 0)\n return 0\n if (n == 1)\n return boards(0)\n val sortedBoards = boards.sorted\n var boundary = n/2\n// println(sortedBoards.take(boundary).sum)\n// println(sortedBoards.takeRight(n - boundary).sum)\n (Math.pow(sortedBoards.take(boundary).sum,2.0) + Math.pow(sortedBoards.takeRight(n-boundary).sum, 2.0)).intValue()\n }\n}"}, {"source_code": "object GrowTree extends App {\n val (n, boards) = readFromTerminal()\n println(compute(n, boards))\n\n def readFromTerminal() = {\n val n = readInt()\n val boards = readLine().split(' ').map(x => x.toInt).toList\n (n, boards)\n }\n\n def compute(n: Int, boards: List[Int]): Int = {\n if (n == 0)\n return 0\n if (n == 1)\n return Math.pow(boards(0), 2).toInt\n val sortedBoards = boards.sorted\n var boundary = n/2\n// println(sortedBoards.take(boundary).sum)\n// println(sortedBoards.takeRight(n - boundary).sum)\n (Math.pow(sortedBoards.take(boundary).sum,2.0) + Math.pow(sortedBoards.takeRight(n-boundary).sum, 2.0)).intValue()\n }\n}"}], "src_uid": "f9fbb45e45d3040e3be19a39ea8faa1f"} {"nl": {"description": "There are $$$n$$$ points on a plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$. You have two horizontal platforms, both of length $$$k$$$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $$$y$$$-coordinate) and have integer borders. If the left border of the platform is $$$(x, y)$$$ then the right border is $$$(x + k, y)$$$ and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $$$y$$$-coordinate.When you place both platforms on a plane, all points start falling down decreasing their $$$y$$$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer $$$t$$$ independent test cases.For better understanding, please read the Note section below to see a picture for the first test case.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$1 \\le k \\le 10^9$$$) \u2014 the number of points and the length of each platform, respectively. The second line of the test case contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$1 \\le x_i \\le 10^9$$$), where $$$x_i$$$ is $$$x$$$-coordinate of the $$$i$$$-th point. The third line of the input contains $$$n$$$ integers $$$y_1, y_2, \\dots, y_n$$$ ($$$1 \\le y_i \\le 10^9$$$), where $$$y_i$$$ is $$$y$$$-coordinate of the $$$i$$$-th point. All points are distinct (there is no pair $$$1 \\le i < j \\le n$$$ such that $$$x_i = x_j$$$ and $$$y_i = y_j$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.", "sample_inputs": ["4\n7 1\n1 5 2 3 1 5 4\n1 3 6 7 2 5 4\n1 1\n1000000000\n1000000000\n5 10\n10 7 5 15 8\n20 199 192 219 1904\n10 10\n15 19 8 17 20 10 9 2 10 19\n12 13 6 17 1 14 7 9 19 3"], "sample_outputs": ["6\n1\n5\n10"], "notes": "NoteThe picture corresponding to the first test case of the example:Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points $$$(1, -1)$$$ and $$$(2, -1)$$$ and the second one between points $$$(4, 3)$$$ and $$$(5, 3)$$$. Vectors represent how the points will fall down. As you can see, the only point we can't save is the point $$$(3, 7)$$$ so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point $$$(5, 3)$$$ doesn't fall at all because it is already on the platform."}, "positive_code": [{"source_code": "//package codeforces.contests._1409\n\nobject TwoPlatforms {\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\n val arr = io.StdIn.readLine.split(\" \").map(_.toInt).sorted\n\n io.StdIn.readLine.split(\" \").map(_.toInt) // dirty read\n\n val right: IndexedSeq[Int] = {\n val right = new Array[Int](n)\n\n @scala.annotation.tailrec\n def loopR(i: Int = 0, j: Int = 0): Unit = {\n if (i != n) {\n if (j == n || arr(i) + k < arr(j)) {\n right(i) = j - i\n loopR(i + 1, j max (i + 1))\n }\n else loopR(i, j + 1)\n }\n }\n\n loopR()\n right\n }\n\n val rightMax = right.scanRight(Int.MinValue)(_ max _)\n\n val left: IndexedSeq[Int] = {\n val left = new Array[Int](n)\n\n @scala.annotation.tailrec\n def loopL(i: Int = n - 1, j: Int = n - 1): Unit = {\n if (i >= 0) {\n if (j < 0 || arr(i) - k > arr(j)) {\n left(i) = i - j\n loopL(i - 1, j min (i - 1))\n }\n else loopL(i, j - 1)\n }\n }\n\n loopL()\n left\n }\n\n val leftMax = left.scanLeft(Int.MinValue)(_ max _).tail\n\n @scala.annotation.tailrec\n def loop(i: Int = 0, acc: Int = Int.MinValue): Int = {\n if (i == n) acc\n else {\n loop(\n i + 1,\n acc max {\n right(i) + {\n val rightResult = if (i + right(i) + 1 < n) rightMax(i + right(i) + 1) else Int.MinValue\n val leftResult = if (i > 0) leftMax(i - 1) else Int.MinValue\n val result = leftResult max rightResult\n\n if (result == Int.MinValue) 0 else result\n }\n }\n )\n }\n }\n\n println {\n loop()\n }\n }\n }\n}\n"}], "negative_code": [], "src_uid": "ae4378fbdb863ed6c30aae5d22851531"} {"nl": {"description": "You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.The forestThe Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example): MovesBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions: Do nothing. Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees. If you are located on the exit cell, you may leave the forest. Only you can perform this move \u2014 all other mikemon breeders will never leave the forest by using this type of movement. After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).Mikemon battleIf you and t (t\u2009>\u20090) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders \u2014 there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).Your goalYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.Goal of other breedersBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.Your taskPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.", "input_spec": "The first line consists of two integers: r and c (1\u2009\u2264\u2009r,\u2009c\u2009\u2264\u20091000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell: 'T': A cell occupied by a tree. 'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map. 'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map. A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder). It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.", "output_spec": "A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.", "sample_inputs": ["5 7\n000E0T3\nT0TT0T0\n010T0T0\n2T0T0T0\n0T0S000", "1 4\nSE23"], "sample_outputs": ["3", "2"], "notes": "NoteThe following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog: The three breeders on the left side of the map will be able to battle you \u2014 the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.For the second example, you should post this sequence in your Blog: Here's what happens. First, you move one cell to the right. Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing. You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest. Finally, you make another move by leaving the forest. "}, "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 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}"}, {"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 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}"}], "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"} {"nl": {"description": "You are given two integers $$$b$$$ and $$$w$$$. You have a chessboard of size $$$10^9 \\times 10^9$$$ with the top left cell at $$$(1; 1)$$$, the cell $$$(1; 1)$$$ is painted white.Your task is to find a connected component on this chessboard that contains exactly $$$b$$$ black cells and exactly $$$w$$$ white cells. Two cells are called connected if they share a side (i.e. for the cell $$$(x, y)$$$ there are at most four connected cells: $$$(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)$$$). A set of cells is called a connected component if for every pair of cells $$$C_1$$$ and $$$C_2$$$ from this set, there exists a sequence of cells $$$c_1$$$, $$$c_2$$$, ..., $$$c_k$$$ such that $$$c_1 = C_1$$$, $$$c_k = C_2$$$, all $$$c_i$$$ from $$$1$$$ to $$$k$$$ are belong to this set of cells and for every $$$i \\in [1, k - 1]$$$, cells $$$c_i$$$ and $$$c_{i + 1}$$$ are connected.Obviously, it can be impossible to find such component. In this case print \"NO\". Otherwise, print \"YES\" and any suitable connected component.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^5$$$)\u00a0\u2014 the number of queries. Then $$$q$$$ queries follow. The only line of the query contains two integers $$$b$$$ and $$$w$$$ ($$$1 \\le b, w \\le 10^5$$$)\u00a0\u2014 the number of black cells required and the number of white cells required. It is guaranteed that the sum of numbers of cells does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum w + \\sum b \\le 2 \\cdot 10^5$$$).", "output_spec": "For each query, print the answer to it. If it is impossible to find the required component, print \"NO\" on the first line. Otherwise, print \"YES\" on the first line. In the next $$$b + w$$$ lines print coordinates of cells of your component in any order. There should be exactly $$$b$$$ black cells and $$$w$$$ white cells in your answer. The printed component should be connected. If there are several answers, you can print any. All coordinates in the answer should be in the range $$$[1; 10^9]$$$.", "sample_inputs": ["3\n1 1\n1 4\n2 5"], "sample_outputs": ["YES\n2 2\n1 2\nYES\n2 3\n1 3\n3 3\n2 2\n2 4\nYES\n2 3\n2 4\n2 5\n1 3\n1 5\n3 3\n3 5"], "notes": null}, "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\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val b, w = in.next().toInt\n // a <= c\n val a = Math.min(b, w)\n val c = Math.max(b, w)\n\n if (a*2 + (a-1) + 2 < c) {\n pw.println(no)\n }\n else {\n\n var ans: List[(Int, Int)] = Nil\n\n // white\u3092\u5168\u90e8\u5165\u308c\u308b\n for (i <- 1 to a) {\n ans = (2, i*2) :: ans\n }\n\n var black: List[(Int, Int)] = Nil\n\n\n // \n for (i <- 1 to a) {\n black = (1, i*2) :: (3, i*2) :: black\n }\n\n // \u7d4c\u8def\u3092\u4f5c\u308b()\n for (i <- 0 to a) {\n black = (2, i*2+1) :: black\n }\n\n ans = ans ++ black.take(c)\n\n // black\u304cmin\u3060\u3063\u305f\u3089\u53f3\u306b\u305a\u3089\u3059\n if (b < w)\n ans = ans.map {case (x, y) => (x+1, y)}\n\n pw.println(yes)\n ans.foreach{ case (x, y) => pw.println(s\"$x $y\") }\n }\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 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\n val q = in.next().toInt\n for (_ <- 1 to q) {\n val b, w = in.next().toInt\n // a <= c\n val a = Math.min(b, w)\n val c = Math.max(b, w)\n\n if (a*2 + (a-1) + 2 < b) {\n pw.println(no)\n }\n else {\n\n var ans: List[(Int, Int)] = Nil\n\n // white\u3092\u5168\u90e8\u5165\u308c\u308b\n for (i <- 1 to a) {\n ans = (2, i*2) :: ans\n }\n\n var black: List[(Int, Int)] = Nil\n\n\n // \n for (i <- 1 to a) {\n black = (1, i*2) :: (3, i*2) :: black\n }\n\n // \u7d4c\u8def\u3092\u4f5c\u308b()\n for (i <- 0 to a) {\n black = (2, i*2+1) :: black\n }\n\n ans = ans ++ black.take(c)\n\n // black\u304cmin\u3060\u3063\u305f\u3089\u53f3\u306b\u305a\u3089\u3059\n if (b < w)\n ans = ans.map {case (x, y) => (x+1, y)}\n\n pw.println(yes)\n ans.foreach{ case (x, y) => pw.println(s\"$x $y\") }\n }\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"}], "src_uid": "92dff52c8f02d500de9fef6f2095b0bd"} {"nl": {"description": "You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n\u2009-\u20091 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: Swap i-th and j-th rows of the matrix; Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i\u2009>\u2009j.", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of rows and columns. Then follow n\u2009-\u20091 lines that contain one's positions, one per line. Each position is described by two integers xk,\u2009yk (1\u2009\u2264\u2009xk,\u2009yk\u2009\u2264\u2009n), separated by a space. A pair (xk,\u2009yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct.", "output_spec": "Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m\u2009\u2264\u2009105) \u2014 the number of actions. In each of the next m lines print three space-separated integers t,\u2009i,\u2009j (1\u2009\u2264\u2009t\u2009\u2264\u20092,\u20091\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n,\u2009i\u2009\u2260\u2009j), where t\u2009=\u20091 if you want to swap rows, t\u2009=\u20092 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.", "sample_inputs": ["2\n1 2", "3\n3 1\n1 3", "3\n2 1\n3 2"], "sample_outputs": ["2\n2 1 2\n1 1 2", "3\n2 2 3\n1 1 3\n1 1 2", "0"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "3b2c5410441e588806690056693514a8"} {"nl": {"description": "A new e-mail service \"Berlandesk\" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.", "output_spec": "Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.", "sample_inputs": ["4\nabacaba\nacaba\nabacaba\nacab", "6\nfirst\nfirst\nsecond\nsecond\nthird\nthird"], "sample_outputs": ["OK\nOK\nabacaba1\nOK", "OK\nfirst1\nOK\nsecond1\nOK\nthird1"], "notes": null}, "positive_code": [{"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": "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": "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}"}, {"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 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"} {"nl": {"description": "Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the description of the i-th bottle.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["4\n1 1\n2 2\n3 3\n4 4", "4\n1 2\n2 3\n3 4\n4 1"], "sample_outputs": ["4", "0"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \\ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \\ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \\ldots s_{l-1}s_{r+1} \\ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\\texttt{a}$$$ is $$$1$$$, the value of $$$\\texttt{b}$$$ is $$$2$$$, the value of $$$\\texttt{c}$$$ is $$$3$$$, $$$\\ldots$$$, and the value of $$$\\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 5\\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\\leq |s|\\leq 2\\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be \"Alice\". If Bob wins the round, the string must be \"Bob\". The integer must be the difference between their scores assuming both players play optimally.", "sample_inputs": ["5\n\naba\n\nabc\n\ncba\n\nn\n\ncodeforces"], "sample_outputs": ["Alice 2\nAlice 4\nAlice 4\nBob 14\nAlice 93"], "notes": "NoteFor the first round, $$$\\texttt{\"aba\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"}{\\color{red}{\\texttt{ab}}}\\texttt{a\"}\\xrightarrow{} \\texttt{\"a\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{a}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\\texttt{\"abc\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"a}{\\color{red}{\\texttt{bc}}}\\texttt{\"}\\xrightarrow{} \\texttt{\"a\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{a}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\\texttt{\"cba\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"}{\\color{red}{\\texttt{cb}}}\\texttt{a\"}\\xrightarrow{} \\texttt{\"a\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{a}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\\texttt{\"n\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"n\"}\\xrightarrow{} \\texttt{\"n\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{n}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\\texttt{\"codeforces\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"}{\\color{red}{\\texttt{codeforces}}}\\texttt{\"}\\xrightarrow{} \\texttt{\"\"}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject Main {\n\n def solveTest(tc: Int): Unit = {\n val s = StdIn.readLine()\n val a = s.map(c => c.toInt - 'a'.toInt + 1).toList\n val n = s.length\n val alice = if (n % 2 == 0) a.sum else Math.max(a.sum - a.head, a.sum - a(n - 1))\n val bob = a.sum - alice\n if (alice > bob) {\n println(s\"Alice ${alice - bob}\")\n } else {\n println(s\"Bob ${bob - alice}\")\n }\n }\n\n def main(args: Array[String]): Unit = {\n val t = StdIn.readInt()\n for (tc <- 1 to t) {\n solveTest(tc)\n }\n }\n}"}], "negative_code": [], "src_uid": "8f02891aa9d2fcd1963df3a4028aa5c0"} {"nl": {"description": "Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.", "output_spec": "In a single line print the answer to the problem \u2014 the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.", "sample_inputs": ["2\n?ab\n??b", "2\na\nb", "1\n?a?b"], "sample_outputs": ["xab", "?", "cacb"], "notes": "NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on."}, "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 n = readInt\n val ss = Array.fill(n) { readLine }\n\n val sb = new StringBuilder\n\n for (pos <- ss.head.indices) {\n var ch = '.'\n var i = 0\n while (i < n && (ch == '.' || ch == ss(i)(pos) || ss(i)(pos) == '?')) {\n if (ss(i)(pos) != '?') {\n ch = ss(i)(pos)\n }\n i += 1\n }\n if (i == n) sb += (if (ch == '.') 'x' else ch)\n else sb += '?'\n }\n\n println(sb.toString)\n}"}], "negative_code": [], "src_uid": "a51d2e6e321d7db67687a594a2b85e47"} {"nl": {"description": "In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.We will consider an extremely simplified subset of Python with only two types of statements.Simple statements are written in a single line, one per line. An example of a simple statement is assignment.For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with \"for\" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.", "input_spec": "The first line contains a single integer N (1\u2009\u2264\u2009N\u2009\u2264\u20095000)\u00a0\u2014 the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either \"f\" (denoting \"for statement\") or \"s\" (\"simple statement\"). It is guaranteed that the last line is a simple statement.", "output_spec": "Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109\u2009+\u20097. ", "sample_inputs": ["4\ns\nf\nf\ns", "4\nf\ns\nf\ns"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.simple statementfor statement for statement simple statementIn the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.for statement simple statement for statement simple statementorfor statement simple statementfor statement simple statement"}, "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"}, {"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"}], "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"} {"nl": {"description": "There are $$$n$$$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $$$x$$$ be the number of such pairs of students in a split. Pairs $$$(a, b)$$$ and $$$(b, a)$$$ are the same and counted only once.For example, if there are $$$6$$$ students: \"olivia\", \"jacob\", \"tanya\", \"jack\", \"oliver\" and \"jessica\", then: splitting into two classrooms (\"jack\", \"jacob\", \"jessica\", \"tanya\") and (\"olivia\", \"oliver\") will give $$$x=4$$$ ($$$3$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom), splitting into two classrooms (\"jack\", \"tanya\", \"olivia\") and (\"jessica\", \"oliver\", \"jacob\") will give $$$x=1$$$ ($$$0$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom). You are given the list of the $$$n$$$ names. What is the minimum $$$x$$$ we can obtain by splitting the students into classrooms?Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1\\leq n \\leq 100$$$)\u00a0\u2014 the number of students. After this $$$n$$$ lines follow. The $$$i$$$-th line contains the name of the $$$i$$$-th student. It is guaranteed each name is a string of lowercase English letters of length at most $$$20$$$. Note that multiple students may share the same name.", "output_spec": "The output must consist of a single integer $$$x$$$\u00a0\u2014 the minimum possible number of chatty pairs.", "sample_inputs": ["4\njorge\njose\noscar\njerry", "7\nkambei\ngorobei\nshichiroji\nkyuzo\nheihachi\nkatsushiro\nkikuchiyo", "5\nmike\nmike\nmike\nmike\nmike"], "sample_outputs": ["1", "2", "4"], "notes": "NoteIn the first sample the minimum number of pairs is $$$1$$$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair.In the second sample the minimum number of pairs is $$$2$$$. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo.In the third sample the minimum number of pairs is $$$4$$$. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Nick had received an awesome array of integers $$$a=[a_1, a_2, \\dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \\cdot a_2 \\cdot \\dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \\cdot a_2 \\cdot \\dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.", "input_spec": "The first line contains integer $$$n$$$ ($$$1 \\leq n \\leq 10^{5}$$$)\u00a0\u2014 number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^{6} \\leq a_i \\leq 10^{6}$$$)\u00a0\u2014 elements of the array", "output_spec": "Print $$$n$$$ numbers\u00a0\u2014 elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them.", "sample_inputs": ["4\n2 2 2 2", "1\n0", "3\n-3 -3 2"], "sample_outputs": ["-3 -3 -3 -3", "0", "-3 -3 2"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n\u2009-\u20091 and 0 to m\u2009-\u20091 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.", "input_spec": "The first line contains two integer n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). The second line contains integer b (0\u2009\u2264\u2009b\u2009\u2264\u2009n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1,\u2009x2,\u2009...,\u2009xb (0\u2009\u2264\u2009xi\u2009<\u2009n), denoting the list of indices of happy boys. The third line conatins integer g (0\u2009\u2264\u2009g\u2009\u2264\u2009m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1,\u2009y2,\u2009... ,\u2009yg (0\u2009\u2264\u2009yj\u2009<\u2009m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.", "output_spec": "If Drazil can make all his friends become happy by this plan, print \"Yes\". Otherwise, print \"No\".", "sample_inputs": ["2 3\n0\n1 0", "2 4\n1 0\n1 2", "2 3\n1 0\n1 1"], "sample_outputs": ["Yes", "No", "Yes"], "notes": "NoteBy we define the remainder of integer division of i by k.In first sample case: On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment. "}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \\dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \\le n, m \\le 2 \\cdot 10^{5})$$$ \u2014 the number of dormitories and the number of letters. The second line contains a sequence $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^{10})$$$, where $$$a_i$$$ equals to the number of rooms in the $$$i$$$-th dormitory. The third line contains a sequence $$$b_1, b_2, \\dots, b_m$$$ $$$(1 \\le b_j \\le a_1 + a_2 + \\dots + a_n)$$$, where $$$b_j$$$ equals to the room number (among all rooms of all dormitories) for the $$$j$$$-th letter. All $$$b_j$$$ are given in increasing order.", "output_spec": "Print $$$m$$$ lines. For each letter print two integers $$$f$$$ and $$$k$$$ \u2014 the dormitory number $$$f$$$ $$$(1 \\le f \\le n)$$$ and the room number $$$k$$$ in this dormitory $$$(1 \\le k \\le a_f)$$$ to deliver the letter.", "sample_inputs": ["3 6\n10 15 12\n1 9 12 23 26 37", "2 3\n5 10000000000\n5 6 9999999999"], "sample_outputs": ["1 1\n1 9\n2 2\n2 13\n3 1\n3 12", "1 5\n2 1\n2 9999999994"], "notes": "NoteIn the first example letters should be delivered in the following order: the first letter in room $$$1$$$ of the first dormitory the second letter in room $$$9$$$ of the first dormitory the third letter in room $$$2$$$ of the second dormitory the fourth letter in room $$$13$$$ of the second dormitory the fifth letter in room $$$1$$$ of the third dormitory the sixth letter in room $$$12$$$ of the third dormitory "}, "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 = 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] \u306e 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}"}, {"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"} {"nl": {"description": "Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai\u2009<\u2009bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj\u2009<\u2009ai and bi\u2009<\u2009bj. Your task is simpler: find the number of events that are included in some other event.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i\u2009+\u20091 line contains two integers ai and bi (1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009109) \u2014 the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai\u2009\u2260\u2009aj,\u2009ai\u2009\u2260\u2009bj,\u2009bi\u2009\u2260\u2009aj,\u2009bi\u2009\u2260\u2009bj for all i, j (where i\u2009\u2260\u2009j). Events are given in arbitrary order.", "output_spec": "Print the only integer \u2014 the answer to the problem.", "sample_inputs": ["5\n1 10\n2 9\n3 8\n4 7\n5 6", "5\n1 100\n2 50\n51 99\n52 98\n10 60", "1\n1 1000000000"], "sample_outputs": ["4", "4", "0"], "notes": "NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third \u2014 in the second and the second \u2014 in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0."}, "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 { _ =>\n val l = in.next().split(' ').map(_.toInt)\n (l.head, l.last)\n }.sorted\n println(data.foldLeft((0, 0)) {\n case((maxEnd, sum), (_, end)) =>\n if (end < maxEnd)\n (maxEnd, sum + 1)\n else\n (end, sum)\n }._2)\n}"}], "negative_code": [], "src_uid": "dfb1479ffa17489095b6bf1921758f7e"} {"nl": {"description": "Let's denote the Manhattan distance between two points $$$p_1$$$ (with coordinates $$$(x_1, y_1)$$$) and $$$p_2$$$ (with coordinates $$$(x_2, y_2)$$$) as $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$$$. For example, the distance between two points with coordinates $$$(1, 3)$$$ and $$$(4, 2)$$$ is $$$|1 - 4| + |3 - 2| = 4$$$.You are given two points, $$$A$$$ and $$$B$$$. The point $$$A$$$ has coordinates $$$(0, 0)$$$, the point $$$B$$$ has coordinates $$$(x, y)$$$.Your goal is to find a point $$$C$$$ such that: both coordinates of $$$C$$$ are non-negative integers; $$$d(A, C) = \\dfrac{d(A, B)}{2}$$$ (without any rounding); $$$d(B, C) = \\dfrac{d(A, B)}{2}$$$ (without any rounding). Find any point $$$C$$$ that meets these constraints, or report that no such point exists.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 3000$$$) \u2014 the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$0 \\le x, y \\le 50$$$) \u2014 the coordinates of the point $$$B$$$.", "output_spec": "For each test case, print the answer on a separate line as follows: if it is impossible to find a point $$$C$$$ meeting the constraints, print \"-1 -1\" (without quotes); otherwise, print two non-negative integers not exceeding $$$10^6$$$ \u2014 the coordinates of point $$$C$$$ meeting the constraints. If there are multiple answers, print any of them. It can be shown that if any such point exists, it's possible to find a point with coordinates not exceeding $$$10^6$$$ that meets the constraints. ", "sample_inputs": ["10\n49 3\n2 50\n13 0\n0 41\n42 0\n0 36\n13 37\n42 16\n42 13\n0 0"], "sample_outputs": ["23 3\n1 25\n-1 -1\n-1 -1\n21 0\n0 18\n13 12\n25 4\n-1 -1\n0 0"], "notes": "NoteExplanations for some of the test cases from the example: In the first test case, the point $$$B$$$ has coordinates $$$(49, 3)$$$. If the point $$$C$$$ has coordinates $$$(23, 3)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|49 - 0| + |3 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|23 - 0| + |3 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|23 - 49| + |3 - 3| = 26$$$. In the second test case, the point $$$B$$$ has coordinates $$$(2, 50)$$$. If the point $$$C$$$ has coordinates $$$(1, 25)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|2 - 0| + |50 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|1 - 0| + |25 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|1 - 2| + |25 - 50| = 26$$$. In the third and the fourth test cases, it can be shown that no point with integer coordinates meets the constraints. In the fifth test case, the point $$$B$$$ has coordinates $$$(42, 0)$$$. If the point $$$C$$$ has coordinates $$$(21, 0)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|42 - 0| + |0 - 0| = 42$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|21 - 0| + |0 - 0| = 21$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|21 - 42| + |0 - 0| = 21$$$. "}, "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 maxn = 10010\n val mp = mutable.Map[Char, Int]()\n\n val t = 1//readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n for (i <- 1 to n) {\n val x = readInt()\n val y = readInt()\n if ((x + y)%2 == 1) {\n writer.println(\"-1 -1\")\n } else {\n writer.println(((x+1)/2).toInt + \" \" + ((y)/2).toInt)\n }\n }\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "f1d3032f1cb07ad6187a37c84376510d"} {"nl": {"description": " William has an array of $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \\le n \\le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.", "sample_inputs": ["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"], "sample_outputs": ["1\n0\n3\n-1\n2"], "notes": "NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$ "}, "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"}, {"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"}], "negative_code": [], "src_uid": "be51a3e4038bd9a3f6d4993b75a20d1c"} {"nl": {"description": "Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1,\u2009c2,\u2009...,\u2009cn and Pari has to tell Arya if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value for any positive integer x?Note, that means the remainder of x after dividing it by y.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n,\u2009 k\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the number of ancient integers and value k that is chosen by Pari. The second line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u20091\u2009000\u2009000).", "output_spec": "Print \"Yes\" (without quotes) if Arya has a winning strategy independent of value of x, or \"No\" (without quotes) otherwise.", "sample_inputs": ["4 5\n2 3 5 12", "2 7\n2 3"], "sample_outputs": ["Yes", "No"], "notes": "NoteIn the first sample, Arya can understand because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n\u2009-\u20091) appears exactly once in it. For example, [0,\u20092,\u20091] is a permutation of length 3 while both [0,\u20092,\u20092] and [1,\u20092,\u20093] is not.A permutation triple of permutations of length n (a,\u2009b,\u2009c) is called a Lucky Permutation Triple if and only if . The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai\u2009+\u2009bi by n and dividing ci by n are equal.Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "If no Lucky Permutation Triple of length n exists print -1. Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line \u2014 permutation b, the third \u2014 permutation c. If there are multiple solutions, print any of them.", "sample_inputs": ["5", "2"], "sample_outputs": ["1 4 3 2 0\n1 0 2 4 3\n2 4 0 1 3", "-1"], "notes": "NoteIn Sample 1, the permutation triple ([1,\u20094,\u20093,\u20092,\u20090],\u2009[1,\u20090,\u20092,\u20094,\u20093],\u2009[2,\u20094,\u20090,\u20091,\u20093]) is Lucky Permutation Triple, as following holds: ; ; ; ; . In Sample 2, you can easily notice that no lucky permutation triple exists."}, "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"}, {"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}"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$. The array is called 3SUM-closed if for all distinct indices $$$i$$$, $$$j$$$, $$$k$$$, the sum $$$a_i + a_j + a_k$$$ is an element of the array. More formally, $$$a$$$ is 3SUM-closed if for all integers $$$1 \\leq i < j < k \\leq n$$$, there exists some integer $$$1 \\leq l \\leq n$$$ such that $$$a_i + a_j + a_k = a_l$$$.Determine if $$$a$$$ is 3SUM-closed.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output \"YES\" (without quotes) if $$$a$$$ is 3SUM-closed and \"NO\" (without quotes) otherwise. You can output \"YES\" and \"NO\" in any case (for example, strings \"yEs\", \"yes\" and \"Yes\" will be recognized as a positive response).", "sample_inputs": ["4\n\n3\n\n-1 0 1\n\n5\n\n1 -2 -2 1 -3\n\n6\n\n0 0 0 0 0 0\n\n4\n\n-1 2 -3 4"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteIn the first test case, there is only one triple where $$$i=1$$$, $$$j=2$$$, $$$k=3$$$. In this case, $$$a_1 + a_2 + a_3 = 0$$$, which is an element of the array ($$$a_2 = 0$$$), so the array is 3SUM-closed.In the second test case, $$$a_1 + a_4 + a_5 = -1$$$, which is not an element of the array. Therefore, the array is not 3SUM-closed.In the third test case, $$$a_i + a_j + a_k = 0$$$ for all distinct $$$i$$$, $$$j$$$, $$$k$$$, and $$$0$$$ is an element of the array, so the array is 3SUM-closed."}, "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\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 tokenizer = new StringTokenizer(input.readLine())\r\n val A = ListBuffer.empty[Int]\r\n for (i <- 1 to n) A+= tokenizer.nextToken().toInt\r\n val B = A.toArray\r\n val C = A.toList\r\n var CC = C.filter(x => x != 0)\r\n if (CC.length >= 5) {\r\n output.println(\"NO\")\r\n }\r\n else {\r\n var c1 = true\r\n if (CC.length != n) {\r\n CC = 0 :: CC\r\n }\r\n for {j <- CC.indices; k <- CC.indices; l <- CC.indices\r\n if ((j\n case v =>\n val t = sums(v)\n \n degrees(t) -= 1\n sums(t) ^= v\n if(degrees(t) == 1)\n queue.enqueue(t)\n \n if(v <= t)\n pairs += ((v, t))\n else\n pairs += ((t, v))\n }\n \n println(pairs.size)\n for(pair <- pairs)\n println(s\"${pair._1} ${pair._2}\")\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"}], "negative_code": [], "src_uid": "14ad30e33bf8cad492e665b0a486008e"} {"nl": {"description": "Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price \u2014 their owners are ready to pay Bob if he buys their useless apparatus. Bob can \u00abbuy\u00bb any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai (\u2009-\u20091000\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 prices of the TV sets. ", "output_spec": "Output the only number \u2014 the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.", "sample_inputs": ["5 3\n-6 0 35 -2 4", "4 2\n7 0 0 -7"], "sample_outputs": ["8", "7"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "You have a large electronic screen which can display up to $$$998244353$$$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $$$7$$$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $$$10$$$ decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $$$1$$$, you have to turn on $$$2$$$ segments of the screen, and if you want to display $$$8$$$, all $$$7$$$ segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $$$n$$$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $$$n$$$ segments.Your program should be able to process $$$t$$$ different test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then the test cases follow, each of them is represented by a separate line containing one integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 the maximum number of segments that can be turned on in the corresponding testcase. It is guaranteed that the sum of $$$n$$$ over all test cases in the input does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the greatest integer that can be displayed by turning on no more than $$$n$$$ segments of the screen. Note that the answer may not fit in the standard $$$32$$$-bit or $$$64$$$-bit integral data type.", "sample_inputs": ["2\n3\n4"], "sample_outputs": ["7\n11"], "notes": null}, "positive_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 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"}, {"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"} {"nl": {"description": "You are given an integer $$$n$$$. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $$$7$$$.If there are multiple ways to do it, print any of them. If the given number is already divisible by $$$7$$$, leave it unchanged.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 990$$$) \u2014 the number of test cases. Then the test cases follow, each test case consists of one line containing one integer $$$n$$$ ($$$10 \\le n \\le 999$$$).", "output_spec": "For each test case, print one integer without any leading zeroes \u2014 the result of your changes (i.\u2009e. the integer that is divisible by $$$7$$$ and can be obtained by changing the minimum possible number of digits in $$$n$$$). If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $$$7$$$, just print it.", "sample_inputs": ["3\n42\n23\n377"], "sample_outputs": ["42\n28\n777"], "notes": "NoteIn the first test case of the example, $$$42$$$ is already divisible by $$$7$$$, so there's no need to change it.In the second test case of the example, there are multiple answers \u2014 $$$28$$$, $$$21$$$ or $$$63$$$.In the third test case of the example, other possible answers are $$$357$$$, $$$371$$$ and $$$378$$$. Note that you cannot print $$$077$$$ or $$$77$$$."}, "positive_code": [{"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}"}, {"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": "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"}], "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"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \\le i < j \\le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \\le a_i + a_j \\le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable: $$$i=1$$$ and $$$j=2$$$ ($$$4 \\le 5 + 1 \\le 7$$$); $$$i=1$$$ and $$$j=3$$$ ($$$4 \\le 5 + 2 \\le 7$$$). ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le l \\le r \\le 10^9$$$)\u00a0\u2014 the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the number of index pairs $$$(i, j)$$$ ($$$i < j$$$), such that $$$l \\le a_i + a_j \\le r$$$.", "sample_inputs": ["4\n3 4 7\n5 1 2\n5 5 8\n5 1 2 4 3\n4 100 1000\n1 1 1 1\n5 9 13\n2 5 5 1 1"], "sample_outputs": ["2\n7\n0\n1"], "notes": null}, "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n @annotation.tailrec\r\n private def binary(p: Int, q: Int, f: Int => Boolean): Int =\r\n if (p + 1 >= q) q\r\n else {\r\n val o = (p + q) / 2\r\n\r\n f(o) match {\r\n case true => binary(o, q, f)\r\n case false => binary(p, o, f)\r\n }\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, l, r) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val ans = (0 until n).foldLeft(0L) { case (count, i) =>\r\n val ai = an(i)\r\n\r\n val p = binary(i, n, an(_) + ai <= r)\r\n val q = binary(i, n, an(_) + ai <= l - 1)\r\n\r\n count + p - q\r\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 @annotation.tailrec\r\n private def binary(p: Int, q: Int, f: Int => Boolean): Int =\r\n if (p + 1 >= q) q\r\n else {\r\n val o = (p + q) / 2\r\n\r\n f(o) match {\r\n case true => binary(o, q, f)\r\n case false => binary(p, o, f)\r\n }\r\n }\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, l, r) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt).sorted\r\n\r\n val ans = (0 until n).foldLeft(0) { case (count, i) =>\r\n val ai = an(i)\r\n\r\n val p = binary(i, n, an(_) + ai <= r)\r\n val q = binary(i, n, an(_) + ai <= l - 1)\r\n\r\n count + p - q\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 val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val Array(n, l, r) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering[Int].reverse)\r\n\r\n def go(i: Int, count: Long): Long =\r\n if (i == n) count\r\n else {\r\n val ai = an(i)\r\n\r\n if (ai >= r) go(i + 1, count)\r\n else {\r\n val p = an.indexWhere(_ + ai <= r, i + 1)\r\n\r\n if (p == -1) go(i + 1, count)\r\n else {\r\n val q = an.lastIndexWhere(_ + ai >= l)\r\n\r\n if (q < p) count\r\n else go(i + 1, count + q - p + 1L)\r\n }\r\n }\r\n }\r\n\r\n val ans = go(0, 0L)\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 Array(n, l, r) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering[Int].reverse)\r\n\r\n def go(i: Int, count: Int): Int =\r\n if (i == n) count\r\n else {\r\n val ai = an(i)\r\n\r\n if (ai >= r) go(i + 1, count)\r\n else {\r\n val p = an.indexWhere(_ + ai <= r, i + 1)\r\n\r\n if (p == -1) go(i + 1, count)\r\n else {\r\n val q = an.lastIndexWhere(_ + ai >= l)\r\n\r\n if (q == -1 || q < p) count\r\n else go(i + 1, count + q - p + 1)\r\n }\r\n }\r\n }\r\n\r\n val ans = go(0, 0)\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 Array(n, l, r) = readLine().split(\" \").map(_.toInt)\r\n val an = readLine().split(\" \").map(_.toInt).sorted(Ordering[Int].reverse)\r\n\r\n def go(i: Int, count: Int): Int =\r\n if (i == n) count\r\n else {\r\n val ai = an(i)\r\n\r\n if (ai >= r) go(i + 1, count)\r\n else {\r\n val p = an.indexWhere(_ + ai <= r, i + 1)\r\n\r\n if (p == -1) count\r\n else {\r\n val q = an.lastIndexWhere(_ + ai >= l)\r\n\r\n if (q == -1 || q < p) count\r\n else go(i + 1, count + q - p + 1)\r\n }\r\n }\r\n }\r\n\r\n val ans = go(0, 0)\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "2f12b2bb23497119bb70ca0839991d68"} {"nl": {"description": "Let $$$f_{x} = c^{2x-6} \\cdot f_{x-1} \\cdot f_{x-2} \\cdot f_{x-3}$$$ for $$$x \\ge 4$$$.You have given integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$. Find $$$f_{n} \\bmod (10^{9}+7)$$$.", "input_spec": "The only line contains five integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$ ($$$4 \\le n \\le 10^{18}$$$, $$$1 \\le f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, $$$c \\le 10^{9}$$$).", "output_spec": "Print $$$f_{n} \\bmod (10^{9} + 7)$$$.", "sample_inputs": ["5 1 2 5 3", "17 97 41 37 11"], "sample_outputs": ["72900", "317451037"], "notes": "NoteIn the first example, $$$f_{4} = 90$$$, $$$f_{5} = 72900$$$.In the second example, $$$f_{17} \\approx 2.28 \\times 10^{29587}$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, f1, f2, f3, C = nl()\n\n val A = Array(\n Array[Long](1, 1, 1),\n Array[Long](1, 0, 0),\n Array[Long](0, 1, 0)\n )\n val B = power(A, N - 3, MOD - 1)(0)\n\n val A2 = Array(\n Array[Long](1, 1, 1, 1, 0),\n Array[Long](1, 0, 0, 0, 0),\n Array[Long](0, 1, 0, 0, 0),\n Array[Long](0, 0, 0, 1, 1),\n Array[Long](0, 0, 0, 0, 1)\n )\n\n val B2 = power(A2, N - 3, MOD - 1)(0)\n debug(B2)\n\n val v3 = B(0)\n val v2 = B(1)\n val v1 = B(2)\n val cc = B2(3) + B2(4)\n\n debug(s\"v1:$v1 v2:$v2 v3:$v3 cc:$cc\")\n\n val ans = powMod(f1, v1, MOD) *\n powMod(f2, v2, MOD) % MOD *\n powMod(f3, v3, MOD) % MOD *\n powMod(C * C % MOD, cc, MOD) % MOD\n\n out.println(ans)\n }\n\n def powMod(x: Long, n: Long, m: Long): Long = {\n def step(x: Long, n: Long, 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)\n }\n\n def power(a: Array[Array[Long]], n: Long, mod: Int): Array[Array[Long]] = {\n if (n == 1) a\n else {\n val q = n / 2\n val r = n % 2\n val b = power(mul(a, a, mod), q, mod)\n if (r == 1) mul(a, b, mod) else b\n }\n }\n\n def mul(a1: Array[Array[Long]], a2: Array[Array[Long]], mod: Int): Array[Array[Long]] = {\n assert(a1(0).length == a2.length)\n val r = a1.length\n val c = a2(0).length\n val len = a1(0).length\n val res = Array.ofDim[Long](r, c)\n REP(r) { i =>\n REP(c) { j =>\n var v = 0L\n REP(len) { k =>\n v += + a1(i)(k) * a2(k)(j)\n if (v > 7e18.toLong) v %= mod\n }\n res(i)(j) = if (v >= mod) v % mod else v\n }\n }\n res\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, f1, f2, f3, C = nl()\n\n val A = Array(\n Array[Long](1, 1, 1),\n Array[Long](1, 0, 0),\n Array[Long](0, 1, 0)\n )\n val B = power(A, N - 3, MOD)(0)\n\n val A2 = Array(\n Array[Long](1, 1, 1, 1, 0),\n Array[Long](1, 0, 0, 0, 0),\n Array[Long](0, 1, 0, 0, 0),\n Array[Long](0, 0, 0, 1, 1),\n Array[Long](0, 0, 0, 0, 1)\n )\n\n val B2 = power(A2, N - 3, MOD)(0)\n debug(B2)\n\n val v3 = B(0)\n val v2 = B(1)\n val v1 = B(2)\n val cc = B2(3) + B2(4)\n\n debug(s\"v1:$v1 v2:$v2 v3:$v3 cc:$cc\")\n\n val ans = powMod(f1, v1, MOD) *\n powMod(f2, v2, MOD) % MOD *\n powMod(f3, v3, MOD) % MOD *\n powMod(C * C % MOD, cc, MOD) % MOD\n\n out.println(ans)\n }\n\n def powMod(x: Long, n: Long, m: Long): Long = {\n def step(x: Long, n: Long, 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)\n }\n\n def power(a: Array[Array[Long]], n: Long, mod: Int): Array[Array[Long]] = {\n if (n == 1) a\n else {\n val q = n / 2\n val r = n % 2\n val b = power(mul(a, a, mod), q, mod)\n if (r == 1) mul(a, b, mod) else b\n }\n }\n\n def mul(a1: Array[Array[Long]], a2: Array[Array[Long]], mod: Int): Array[Array[Long]] = {\n assert(a1(0).length == a2.length)\n val r = a1.length\n val c = a2(0).length\n val len = a1(0).length\n val res = Array.ofDim[Long](r, c)\n REP(r) { i =>\n REP(c) { j =>\n var v = 0L\n REP(len) { k =>\n v += + a1(i)(k) * a2(k)(j)\n if (v > 7e18.toLong) v %= mod\n }\n res(i)(j) = if (v >= mod) v % mod else v\n }\n }\n res\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, f1, f2, f3, C = nl()\n\n val A = Array(\n Array[Long](1, 1, 1),\n Array[Long](1, 0, 0),\n Array[Long](0, 1, 0)\n )\n val B = power(A, N - 3, MOD)(0)\n\n val A2 = Array(\n Array[Long](1, 1, 1, 1, 0),\n Array[Long](1, 0, 0, 0, 0),\n Array[Long](0, 1, 0, 0, 0),\n Array[Long](0, 0, 0, 1, 1),\n Array[Long](0, 0, 0, 0, 1)\n )\n\n val B2 = power(A2, N - 3, MOD)(0)\n debug(B2)\n\n val v3 = B(0)\n val v2 = B(1)\n val v1 = B(2)\n val cc = B2(3) + B2(4)\n\n debug(s\"v1:$v1 v2:$v2 v3:$v3 cc:$cc\")\n\n val ans = powMod(f1, v1, MOD) *\n powMod(f2, v2, MOD) % MOD *\n powMod(f3, v3, MOD) % MOD *\n powMod(C * C % MOD, cc, MOD) % MOD\n\n out.println(ans)\n }\n\n def powMod(x: Long, n: Long, m: Long): Long = {\n def step(x: Long, n: Long, 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)\n }\n\n def power(a: Array[Array[Long]], n: Long, mod: Int): Array[Array[Long]] = {\n if (n == 1) a\n else {\n val q = n / 2\n val r = n % 2\n val b = power(mul(a, a, mod), q, mod)\n if (r == 1) mul(a, b, mod) else b\n }\n }\n\n def mul(a1: Array[Array[Long]], a2: Array[Array[Long]], mod: Int): Array[Array[Long]] = {\n assert(a1(0).length == a2.length)\n val r = a1.length\n val c = a2(0).length\n val len = a1(0).length\n val res = Array.ofDim[Long](r, c)\n REP(r) { i =>\n REP(c) { j =>\n var v = 0L\n REP(len) { k =>\n v += + a1(i)(k) * a2(k)(j)\n if (v > 7e18.toInt) v %= mod\n }\n res(i)(j) = if (v >= mod) v % mod else v\n }\n }\n res\n }\n}"}], "src_uid": "6fcd8713af5a108d590bc99da314cded"} {"nl": {"description": "Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of worm's forms. The second line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 lengths of worms of each form.", "output_spec": "Output 3 distinct integers i j k (1\u2009\u2264\u2009i,\u2009j,\u2009k\u2009\u2264\u2009n) \u2014 such indexes of worm's forms that ai\u2009=\u2009aj\u2009+\u2009ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj\u2009=\u2009ak.", "sample_inputs": ["5\n1 2 3 5 7", "5\n1 8 1 5 1"], "sample_outputs": ["3 2 1", "-1"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \\le f_i \\le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of friends. The second line of the input contains $$$n$$$ integers $$$f_1, f_2, \\dots, f_n$$$ ($$$0 \\le f_i \\le n$$$, $$$f_i \\ne i$$$, all $$$f_i \\ne 0$$$ are distinct), where $$$f_i$$$ is the either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \\le f_i \\le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$. It is also guaranteed that there is at least two values $$$f_i = 0$$$.", "output_spec": "Print $$$n$$$ integers $$$nf_1, nf_2, \\dots, nf_n$$$, where $$$nf_i$$$ should be equal to $$$f_i$$$ if $$$f_i \\ne 0$$$ or the number of friend whom the $$$i$$$-th friend wants to give the gift to. All values $$$nf_i$$$ should be distinct, $$$nf_i$$$ cannot be equal to $$$i$$$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. If there are several answers, you can print any.", "sample_inputs": ["5\n5 0 0 2 4", "7\n7 0 0 1 4 0 6", "7\n7 4 0 3 0 5 1", "5\n2 1 0 0 0"], "sample_outputs": ["5 3 1 2 4", "7 3 2 1 4 5 6", "7 4 2 3 6 5 1", "2 1 4 5 3"], "notes": null}, "positive_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n val to: Array[Int] = stdin.next().split(\" \").map(_.toInt)\n val from = new Array[Int](t)\n Range(0, t).filter(i => to(i) != 0).foreach(i => from(to(i) - 1) = i + 1)\n var startIndex = from.indexOf(0)\n var freeIndexes = Range(0, t).filter(i => from(i) == 0 && i != startIndex)\n var currentIndex = startIndex\n var i = 0\n while (i == 0 || (currentIndex != startIndex)) {\n if (to(currentIndex) == 0 && freeIndexes.nonEmpty) {\n to(currentIndex) = freeIndexes.head + 1\n freeIndexes = freeIndexes.tail\n }\n else if (to(currentIndex) == 0) {\n to(currentIndex) = startIndex + 1\n }\n currentIndex = to(currentIndex) - 1\n i += 1\n }\n println(to.mkString(\" \"))\n}"}], "negative_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n val arr = stdin.next().split(\" \").map(_.toInt)\n var res = arr.toSet\n val str = {\n var i = 1\n def loop(cand: Int): Stream[Int] =\n if (cand == 0) loop(t)\n else if (res.contains(cand)) loop(cand - 1)\n else if (cand == i) loop(cand - 1)\n else {\n res = res + cand\n i += 1\n cand #:: loop(cand - 1)\n }\n loop(t)\n }.iterator\n\n println(arr.map(x => if (x == 0) str.next() else x).mkString(\" \"))\n}"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n val arr = stdin.next().split(\" \").map(_.toInt)\n var set = arr.toSet\n\n val iter = {\n def loop(cand: Int): Stream[Int] = if (set.contains(cand)) loop(cand - 1) else cand #:: loop(cand - 1)\n loop(t).iterator\n }\n\n var res = arr.zipWithIndex.foldLeft((None: Option[Int], List.empty[Int])) {\n case ((x, list), (el, _)) if el != 0 => (x, el :: list)\n case ((None, list), (el, i)) => {\n val cand = iter.next()\n if (cand == i + 1)\n (Some(cand), iter.next() :: list)\n else\n (None, cand :: list)\n }\n case ((Some(x), list), (el, i)) => (None, x :: list)\n }\n\n val list = (res._1 ++ res._2).toList.reverse\n\n\n\n println(list.mkString(\" \"))\n}"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n val arr = stdin.next().split(\" \").map(_.toInt)\n val res = arr.toSet\n val str = {\n def loop(cand: Int): Stream[Int] = if (res.contains(cand)) loop(cand - 1) else cand #:: loop(cand - 1)\n loop(t)\n }.iterator\n\n println(arr.map(x => if (x == 0) str.next() else x).mkString(\" \"))\n}"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n\n val t = stdin.next().toInt\n val to: Array[Int] = stdin.next().split(\" \").map(_.toInt)\n val from = new Array[Int](t)\n Range(0, t).filter(i => to(i) != 0).foreach(i => from(to(i) - 1) = i + 1)\n var startIndex = from.find(_ == 0).get\n var freeIndexes = Range(0, t).filter(i => from(i) == 0 && i != startIndex)\n var currentIndex = to(startIndex) - 1\n var i = 0\n while (currentIndex != startIndex && i < t) {\n if (to(currentIndex) == 0 && freeIndexes.nonEmpty) {\n to(currentIndex) = freeIndexes.head + 1\n freeIndexes = freeIndexes.tail\n }\n else if (to(currentIndex) == 0) {\n to(currentIndex) = startIndex + 1\n }\n currentIndex = to(currentIndex) - 1\n i += 1\n }\n println(to.mkString(\" \"))\n}"}], "src_uid": "bef323e7c8651cc78c49db38e49ba53d"} {"nl": {"description": "zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task!", "input_spec": "The only line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20092\u00b7105) \u2014 the string given to zscoder. The string s consists of only lowercase English letters.", "output_spec": "Print the simple string s' \u2014 the string s after the minimal number of changes. If there are multiple solutions, you may output any of them. Note that the string s' should also consist of only lowercase English letters.", "sample_inputs": ["aab", "caaab", "zscoder"], "sample_outputs": ["bab", "cabab", "zscoder"], "notes": null}, "positive_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n val str = in.next().toCharArray\n (1 until str.length).foreach { i =>\n if (str(i) == str(i - 1))\n str(i) = List(str(i), 'a', 'b', 'c')\n .find(nch => nch != str(i - 1) && (i == str.length - 1 || nch != str(i + 1))).get\n }\n println(str.mkString(\"\"))\n}"}], "negative_code": [], "src_uid": "1f38c88f89786f118c65215d7df7bc9c"} {"nl": {"description": "Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, \"DINAMO BYTECITY\". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is \"DIN\", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is \"DIB\". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name \"DIB\", then no club for which the first option is chosen can have short name equal to \"DIN\". However, it is possible that some club have short name \"DIN\", where \"DI\" are the first two letters of the team's name, and \"N\" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. ", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of clubs in the league. Each of the next n lines contains two words\u00a0\u2014 the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.", "output_spec": "It it is not possible to choose short names and satisfy all constraints, print a single line \"NO\". Otherwise, in the first line print \"YES\". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them.", "sample_inputs": ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"], "sample_outputs": ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"], "notes": "NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different."}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\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 var m: Int = _\n\n val adj = Array.fill(3000)(ArrayBuffer[Int]())\n val matches = Array.fill(3000)(-1)\n val used = Array.fill(3000)(false)\n\n def dfs(v: Int): Boolean = {\n used(v) = true\n adj(v).exists { u =>\n val w = matches(u)\n if (w < 0 || (!used(w) && dfs(w))) {\n matches(u) = v\n matches(v) = u\n true\n } else {\n false\n }\n }\n }\n\n def main(args: Array[String]) {\n\n val n = readLine.toInt\n val opt = Array.fill(n) {\n val Array(first, second) = readLine.split(\" \")\n (first.take(3), first.take(2) + second.take(1))\n }\n\n val key = mutable.HashMap[String, ArrayBuffer[Int]]().withDefaultValue(ArrayBuffer[Int]())\n\n val n2i = mutable.HashMap[String, Int]()\n val i2n = Array.fill(3000)(\"\")\n\n m = n\n\n opt.zipWithIndex.foreach {\n case ((first, second), i) =>\n key.getOrElseUpdate(first, ArrayBuffer[Int]()).append(i)\n if (!n2i.contains(first)) {\n n2i.put(first, m)\n i2n(m) = first\n m += 1\n }\n if (!n2i.contains(second)) {\n n2i.put(second, m)\n i2n(m) = second\n m += 1\n }\n }\n\n key.foreach { case (_, array) =>\n if (array.size > 1) {\n array.foreach { i =>\n adj(i).append(n2i(opt(i)._2))\n adj(n2i(opt(i)._2)).append(i)\n }\n } else {\n val i = array.head\n adj(i).append(n2i(opt(i)._1))\n adj(i).append(n2i(opt(i)._2))\n adj(n2i(opt(i)._1)).append(i)\n adj(n2i(opt(i)._2)).append(i)\n }\n }\n\n var res = 0\n\n for (i <- 0 to n - 1) {\n if (matches(i) < 0) {\n for (j <- 0 to m - 1) used(j) = false\n if (dfs(i)) res += 1\n }\n }\n\n\n if (res == n) {\n println(\"YES\")\n matches.take(n).map(i2n(_)).foreach(println)\n } else {\n println(\"NO\")\n }\n\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "negative_code": [{"source_code": "import 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\n val n = readLine.toInt\n val opt = Array.fill(n) {\n val Array(first, second) = readLine.split(\" \")\n (first.take(3), first.take(2) + second.take(1))\n }\n val res = Array.fill[String](n)(\"\")\n\n val key = mutable.HashMap[String, ArrayBuffer[Int]]().withDefaultValue(ArrayBuffer[Int]())\n val name = mutable.HashSet[String]()\n\n opt.zipWithIndex.foreach { case ((first, _), i) =>\n key.getOrElseUpdate(first, ArrayBuffer[Int]()).append(i)\n }\n\n var valid = true\n key.filter(_._2.size > 1).foreach { case (_, array) =>\n if (valid) {\n array.foreach { i =>\n if (name.contains(opt(i)._2)) valid = false\n else {\n name.add(opt(i)._2)\n res(i) = opt(i)._2\n }\n }\n }\n }\n\n val single = key.filter(valid && _._2.size == 1).map(_._2.head).toList\n\n var dep = true\n while (single.filter(res(_)==\"\").nonEmpty && dep && valid) {\n single.filter(res(_)==\"\").foreach { i =>\n if (name.contains(opt(i)._1) && !name.contains(opt(i)._2)) {\n name.add(opt(i)._2)\n res(i) = opt(i)._2\n } else if (!name.contains(opt(i)._1) && name.contains(opt(i)._2)) {\n name.add(opt(i)._1)\n res(i) = opt(i)._1\n } else if (name.contains(opt(i)._1) && name.contains(opt(i)._2)) {\n valid = false\n } else {\n dep = false\n }\n }\n }\n\n for (i <- res.indices) {\n if (res(i) == \"\") res(i) = opt(i)._1\n }\n\n if (valid) {\n println(\"YES\")\n res.foreach(println)\n } else {\n println(\"NO\")\n }\n\n\n // Console.withOut(new java.io.BufferedOutputStream(Console.out))\n // println(res.mkString(\"\\n\"))\n // Console.flush\n }\n}"}], "src_uid": "733b36bfc2b72200281477af875f8efa"} {"nl": {"description": "Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student\u2019s laziness level is equal to their task\u2019s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task\u2019s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10\u2009007.", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of tasks. The next n lines contain exactly one integer number ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009100\u2009000)\u00a0\u2014 both the difficulty of the initial task and the laziness of the i-th students.", "output_spec": "Print the minimum total time to finish all tasks modulo 10\u2009007.", "sample_inputs": ["2\n1\n3"], "sample_outputs": ["6"], "notes": "NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3\u2009+\u20093\u2009=\u20096 time units."}, "positive_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(_.toLong).toArray.sorted\n println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 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).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"} {"nl": {"description": "City X consists of n vertical and n horizontal infinite roads, forming n\u2009\u00d7\u2009n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of vertical and horizontal roads in the city. Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi,\u2009vi (1\u2009\u2264\u2009hi,\u2009vi\u2009\u2264\u2009n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.", "output_spec": "In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.", "sample_inputs": ["2\n1 1\n1 2\n2 1\n2 2", "1\n1 1"], "sample_outputs": ["1 4", "1"], "notes": "NoteIn the sample the brigade acts like that: On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road; On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything; On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything; On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road. "}, "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 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}"}, {"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"} {"nl": {"description": "It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si,\u2009si\u2009+\u2009di,\u2009si\u2009+\u20092di,\u2009....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?", "input_spec": "First line contains an integer n \u2014 number of doctors (1\u2009\u2264\u2009n\u2009\u2264\u20091000). Next n lines contain two numbers si and di (1\u2009\u2264\u2009si,\u2009di\u2009\u2264\u20091000).", "output_spec": "Output a single integer \u2014 the minimum day at which Borya can visit the last doctor.", "sample_inputs": ["3\n2 2\n1 2\n2 2", "2\n10 1\n6 5"], "sample_outputs": ["4", "11"], "notes": "NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11."}, "positive_code": [{"source_code": "object _879A 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 doctors = io.read[Seq[(Int, Int)]]\n val ans = doctors.foldLeft(0) {\n case (day, (s, d)) =>\n Iterator.from(start = (day - s)/d max 0)\n .map(i => s + i*d)\n .find(_ > day).get\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 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 _879A 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 doctors = io.read[Seq[(Int, Int)]]\n val ans = doctors.foldLeft(0) {\n case (day, (s, d)) =>\n val i = (1 + (day - s)/d) max 0\n s + i*d\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 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": "d324617c86423d86cdcb839894e00e1a"} {"nl": {"description": "Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L\u2009-\u2009R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of columns. The next n lines contain the pairs of integers li and ri (1\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u2009500)\u00a0\u2014 the number of soldiers in the i-th column which start to march from the left or the right leg respectively.", "output_spec": "Print single integer k\u00a0\u2014 the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.", "sample_inputs": ["3\n5 6\n8 9\n10 3", "2\n6 5\n5 6", "6\n5 9\n1 3\n4 8\n4 5\n23 54\n12 32"], "sample_outputs": ["3", "1", "0"], "notes": "NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5\u2009+\u20098\u2009+\u200910\u2009=\u200923, and from the right leg\u00a0\u2014 6\u2009+\u20099\u2009+\u20093\u2009=\u200918. In this case the beauty of the parade will equal |23\u2009-\u200918|\u2009=\u20095.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5\u2009+\u20098\u2009+\u20093\u2009=\u200916, and who march from the right leg\u00a0\u2014 6\u2009+\u20099\u2009+\u200910\u2009=\u200925. In this case the beauty equals |16\u2009-\u200925|\u2009=\u20099.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9."}, "positive_code": [{"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"}, {"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": "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"}], "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"} {"nl": {"description": "Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \\cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, \"abc\" $$$\\cdot~2~=$$$ \"abcabc\", \"a\" $$$\\cdot~5~=$$$ \"aaaaa\".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \\cdot x = a$$$. For example, \"abababab\" is divisible by \"ab\", but is not divisible by \"ababab\" or \"aa\".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 2000$$$) \u2014 the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \\le |s|, |t| \\le 20$$$). Each character in each of these strings is either 'a' or 'b'.", "output_spec": "For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.", "sample_inputs": ["3\nbaba\nba\naa\naaa\naba\nab"], "sample_outputs": ["baba\naaaaaa\n-1"], "notes": "NoteIn the first test case, \"baba\" = \"baba\" $$$\\cdot~1~=$$$ \"ba\" $$$\\cdot~2$$$.In the second test case, \"aaaaaa\" = \"aa\" $$$\\cdot~3~=$$$ \"aaa\" $$$\\cdot~2$$$."}, "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 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}"}, {"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"} {"nl": {"description": "Gildong recently learned how to find the longest increasing subsequence (LIS) in $$$O(n\\log{n})$$$ time for a sequence of length $$$n$$$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length $$$n-1$$$, consisting of characters '<' and '>' only. The $$$i$$$-th (1-indexed) character is the comparison result between the $$$i$$$-th element and the $$$i+1$$$-st element of the sequence. If the $$$i$$$-th character of the string is '<', then the $$$i$$$-th element of the sequence is less than the $$$i+1$$$-st element. If the $$$i$$$-th character of the string is '>', then the $$$i$$$-th element of the sequence is greater than the $$$i+1$$$-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.", "input_spec": "Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is $$$n-1$$$. It is guaranteed that the sum of all $$$n$$$ in all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print two lines with $$$n$$$ integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between $$$1$$$ and $$$n$$$, inclusive, and should satisfy the comparison results. It can be shown that at least one answer always exists.", "sample_inputs": ["3\n3 <<\n7 >><>><\n5 >>><"], "sample_outputs": ["1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3"], "notes": "NoteIn the first case, $$$1$$$ $$$2$$$ $$$3$$$ is the only possible answer.In the second case, the shortest length of the LIS is $$$2$$$, and the longest length of the LIS is $$$3$$$. In the example of the maximum LIS sequence, $$$4$$$ '$$$3$$$' $$$1$$$ $$$7$$$ '$$$5$$$' $$$2$$$ '$$$6$$$' can be one of the possible LIS."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n\n def f1: Unit = {\n val Array(ns, s) = readLine.split(\" \")\n val sa = s.toArray\n val n = ns.toInt\n var t = n\n val la = Array.ofDim[Int](n)\n val lb = Array.ofDim[Int](n)\n var i = 0;\n while (i < n - 1) {\n var l = 0;\n var r = 0;\n var tmp = 0;\n if (sa(i) == '<') {\n l = i;\n tmp = i;\n while (tmp < n - 1 && sa(tmp) == '<') tmp += 1;\n r = tmp;\n while (i < tmp) {\n la(i + 1) = t - (tmp - i - 1)\n i += 1\n }\n t -= (r - l)\n } else {\n i += 1\n }\n }\n i = 0;\n la(0) = t\n t -= 1\n while (i < n - 1) {\n if (sa(i) == '>') {\n la(i + 1) = t\n t -= 1\n }\n i += 1\n }\n i = n - 2;\n t = n\n while (i >= 0) {\n var l = 0;\n var r = 0;\n var tmp = 0;\n if (sa(i) == '<') {\n lb(i + 1) = t\n t -= 1\n }\n i -= 1\n }\n i = n - 2\n lb(0) = t\n t -= 1\n while (i >= 0) {\n var l = 0;\n var r = 0;\n var tmp = 0;\n if (sa(i) == '>') {\n r = i;\n tmp = i;\n while (tmp >= 0 && sa(tmp) == '>') tmp -= 1;\n l = tmp;\n while (i > tmp) {\n lb(i + 1) = t - (i - tmp - 1)\n i -= 1\n }\n t -= (r - l)\n } else {\n i -= 1\n }\n }\n\n println(la.mkString(\" \"))\n println(lb.mkString(\" \"))\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val t = readInt\n (0 until t).foreach((x) => f1)\n }\n\n def f1: Unit = {\n val Array(ns, s) = readLine.split(\" \")\n val sa = s.toArray\n val n = ns.toInt\n var t = n\n val la = Array.ofDim[Int](n)\n var i = 0;\n while (i < n - 1) {\n var l = 0;\n var r = 0;\n var tmp = 0;\n if (sa(i) == '<') {\n l = i;\n tmp = i;\n while (tmp < n - 1 && sa(tmp) == '<') tmp += 1;\n r = tmp;\n while (i < tmp) {\n la(i + 1) = t - (tmp - i - 1)\n i += 1\n }\n t -= (r - l)\n } else {\n i += 1\n }\n }\n i = 0;\n la(0) = t\n t -= 1\n while (i < n - 1) {\n if (sa(i) == '>') {\n la(i + 1) = t\n t = t - 1\n }\n i += 1\n }\n println(la.mkString(\" \"))\n var a0 = la(0)\n i = 1\n var flag = true\n while (i < n - 1 && flag) {\n if (la(i - 1) < la(i) && la(i) > la(i + 1)) {\n for (j <- 0 to i - 2) la(j) = la(j + 1)\n la(i - 1) = la(i + 1)\n la(i + 1) = a0\n flag = false\n }\n i += 1\n }\n println(la.mkString(\" \"))\n }\n}\n"}], "src_uid": "fd0e9b90f36611c28fa8aca5b4e59ae9"} {"nl": {"description": "New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n\u2009-\u20091 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n\u2009-\u20091. Let's define d(u,\u2009v) as total length of roads on the path between city u and city v.As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1\u2009\u2264\u2009k\u2009\u2264\u20093) Santa will take charge of the warehouse in city ck.It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1,\u2009c2)\u2009+\u2009d(c2,\u2009c3)\u2009+\u2009d(c3,\u2009c1) dollars. Santas are too busy to find the best place, so they decided to choose c1,\u2009c2,\u2009c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.", "input_spec": "The first line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities in Tree World. Next n\u2009-\u20091 lines describe the roads. The i-th line of them (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) contains three space-separated integers ai, bi, li (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi, 1\u2009\u2264\u2009li\u2009\u2264\u2009103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009105) \u2014 the number of road length changes. Next q lines describe the length changes. The j-th line of them (1\u2009\u2264\u2009j\u2009\u2264\u2009q) contains two space-separated integers rj, wj (1\u2009\u2264\u2009rj\u2009\u2264\u2009n\u2009-\u20091, 1\u2009\u2264\u2009wj\u2009\u2264\u2009103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.", "output_spec": "Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["3\n2 3 5\n1 3 3\n5\n1 4\n2 2\n1 2\n2 1\n1 1", "6\n1 5 3\n5 3 2\n6 1 7\n1 4 4\n5 2 3\n5\n1 2\n2 1\n3 5\n4 1\n5 2"], "sample_outputs": ["14.0000000000\n12.0000000000\n8.0000000000\n6.0000000000\n4.0000000000", "19.6000000000\n18.6000000000\n16.6000000000\n13.6000000000\n12.6000000000"], "notes": "NoteConsider the first sample. There are 6 triples: (1,\u20092,\u20093),\u2009(1,\u20093,\u20092),\u2009(2,\u20091,\u20093),\u2009(2,\u20093,\u20091),\u2009(3,\u20091,\u20092),\u2009(3,\u20092,\u20091). Because n\u2009=\u20093, the cost needed to build the network is always d(1,\u20092)\u2009+\u2009d(2,\u20093)\u2009+\u2009d(3,\u20091) for all the triples. So, the expected cost equals to d(1,\u20092)\u2009+\u2009d(2,\u20093)\u2009+\u2009d(3,\u20091)."}, "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"}, {"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"}], "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"} {"nl": {"description": "Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \\ldots, p_m$$$, where $$$1 \\leq p_1 < p_2 < \\ldots < p_m \\leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\\max\\limits_{1 \\le i < m} \\left(p_{i + 1} - p_i\\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.", "input_spec": "The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\leq m \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.", "output_spec": "Output one integer\u00a0\u2014 the maximum width of a beautiful sequence.", "sample_inputs": ["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"], "sample_outputs": ["3", "4", "1", "1"], "notes": "NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\\{1, 2, 5\\}$$$ and $$$\\{1, 4, 5\\}$$$.In the second example the beautiful sequence with the maximum width is $$$\\{1, 5\\}$$$.In the third example there is exactly one beautiful sequence\u00a0\u2014 it is $$$\\{1, 2, 3, 4, 5\\}$$$.In the fourth example there is exactly one beautiful sequence\u00a0\u2014 it is $$$\\{1, 2\\}$$$."}, "positive_code": [{"source_code": "object C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n, m = nextInt\n val s, t = nextLine.map(_ - 'a')\n val Z = 'z' - 'a' + 1\n\n// val min, max = Array.fill(Z)(-1)\n val mins, maxs = Array.ofDim[Int](m)\n\n var prev = 0\n for (i <- 0 until m) {\n val c = t(i)\n while (s(prev) != c) prev += 1\n mins(i) = prev\n prev += 1\n// var k = if (min(c) == -1) 0 else min(c) + 1\n// while (s(k) != c) k += 1\n// min(c) = k\n// for (c <- 0 until Z) {\n// mins(c)(i) = min(c)\n// }\n }\n\n prev = n - 1\n for (i <- m - 1 to 0 by -1) {\n val c = t(i)\n while (s(prev) != c) prev -= 1\n maxs(i) = prev\n prev -= 1\n// var k = if (max(c) == -1) n - 1 else max(c) - 1\n// while (s(k) != c) k -= 1\n// max(c) = k\n// for (c <- 0 until Z) {\n// maxs(c)(i) = max(c)\n// }\n }\n\n var res = 0\n for (i <- 1 until m) {\n// val c = t(i - 1)\n// val c2 = t(i)\n val x = mins(i - 1)\n val y = maxs(i)\n// println(c + 'a', c2 + 'a', x, y)\n if (x >= 0 && y >= 0) {\n val d = y - x\n if (d > res) res = d\n }\n }\n\n out.println(res)\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 C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n, m = nextInt\n val s, t = nextLine.map(_ - 'a')\n val Z = 'z' - 'a' + 1\n\n val min, max = Array.fill(Z)(-1)\n val mins, maxs = Array.ofDim[Int](Z, m)\n\n for (i <- 0 until m) {\n val c = t(i)\n var k = if (min(c) == -1) 0 else min(c) + 1\n while (s(k) != c) k += 1\n min(c) = k\n for (c <- 0 until Z) {\n mins(c)(i) = min(c)\n }\n }\n\n for (i <- m - 1 to 0 by -1) {\n val c = t(i)\n var k = if (max(c) == -1) n - 1 else max(c) - 1\n while (s(k) != c) k -= 1\n max(c) = k\n for (c <- 0 until Z) {\n maxs(c)(i) = max(c)\n }\n }\n\n var res = 0\n for (i <- 1 until m) {\n val c = t(i - 1)\n val c2 = t(i)\n val x = mins(c)(i - 1)\n val y = maxs(c2)(i)\n// println(c + 'a', c2 + 'a', x, y)\n if (x >= 0 && y >= 0) {\n val d = y - x\n if (d > res) res = d\n }\n }\n\n out.println(res)\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": "17fff01f943ad467ceca5dce5b962169"} {"nl": {"description": "A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make. ", "input_spec": "The first line contains a single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of initial bouquets. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the number of flowers in each of the initial bouquets.", "output_spec": "Print the maximum number of large bouquets Vasya can make. ", "sample_inputs": ["5\n2 3 4 2 7", "6\n2 2 6 8 6 12", "3\n11 4 10"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11\u2009+\u20094\u2009+\u200910\u2009=\u200925."}, "positive_code": [{"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}"}, {"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 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 }"}], "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"} {"nl": {"description": "ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai\u2009\u2260\u2009i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after.ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1,\u2009A2,\u2009...,\u2009Ak (k\u2009>\u20091) such that for every 1\u2009\u2264\u2009i\u2009<\u2009k there is a road from town Ai to town Ai\u2009+\u20091 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns.Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing.Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.", "input_spec": "The first line of the input contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of towns in Udayland. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009i), ai denotes a road going from town i to town ai.", "output_spec": "Print a single integer\u00a0\u2014 the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109\u2009+\u20097.", "sample_inputs": ["3\n2 3 1", "4\n2 1 1 1", "5\n2 4 2 5 3"], "sample_outputs": ["6", "8", "28"], "notes": "NoteConsider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are , , initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1},\u2009{2},\u2009{3},\u2009{1,\u20092},\u2009{1,\u20093},\u2009{2,\u20093}. Note that the empty set is invalid because if no roads are flipped, then towns 1,\u20092,\u20093 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip.The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing."}, "positive_code": [{"source_code": "import 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 val Array(n) = readInts(1)\n val as = readInts(n).map(_ - 1)\n val MOD = 1000000007L\n val TWO = BigInt(2)\n\n val cycleSizes = ArrayBuffer.empty[Int]\n val gens = Array.fill(n){ -1 }\n var gen = 0\n\n def dfs(u: Int, gen0: Int): Unit = {\n gen += 1\n if (gens(u) >= gen0) cycleSizes += gen - gens(u)\n else if (gens(u) == -1) {\n gens(u) = gen\n dfs(as(u), gen0)\n }\n }\n\n for (u <- 0 until n) {\n if (gens(u) == -1) dfs(u, gen)\n }\n\n val nonCycleCount = n - cycleSizes.sum\n\n var res = TWO.modPow(nonCycleCount, MOD)\n\n for (cs <- cycleSizes) {\n res = res * (TWO.modPow(cs, MOD) - 2 + MOD) % MOD\n }\n\n println(res)\n}\n"}], "negative_code": [], "src_uid": "869f94e76703cde502bd908b476d970e"} {"nl": {"description": "You are given an undirected connected weighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges. Let's denote the length of the shortest path from vertex $$$1$$$ to vertex $$$i$$$ as $$$d_i$$$. You have to erase some edges of the graph so that at most $$$k$$$ edges remain. Let's call a vertex $$$i$$$ good if there still exists a path from $$$1$$$ to $$$i$$$ with length $$$d_i$$$ after erasing the edges.Your goal is to erase the edges in such a way that the number of good vertices is maximized.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$, $$$1 \\le m \\le 3 \\cdot 10^5$$$, $$$n - 1 \\le m$$$, $$$0 \\le k \\le m$$$) \u2014 the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$, $$$w$$$ ($$$1 \\le x, y \\le n$$$, $$$x \\ne y$$$, $$$1 \\le w \\le 10^9$$$), denoting an edge connecting vertices $$$x$$$ and $$$y$$$ and having weight $$$w$$$. The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).", "output_spec": "In the first line print $$$e$$$ \u2014 the number of edges that should remain in the graph ($$$0 \\le e \\le k$$$). In the second line print $$$e$$$ distinct integers from $$$1$$$ to $$$m$$$ \u2014 the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.", "sample_inputs": ["3 3 2\n1 2 1\n3 2 1\n1 3 3", "4 5 2\n4 1 8\n2 4 1\n2 1 3\n3 4 9\n3 1 5"], "sample_outputs": ["2\n1 2", "2\n3 2"], "notes": null}, "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 from, to, weight = Array.ofDim[Int](M)\n rep(M) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n weight(i) = ni()\n }\n\n val g = packWUGraph(N, from, to, weight)\n val edges = dijk(g, 0, K)\n out.println(edges.length)\n out.println(edges.map(_.id + 1).mkString(\" \"))\n }\n\n def dijk(g: WUGraph, start: Int, K: Int): ArrayBuffer[Edge] = {\n val d = Array.fill[Long](g.length)(Long.MaxValue / 2)\n case class Visit(node: Int, cost: Long, edge: Option[Edge]) extends Comparable[Visit] {\n override def compareTo(o: Visit): Int = java.lang.Long.compare(cost, o.cost)\n }\n val queue = new java.util.PriorityQueue[Visit]()\n queue.add(Visit(start, 0, None))\n\n val res = ArrayBuffer[Edge]()\n\n while(!queue.isEmpty) {\n val v = queue.poll()\n if (d(v.node) > v.cost) {\n d(v.node) = v.cost\n res ++= v.edge\n if (res.length == K) return res\n\n if (d(v.node) == v.cost) {\n rep(g(v.node).length) { i =>\n val e = g(v.node)(i)\n val next = v.cost + e.weight\n if (d(e.to) > next) {\n queue.add(Visit(e.to, next, Some(e)))\n }\n }\n }\n }\n }\n\n res\n }\n\n case class Edge(to: Int, weight: Int, id: Int)\n type WUGraph = Array[Array[Edge]]\n /**\n * uwi\u306e\u3071\u304f\u308a\n */\n def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Int]): WUGraph = {\n val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))\n rep(m) { i =>\n p(from(i)) -= 1\n g(from(i))(p(from(i))) = Edge(to(i), w(i), i)\n p(to(i)) -= 1\n g(to(i))(p(to(i))) = Edge(from(i), w(i), i)\n }\n g\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "0f181629eb10c5b2718f7a8f79043543"} {"nl": {"description": "You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings \"AB\" and \"BA\" (the substrings can go in any order).", "input_spec": "The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.", "output_spec": "Print \"YES\" (without the quotes), if string s contains two non-overlapping substrings \"AB\" and \"BA\", and \"NO\" otherwise.", "sample_inputs": ["ABA", "BACFAB", "AXBYBXA"], "sample_outputs": ["NO", "YES", "NO"], "notes": "NoteIn the first sample test, despite the fact that there are substrings \"AB\" and \"BA\", their occurrences overlap, so the answer is \"NO\".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring \"AB\" nor substring \"BA\"."}, "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 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}"}, {"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"} {"nl": {"description": "Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n\u2009-\u20091 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1,\u2009p2,\u2009...,\u2009pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.", "input_spec": "The first line contains three space-separated integers n, m and d (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u2009100000;\u00a00\u2009\u2264\u2009d\u2009\u2264\u2009n\u2009-\u20091). The second line contains m distinct space-separated integers p1,\u2009p2,\u2009...,\u2009pm (1\u2009\u2264\u2009pi\u2009\u2264\u2009n). Then n\u2009-\u20091 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.", "output_spec": "Print a single number \u2014 the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.", "sample_inputs": ["6 2 3\n1 2\n1 5\n2 3\n3 4\n4 5\n5 6"], "sample_outputs": ["3"], "notes": "NoteSample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5. "}, "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 \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\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"}, {"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 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 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}"}, {"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 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 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"}], "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"} {"nl": {"description": "Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \\dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \\leq i \\leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \\neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. ", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \\leq |s| \\leq 50$$$) consisting of lowercase English letters.", "output_spec": "For each test case, print the final string in a single line.", "sample_inputs": ["3\na\nbbbb\naz"], "sample_outputs": ["b\nazaz\nby"], "notes": "NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'."}, "positive_code": [{"source_code": "import java.util.Scanner\r\n\r\nobject Contest06YetAnotherStringScala {\r\n def playWord(word: String): String = {\r\n word.foldLeft((true,List[Char]()))((acc,a) => {\r\n (!acc._1,\r\n (if (acc._1) {// find next char\r\n if (a == 'a') 'b' else 'a'\r\n } else {\r\n if (a == 'z') 'y' else 'z'\r\n }) :: acc._2\r\n )\r\n })._2.mkString.reverse\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val scanner = new Scanner(System.in)\r\n val totalCases = scanner.nextInt\r\n for (i <- 0 to totalCases) {\r\n val word = scanner.nextLine()\r\n System.out.println(playWord(word))\r\n }\r\n scanner.close()\r\n }\r\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\r\n\r\nobject Contest06YetAnotherStringScala {\r\n def playWord(word: String): String = {\r\n word.foldLeft((true,List[Char]()))((acc,a) => {\r\n (!acc._1,\r\n (if (acc._1) {// find next char\r\n if (a == 'a') 'b' else 'a'\r\n } else {\r\n if (a == 'z') 'y' else 'z'\r\n }) :: acc._2\r\n )\r\n })._2.mkString.reverse\r\n }\r\n\r\n def main(args: Array[String]): Unit = {\r\n val scanner = new Scanner(System.in)\r\n val totalCases = scanner.nextInt\r\n for (i <- 0 until totalCases) {\r\n val word = scanner.nextLine()\r\n System.out.println(playWord(word))\r\n }\r\n scanner.close()\r\n }\r\n}"}], "src_uid": "c02357c4d959e300f970f66f9b3107eb"} {"nl": {"description": "Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \\dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \\le i \\le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\\dots$$$ $$$+ a_n \\ne 0$$$ and $$$a_1 \\cdot a_2 \\cdot$$$ $$$\\dots$$$ $$$\\cdot a_n \\ne 0$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-100 \\le a_i \\le 100$$$)\u00a0\u2014 elements of the array .", "output_spec": "For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.", "sample_inputs": ["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"], "sample_outputs": ["1\n2\n0\n2"], "notes": "NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "1ffb08fe61cdf90099c82162b8353b1f"} {"nl": {"description": "The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2\u2009\u00d7\u20092 square, such that from the four letters of this square you can make word \"face\". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.", "input_spec": "The first line contains two space-separated integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950) \u2014 the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.", "output_spec": "In the single line print the number of faces on the image.", "sample_inputs": ["4 4\nxxxx\nxfax\nxcex\nxxxx", "4 2\nxx\ncf\nae\nxx", "2 3\nfac\ncef", "1 4\nface"], "sample_outputs": ["1", "1", "2", "0"], "notes": "NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column: In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown: In the fourth sample the image has no faces on it."}, "positive_code": [{"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": "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"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "742e4e6ca047da5f5ebe5d854d6a2024"} {"nl": {"description": "You are given a binary string $$$s$$$ (recall that a string is binary if each character is either $$$0$$$ or $$$1$$$).Let $$$f(t)$$$ be the decimal representation of integer $$$t$$$ written in binary form (possibly with leading zeroes). For example $$$f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$$$ and $$$f(000100) = 4$$$.The substring $$$s_{l}, s_{l+1}, \\dots , s_{r}$$$ is good if $$$r - l + 1 = f(s_l \\dots s_r)$$$.For example string $$$s = 1011$$$ has $$$5$$$ good substrings: $$$s_1 \\dots s_1 = 1$$$, $$$s_3 \\dots s_3 = 1$$$, $$$s_4 \\dots s_4 = 1$$$, $$$s_1 \\dots s_2 = 10$$$ and $$$s_2 \\dots s_4 = 011$$$. Your task is to calculate the number of good substrings of string $$$s$$$.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of queries. The only line of each query contains string $$$s$$$ ($$$1 \\le |s| \\le 2 \\cdot 10^5$$$), consisting of only digits $$$0$$$ and $$$1$$$. It is guaranteed that $$$\\sum\\limits_{i=1}^{t} |s_i| \\le 2 \\cdot 10^5$$$.", "output_spec": "For each query print one integer \u2014 the number of good substrings of string $$$s$$$.", "sample_inputs": ["4\n0110\n0101\n00001000\n0001000"], "sample_outputs": ["4\n3\n4\n3"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u9023\u7d9a\u3057\u305f0\u306e\u500b\u6570\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}"}, {"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"} {"nl": {"description": "A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \\in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \\dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings \u2014 there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \\le x, y \\le n$$$ and $$$1 \\le a \\le |s_x|$$$ and $$$1 \\le b \\le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously?", "input_spec": "The first line contains single integer $$$Q$$$ ($$$1 \\le Q \\le 50$$$) \u2014 the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \\dots, s_n$$$ \u2014 one per line. It's guaranteed that $$$1 \\le |s_i| \\le 50$$$ and all strings constist of zeroes and/or ones.", "output_spec": "Print $$$Q$$$ integers \u2014 one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case.", "sample_inputs": ["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"], "sample_outputs": ["1\n2\n2\n2"], "notes": "NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \\text{0110}$$$, $$$s_2 = \\text{111111}$$$ and $$$s_3 = \\text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \\text{11011}$$$ and $$$s_2 = \\text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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 //\u0432\u0441\u0435 \u0434\u043b\u0438\u043d\u044b\n val lengths = rows.map{row => row.length }\n //\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0435\u0441\u0442\u044c \u043f\u0430\u0440\n val possiblePairs = (zeros / 2) + (ones / 2)\n // \u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043d\u0443\u0436\u043d\u043e \u043f\u0430\u0440\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"} {"nl": {"description": "An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $$$091$$$), a colon (ASCII code $$$058$$$), some (possibly zero) vertical line characters (ASCII code $$$124$$$), another colon, and a closing bracket (ASCII code $$$093$$$). The length of the accordion is the number of characters in it.For example, [::], [:||:] and [:|||:] are accordions having length $$$4$$$, $$$6$$$ and $$$7$$$. (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string $$$s$$$. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from $$$s$$$, and if so, what is the maximum possible length of the result?", "input_spec": "The only line contains one string $$$s$$$ ($$$1 \\le |s| \\le 500000$$$). It consists of lowercase Latin letters and characters [, ], : and |.", "output_spec": "If it is not possible to obtain an accordion by removing some characters from $$$s$$$, print $$$-1$$$. Otherwise print maximum possible length of the resulting accordion.", "sample_inputs": ["|[a:b:|]", "|]:[|:]"], "sample_outputs": ["4", "-1"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "You are given a tree (an undirected connected acyclic graph) consisting of $$$n$$$ vertices and $$$n - 1$$$ edges. A number is written on each edge, each number is either $$$0$$$ (let's call such edges $$$0$$$-edges) or $$$1$$$ (those are $$$1$$$-edges).Let's call an ordered pair of vertices $$$(x, y)$$$ ($$$x \\ne y$$$) valid if, while traversing the simple path from $$$x$$$ to $$$y$$$, we never go through a $$$0$$$-edge after going through a $$$1$$$-edge. Your task is to calculate the number of valid pairs in the tree.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 200000$$$) \u2014 the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each denoting an edge of the tree. Each edge is represented by three integers $$$x_i$$$, $$$y_i$$$ and $$$c_i$$$ ($$$1 \\le x_i, y_i \\le n$$$, $$$0 \\le c_i \\le 1$$$, $$$x_i \\ne y_i$$$) \u2014 the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree.", "output_spec": "Print one integer \u2014 the number of valid pairs of vertices.", "sample_inputs": ["7\n2 1 1\n3 2 0\n4 2 1\n5 2 0\n6 7 1\n7 2 1"], "sample_outputs": ["34"], "notes": "NoteThe picture corresponding to the first example:"}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n\n def solve(): Unit = {\n val N = ni()\n val uf0, uf1 = new UnionFind(N)\n val flg0, flg1 = Array.ofDim[Boolean](N)\n REP(N - 1) { i =>\n val v, u = ni() - 1\n val w = ni()\n (if (w == 0) uf0 else uf1).unite(v, u)\n val flg = if (w == 0) flg0 else flg1\n flg(v) = true\n flg(u) = true\n }\n\n var ans = 0L\n val used0, used1 = Array.ofDim[Boolean](N)\n REP(N) { i =>\n val id0 = uf0.find(i)\n val id1 = uf1.find(i)\n\n // 0-0\n if (!used0(id0)) {\n used0(id0) = true\n val n = uf0.cntNodes(id0)\n debug(s\"0-0 n:$n\")\n ans += n.toLong * (n - 1)\n }\n\n // 1-1\n if (!used1(id1)) {\n used1(id1) = true\n val n = uf1.cntNodes(id1)\n debug(s\"1-1 n:$n\")\n ans += n.toLong * (n - 1)\n }\n\n // 0-1\n if (flg0(i) && flg1(i)) {\n val n0 = uf0.cntNodes(id0)\n val n1 = uf1.cntNodes(id1)\n debug(s\"0-1 n0:$n0 n1:$n1\")\n ans += (n0 - 1).toLong * (n1 - 1)\n }\n }\n out.println(ans)\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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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 private def merge(node: Int, rt: Int): Int = {\n par(node) = rt\n rank(rt) += rank(node)\n rt\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(y1))\n merge(x1, y1)\n else\n merge(y1, x1)\n }\n }\n\n /**\n * x\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\n */\n def cntNodes(x: Int): Int = rank(find(x))\n }\n}"}], "negative_code": [], "src_uid": "13b9b9c47ae7e8cfdcaee50f9c187d84"} {"nl": {"description": "In the Isle of Guernsey there are n different types of coins. For each i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), coin of type i is worth ai cents. It is possible that ai\u2009=\u2009aj for some i and j (i\u2009\u2260\u2009j). Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1\u2009\u2264\u2009i\u2009\u2264\u2009q), the pair bi,\u2009ci tells Jessie that Bessie has a strictly greater number of coins of type bi than coins of type ci. It is known that all bi are distinct and all ci are distinct. Help Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), such that the number of coins Bessie has of type i is different in the two combinations. Since the answer can be very large, output it modulo 1000000007 (109\u2009+\u20097). If there are no possible combinations of coins totaling t cents that satisfy Bessie's conditions, output 0.", "input_spec": "The first line contains three space-separated integers, n,\u2009q and t (1\u2009\u2264\u2009n\u2009\u2264\u2009300;\u00a00\u2009\u2264\u2009q\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009t\u2009\u2264\u2009105). The second line contains n space separated integers, a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105). The next q lines each contain two distinct space-separated integers, bi and ci (1\u2009\u2264\u2009bi,\u2009ci\u2009\u2264\u2009n;\u00a0bi\u2009\u2260\u2009ci). It's guaranteed that all bi are distinct and all ci are distinct.", "output_spec": "A single integer, the number of valid coin combinations that Bessie could have, modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["4 2 17\n3 1 2 5\n4 2\n3 4", "3 2 6\n3 1 1\n1 2\n2 3", "3 2 10\n1 2 3\n1 2\n2 1"], "sample_outputs": ["3", "0", "0"], "notes": "NoteFor the first sample, the following 3 combinations give a total of 17 cents and satisfy the given conditions: {0\u00a0of\u00a0type\u00a01,\u20091\u00a0of\u00a0type\u00a02,\u20093\u00a0of\u00a0type\u00a03,\u20092\u00a0of\u00a0type\u00a04},\u2009{0,\u20090,\u20096,\u20091},\u2009{2,\u20090,\u20093,\u20091}.No other combinations exist. Note that even though 4 occurs in both bi and ci,\u2009 the problem conditions are still satisfied because all bi are distinct and all ci are distinct."}, "positive_code": [{"source_code": "import java.io._\nimport java.util._\nimport collection.mutable\n\nobject A extends App {\n val Array(n, q, t) = readLine split ' ' map (_.toInt)\n val a = readLine split ' ' map (_.toInt)\n val b = Array.fill(n)(-1)\n\n val less = Array.fill(n)(-1)\n val greater = Array.fill(n)(-1)\n for (i <- 1 to q) {\n val Array(u, v) = readLine split ' ' map (_.toInt - 1)\n less(u) = v\n greater(v) = u\n }\n\n var tt = t.toLong\n for (i <- 0 until n) {\n if (greater(i) == -1) {\n b(i) = a(i)\n var u = less(i)\n while (u != -1) {\n b(u) = b(greater(u)) + a(u)\n u = less(u)\n }\n }\n if (less(i) == -1) {\n var cnt = 0L\n var u = greater(i)\n while (u != -1) {\n cnt += 1\n tt -= cnt * a(u)\n u = greater(u)\n }\n }\n }\n\n if (tt < 0) {\n println(\"0\")\n System.exit(0)\n }\n for (i <- 0 until n)\n if (b(i) == -1) {\n println(\"0\")\n System.exit(0)\n }\n\n val ttt = tt.toInt\n val dp = Array.fill(ttt+1)(0)\n dp(0) = 1\n for (v <- b)\n for (i <- v to ttt)\n dp(i) = (dp(i) + dp(i-v)) % 1000000007\n println(dp(ttt))\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util._\nimport collection.mutable\n\nobject A extends App {\n val Array(n, q, t) = readLine split ' ' map (_.toInt)\n val a = readLine split ' ' map (_.toInt)\n val b = Array.fill(n)(-1)\n\n val less = Array.fill(n)(-1)\n val greater = Array.fill(n)(-1)\n for (i <- 1 to q) {\n val Array(u, v) = readLine split ' ' map (_.toInt - 1)\n less(u) = v\n greater(v) = u\n }\n\n var tt = t.toLong\n for (i <- 0 until n) {\n if (greater(i) == -1) {\n b(i) = a(i)\n var u = less(i)\n while (u != -1) {\n b(u) = b(greater(u)) + a(u)\n u = less(u)\n }\n }\n if (less(i) == -1) {\n var cnt = 0L\n var u = greater(i)\n while (u != -1) {\n cnt += 1\n tt -= cnt * a(u)\n u = greater(u)\n }\n }\n }\n\n if (tt < 0) {\n println(\"0\")\n System.exit(0)\n }\n for (i <- 0 until n)\n if (b(i) == -1) {\n println(\"0\")\n System.exit(0)\n }\n\n val ttt = tt.toInt\n val dp = Array.fill(ttt+1)(0)\n dp(0) = 1\n for (v <- b)\n for (i <- v to ttt)\n dp(i) += dp(i-v)\n println(dp(ttt))\n}\n"}, {"source_code": "import java.io._\nimport java.util._\nimport collection.mutable\n\nobject A extends App {\n val Array(n, q, t) = readLine split ' ' map (_.toInt)\n val a = readLine split ' ' map (_.toInt)\n val b = Array.fill(n)(-1)\n\n val less = Array.fill(n)(-1)\n val greater = Array.fill(n)(-1)\n for (i <- 1 to q) {\n val Array(u, v) = readLine split ' ' map (_.toInt - 1)\n less(u) = v\n greater(v) = u\n }\n\n var tt = t.toLong\n for (i <- 0 until n) {\n if (greater(i) == -1) {\n b(i) = a(i)\n var u = less(i)\n while (u != -1) {\n b(u) = b(greater(u)) + a(u)\n u = less(u)\n }\n }\n if (less(i) == -1) {\n var cnt = 0L\n var u = greater(i)\n while (u != -1) {\n cnt += 1\n tt -= cnt * a(u)\n u = greater(u)\n }\n }\n }\n\n if (tt < 0) {\n println(\"0\")\n System.exit(0)\n }\n for (i <- 0 until n)\n if (b(i) == -1) {\n println(\"0\")\n System.exit(0)\n }\n\n val ttt = tt.toInt\n val dp = Array.fill(ttt+1)(0L)\n dp(0) = 1\n for (v <- b)\n for (i <- v to ttt)\n dp(i) += dp(i-v)\n println(dp(ttt))\n}\n"}], "src_uid": "e077e9dd8d82bad597e6ecc51fb744c6"} {"nl": {"description": "Initially there was an array $$$a$$$ consisting of $$$n$$$ integers. Positions in it are numbered from $$$1$$$ to $$$n$$$.Exactly $$$q$$$ queries were performed on the array. During the $$$i$$$-th query some segment $$$(l_i, r_i)$$$ $$$(1 \\le l_i \\le r_i \\le n)$$$ was selected and values of elements on positions from $$$l_i$$$ to $$$r_i$$$ inclusive got changed to $$$i$$$. The order of the queries couldn't be changed and all $$$q$$$ queries were applied. It is also known that every position from $$$1$$$ to $$$n$$$ got covered by at least one segment.We could have offered you the problem about checking if some given array (consisting of $$$n$$$ integers with values from $$$1$$$ to $$$q$$$) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to $$$0$$$.Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.If there are multiple possible arrays then print any of them.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 2 \\cdot 10^5$$$) \u2014 the number of elements of the array and the number of queries perfomed on it. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le q$$$) \u2014 the resulting array. If element at some position $$$j$$$ is equal to $$$0$$$ then the value of element at this position can be any integer from $$$1$$$ to $$$q$$$.", "output_spec": "Print \"YES\" if the array $$$a$$$ can be obtained by performing $$$q$$$ queries. Segments $$$(l_i, r_i)$$$ $$$(1 \\le l_i \\le r_i \\le n)$$$ are chosen separately for each query. Every position from $$$1$$$ to $$$n$$$ should be covered by at least one segment. Otherwise print \"NO\". If some array can be obtained then print $$$n$$$ integers on the second line \u2014 the $$$i$$$-th number should be equal to the $$$i$$$-th element of the resulting array and should have value from $$$1$$$ to $$$q$$$. This array should be obtainable by performing exactly $$$q$$$ queries. If there are multiple possible arrays then print any of them.", "sample_inputs": ["4 3\n1 0 2 3", "3 10\n10 10 10", "5 6\n6 5 6 2 2", "3 5\n0 0 0"], "sample_outputs": ["YES\n1 2 2 3", "YES\n10 10 10", "NO", "YES\n5 4 2"], "notes": "NoteIn the first example you can also replace $$$0$$$ with $$$1$$$ but not with $$$3$$$.In the second example it doesn't really matter what segments to choose until query $$$10$$$ when the segment is $$$(1, 3)$$$.The third example showcases the fact that the order of queries can't be changed, you can't firstly set $$$(1, 3)$$$ to $$$6$$$ and after that change $$$(2, 2)$$$ to $$$5$$$. The segment of $$$5$$$ should be applied before segment of $$$6$$$.There is a lot of correct resulting arrays for the fourth example."}, "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\u304c\u3067\u3066\u304f\u308b\u304b\u30010\u304c\u3042\u308c\u3070\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 // \u5168\u90e80\u306e\u5834\u5408\u3082!hasQ\u304b\u3064zeros.length == 1 \u306a\u306e\u3067\u3053\u308c\u3067\u5927\u4e08\u592b\n if (!hasQ) {\n rep(zeros.length - 1)(i => fillZero(zeros(i)))\n fillZeroBy(zeros.last, Q) // \u4e00\u7b87\u6240Q\u3067\u57cb\u3081\u308b\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}"}, {"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"}], "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\u304c\u3067\u3066\u304f\u308b\u304b\u30010\u304c\u3042\u308c\u3070\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 // \u5168\u90e80\u306e\u5834\u5408\u3082!hasQ\u304b\u3064zeros.length == 1 \u306a\u306e\u3067\u3053\u308c\u3067\u5927\u4e08\u592b\n if (!hasQ) {\n rep(zeros.length - 1)(i => fillZero(zeros(i)))\n fillZeroBy(zeros.last, Q) // \u4e00\u7b87\u6240Q\u3067\u57cb\u3081\u308b\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"} {"nl": {"description": "Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.Let\u2019s assume that value gcd(a,\u2009b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1,\u2009p2,\u2009... ,\u2009pn is good if gcd(i,\u2009pi)\u2009>\u20091. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn\u2019t know any beautiful permutation. Your task is to help him to find at least one of them.", "input_spec": "The single line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u2009n).", "output_spec": "In a single line print either any beautiful permutation or -1, if such permutation doesn\u2019t exist. If there are multiple suitable permutations, you are allowed to print any of them.", "sample_inputs": ["4 2", "1 1"], "sample_outputs": ["2 4 3 1", "-1"], "notes": "NoteIn the first sample elements 4 and 3 are good because gcd(2,\u20094)\u2009=\u20092\u2009>\u20091 and gcd(3,\u20093)\u2009=\u20093\u2009>\u20091. Elements 2 and 1 are not good because gcd(1,\u20092)\u2009=\u20091 and gcd(4,\u20091)\u2009=\u20091. As there are exactly 2 good elements, the permutation is beautiful.The second sample has no beautiful permutations."}, "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\n if (k > n - 1)\n println(\"-1\")\n else if (k == n - 1)\n println((1 to n).mkString(\" \"))\n else\n println((n :: (2 to k + 1).toList ::: (1 :: (k + 2 until n).toList)).mkString(\" \"))\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\n if (k > n - 1)\n println(\"-1\")\n if (k == n - 1)\n println((1 to n).mkString(\" \"))\n else\n println((n :: (2 to k + 1).toList ::: (1 :: (k + 2 until n).toList)).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\n if (k > n - 1)\n println(\"-1\")\n else\n println(((2 to k).toList ::: (1 :: (k - 1 to 0 by -1).map(i => n - i).toList)).mkString(\" \"))\n}"}], "src_uid": "dc548fe1d8683b4b0ee4e0fa67638185"} {"nl": {"description": "You play your favourite game yet another time. You chose the character you didn't play before. It has $$$str$$$ points of strength and $$$int$$$ points of intelligence. Also, at start, the character has $$$exp$$$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $$$1$$$ or raise intelligence by $$$1$$$).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.", "input_spec": "The first line contains the single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. Next $$$T$$$ lines contain descriptions of queries \u2014 one per line. This line contains three integers $$$str$$$, $$$int$$$ and $$$exp$$$ ($$$1 \\le str, int \\le 10^8$$$, $$$0 \\le exp \\le 10^8$$$) \u2014 the initial strength and intelligence of the character and the number of free points, respectively.", "output_spec": "Print $$$T$$$ integers \u2014 one per query. For each query print the number of different character builds you can create.", "sample_inputs": ["4\n5 3 4\n2 1 0\n3 5 5\n4 10 6"], "sample_outputs": ["3\n1\n2\n0"], "notes": "NoteIn the first query there are only three appropriate character builds: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ and $$$(9, 3)$$$. All other builds are either too smart or don't use all free points.In the second query there is only one possible build: $$$(2, 1)$$$.In the third query there are two appropriate builds: $$$(7, 6)$$$, $$$(8, 5)$$$.In the fourth query all builds have too much brains."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 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"}, {"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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string $$$s$$$ of lowercase Latin letters. She considers a string $$$t$$$ as hidden in string $$$s$$$ if $$$t$$$ exists as a subsequence of $$$s$$$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $$$1$$$, $$$3$$$, and $$$5$$$, which form an arithmetic progression with a common difference of $$$2$$$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $$$S$$$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden $$$3$$$ times, b is hidden $$$2$$$ times, ab is hidden $$$6$$$ times, aa is hidden $$$3$$$ times, bb is hidden $$$1$$$ time, aab is hidden $$$2$$$ times, aaa is hidden $$$1$$$ time, abb is hidden $$$1$$$ time, aaab is hidden $$$1$$$ time, aabb is hidden $$$1$$$ time, and aaabb is hidden $$$1$$$ time. The number of occurrences of the secret message is $$$6$$$.", "input_spec": "The first line contains a string $$$s$$$ of lowercase Latin letters ($$$1 \\le |s| \\le 10^5$$$) \u2014 the text that Bessie intercepted.", "output_spec": "Output a single integer \u00a0\u2014 the number of occurrences of the secret message.", "sample_inputs": ["aaabb", "usaco", "lol"], "sample_outputs": ["6", "1", "2"], "notes": "NoteIn the first example, these are all the hidden strings and their indice sets: a occurs at $$$(1)$$$, $$$(2)$$$, $$$(3)$$$ b occurs at $$$(4)$$$, $$$(5)$$$ ab occurs at $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,4)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$ aa occurs at $$$(1,2)$$$, $$$(1,3)$$$, $$$(2,3)$$$ bb occurs at $$$(4,5)$$$ aab occurs at $$$(1,3,5)$$$, $$$(2,3,4)$$$ aaa occurs at $$$(1,2,3)$$$ abb occurs at $$$(3,4,5)$$$ aaab occurs at $$$(1,2,3,4)$$$ aabb occurs at $$$(2,3,4,5)$$$ aaabb occurs at $$$(1,2,3,4,5)$$$ Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer mi (1\u2009\u2264\u2009mi\u2009\u2264\u2009100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers ai,\u20091,\u2009ai,\u20092,\u2009...,\u2009ai,\u2009mi (1\u2009\u2264\u2009ai,\u2009k\u2009\u2264\u2009100) \u2014 the numbers on the i-th player's card. The numbers in the lines are separated by single spaces. It is guaranteed that all the numbers on each card are distinct.", "output_spec": "Print n lines, the i-th line must contain word \"YES\" (without the quotes), if the i-th player can win, and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["3\n1 1\n3 2 4 1\n2 10 11", "2\n1 1\n1 1"], "sample_outputs": ["YES\nNO\nYES", "NO\nNO"], "notes": null}, "positive_code": [{"source_code": "object Probb{\n def main(args:Array[String]){\n var n=readInt()\n var list=new Array[Set[Int]](n)\n var listans=new Array[String](n)\n for(i<-0 until n){\n var buff=readLine.split(' ').map(x=>x.toInt)\n list(i)=buff.slice(1,buff(0)+1).toSet\n }\n for(i<-0 until n){\n for(j<-0 until n){\n if(i!=j){\n if(list(i) subsetOf list(j)){\n listans(j)=\"NO\"\n } \n }\n }\n }\n for(i<-0 until n){\n if(listans(i)!=null)\n println(\"NO\")\n else\n println(\"YES\")\n }\n }\n}"}], "negative_code": [{"source_code": "object Probb{\n def main(args:Array[String]){\n var n=readInt()\n var list=new Array[Set[Int]](n)\n var listans=new Array[String](n)\n for(i<-0 until n){\n var buff=readLine.split(' ').map(x=>x.toInt)\n list(i)=buff.slice(1,buff(0)+1).toSet\n }\n for(i<-0 until n){\n for(j<-0 until n){\n if(i!=j){\n if(list(i) subsetOf list(j)){\n listans(j)=\"NO\"\n } \n }\n }\n }\n for(i<-0 until n){\n if(listans(i)!=null)\n println(\"No\")\n else\n println(\"Yes\")\n }\n }\n}"}], "src_uid": "90a47422f7ae53beb0a817422d760c6e"} {"nl": {"description": "Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second \u2014 from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.", "input_spec": "The first line of the input file contains integers n and x0 (1\u2009\u2264\u2009n\u2009\u2264\u2009100; 0\u2009\u2264\u2009x0\u2009\u2264\u20091000). The following n lines contain pairs of integers ai,\u2009bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000; ai\u2009\u2260\u2009bi).", "output_spec": "Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.", "sample_inputs": ["3 3\n0 7\n14 2\n4 6"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or \u2009-\u20091 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: .Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?", "input_spec": "The only line of the input contains a single integer k (0\u2009\u2264\u2009k\u2009\u2264\u20099).", "output_spec": "Print 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to '\u2009*\u2009' if the j-th coordinate of the i-th vector is equal to \u2009-\u20091, and must be equal to '\u2009+\u2009' if it's equal to \u2009+\u20091. It's guaranteed that the answer always exists. If there are many correct answers, print any.", "sample_inputs": ["2"], "sample_outputs": ["++**\n+*+*\n++++\n+**+"], "notes": "NoteConsider all scalar products in example: Vectors 1 and 2: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009-\u20091)\u2009=\u20090 Vectors 1 and 3: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 1 and 4: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 2 and 3: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 2 and 4: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 3 and 4: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 "}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "4e25d49e8a50dacc1cfcc9413ee83db6"} {"nl": {"description": "The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0\u2009<\u2009r2\u2009<\u2009r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.The Olympic jury decided that r1 will take one of possible values of x1,\u2009x2,\u2009...,\u2009xn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1,\u2009y2,\u2009...,\u2009ym, and p2 will take a value from list z1,\u2009z2,\u2009...,\u2009zk.According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal , where A,\u2009B are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.", "input_spec": "The first input line contains an integer n and a sequence of integers x1,\u2009x2,\u2009...,\u2009xn. The second input line contains an integer m and a sequence of integers y1,\u2009y2,\u2009...,\u2009ym. The third input line contains an integer k and a sequence of integers z1,\u2009z2,\u2009...,\u2009zk. The last line contains two integers A and B. All numbers given in the input are positive and do not exceed 5000. Each of the three sequences contains distinct numbers. The numbers in the lines are separated by spaces.", "output_spec": "Print a single real number \u2014 the sought value r2 with absolute or relative error of at most 10\u2009-\u20096. It is guaranteed that the solution that meets the problem requirements exists.", "sample_inputs": ["3 1 2 3\n1 2\n3 3 2 1\n1 2", "4 2 3 6 4\n2 1 2\n3 10 6 8\n2 1"], "sample_outputs": ["2.683281573000", "2.267786838055"], "notes": "NoteIn the first sample the jury should choose the following values: r1\u2009=\u20093, p1\u2009=\u20092, p2\u2009=\u20091."}, "positive_code": [{"source_code": "object Main { \n def rins(rout: Float, p1: Float, p2: Float, a: Float, b: Float): Float = {\n val den = p2 * a + p1 * b\n rout * rout * p1 * b / den\n }\n \n def main(args: Array[String]) {\n val n :: xs = readLine().split(\" \").map(_.toInt).toList\n val m :: ys = readLine().split(\" \").map(_.toInt).toList\n val k :: zs = readLine().split(\" \").map(_.toInt).toList\n val Array(a, b) = readLine().split(\" \").map(_.toInt)\n val r = rins(xs.max.toFloat, ys.max.toFloat, zs.min.toFloat, a.toFloat, b.toFloat)\n println(math.sqrt(r))\n }\n}"}], "negative_code": [], "src_uid": "18b1814234b05bae56ea4446506b543b"} {"nl": {"description": "You are given a string, consisting of lowercase Latin letters.A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string \"abaca\" contains ugly pairs at positions $$$(1, 2)$$$ \u2014 \"ab\" and $$$(2, 3)$$$ \u2014 \"ba\". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.If there are multiple answers, print any of them.You also have to answer $$$T$$$ separate queries.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. Each of the next $$$T$$$ lines contains string $$$s$$$ $$$(1 \\le |s| \\le 100)$$$ \u2014 the string for the next query. It is guaranteed that it contains only lowercase Latin letters. Note that in hacks you have to set $$$T = 1$$$.", "output_spec": "Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th query. If the answer for the $$$i$$$-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same. If there are multiple answers, print any of them. Otherwise print \"No answer\" for that query.", "sample_inputs": ["4\nabcd\ngg\ncodeforces\nabaca"], "sample_outputs": ["cadb\ngg\ncodfoerces\nNo answer"], "notes": "NoteIn the first example answer \"bdac\" is also correct.The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.There are lots of valid answers for the third example."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "negative_code": [], "src_uid": "d62d0a9d827444a671029407f6a4ad39"} {"nl": {"description": "Given a string s, process q queries, each having one of the following forms: 1\u2009i\u2009c \u2014 Change the i-th character in the string to c. 2\u2009l\u2009r\u2009y \u2014 Consider the substring of s starting at position l and ending at position r. Output the number of times y occurs as a substring in it. ", "input_spec": "The first line of the input contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105) of lowercase English letters. The second line contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009105) \u00a0\u2014 the number of queries to process. The next q lines describe the queries and may have one of the following forms: 1\u2009i\u2009c (1\u2009\u2264\u2009i\u2009\u2264\u2009|s|) 2\u2009l\u2009r\u2009y (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009|s|) c is a lowercase English letter and y is a non-empty string consisting of only lowercase English letters. The sum of |y| over all queries of second type is at most 105. It is guaranteed that there is at least one query of second type. All strings are 1-indexed. |s| is the length of the string s.", "output_spec": "For each query of type 2, output the required answer in a separate line.", "sample_inputs": ["ababababa\n3\n2 1 7 aba\n1 5 c\n2 1 7 aba", "abcdcbc\n5\n2 1 7 bc\n1 4 b\n2 4 7 bc\n1 2 a\n2 1 4 aa"], "sample_outputs": ["3\n1", "2\n2\n1"], "notes": "NoteConsider the first sample case. Initially, the string aba occurs 3 times in the range [1,\u20097]. Note that two occurrences may overlap. After the update, the string becomes ababcbaba and now aba occurs only once in the range [1,\u20097]."}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i.\u2009e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ lines describing the test cases follow. The $$$i$$$-th of these lines contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) \u2014 the goal of the $$$i$$$-th test case.", "output_spec": "For each test case, print one integer \u2014 the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$ for the corresponding test case.", "sample_inputs": ["4\n\n1\n\n3\n\n4\n\n12"], "sample_outputs": ["2\n1\n2\n4"], "notes": null}, "positive_code": [{"source_code": "//scala ACM\u6a21\u5f0f\u8bfb\u5165\u8bfb\u51fa\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": "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\u6a21\u5f0f\u8bfb\u5165\u8bfb\u51fa\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\u6a21\u5f0f\u8bfb\u5165\u8bfb\u51fa\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"} {"nl": {"description": "There are $$$n$$$ students numerated from $$$1$$$ to $$$n$$$. The level of the $$$i$$$-th student is $$$a_i$$$. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than $$$x$$$.For example, if $$$x = 4$$$, then the group with levels $$$[1, 10, 8, 4, 4]$$$ is stable (because $$$4 - 1 \\le x$$$, $$$4 - 4 \\le x$$$, $$$8 - 4 \\le x$$$, $$$10 - 8 \\le x$$$), while the group with levels $$$[2, 10, 10, 7]$$$ is not stable ($$$7 - 2 = 5 > x$$$).Apart from the $$$n$$$ given students, teachers can invite at most $$$k$$$ additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).For example, if there are two students with levels $$$1$$$ and $$$5$$$; $$$x = 2$$$; and $$$k \\ge 1$$$, then you can invite a new student with level $$$3$$$ and put all the students in one stable group.", "input_spec": "The first line contains three integers $$$n$$$, $$$k$$$, $$$x$$$ ($$$1 \\le n \\le 200\\,000$$$, $$$0 \\le k \\le 10^{18}$$$, $$$1 \\le x \\le 10^{18}$$$)\u00a0\u2014 the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^{18}$$$)\u00a0\u2014 the students levels.", "output_spec": "In the only line print a single integer: the minimum number of stable groups you can split the students into.", "sample_inputs": ["8 2 3\n1 1 5 8 12 13 20 22", "13 0 37\n20 20 80 70 70 70 420 5 1 5 1 60 90"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first example you can invite two students with levels $$$2$$$ and $$$11$$$. Then you can split the students into two stable groups: $$$[1, 1, 2, 5, 8, 11, 12, 13]$$$, $$$[20, 22]$$$. In the second example you are not allowed to invite new students, so you need $$$3$$$ groups: $$$[1, 1, 5, 5, 20, 20]$$$ $$$[60, 70, 70, 70, 80, 90]$$$ $$$[420]$$$ "}, "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val Array(_, k, x) = readLine().split(\" \").map(_.toLong)\r\n val an = readLine().split(\" \").map(_.toLong).sorted\r\n val n = an.length\r\n\r\n val indices = for {\r\n i <- 0 until (n - 1) if an(i + 1) > x + an(i)\r\n } yield i\r\n val weights = indices.map(i => (an(i + 1) - an(i) + x - 1) / x - 1).sorted\r\n\r\n @annotation.tailrec\r\n def go(k: Long, weights: Seq[Long]): Long =\r\n weights match {\r\n case weight +: weights if k - weight >= 0 => go(k - weight, weights)\r\n case _ => weights.length + 1\r\n }\r\n\r\n val ans = go(k, weights)\r\n\r\n println(ans)\r\n}\r\n"}], "negative_code": [], "src_uid": "c6c07ef23cf2def9f99cbfb6076c9810"} {"nl": {"description": "XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $$$n$$$ booths, arranged in a circle. The booths are numbered $$$1$$$ through $$$n$$$ clockwise with $$$n$$$ being adjacent to $$$1$$$. The $$$i$$$-th booths sells some candies for the price of $$$a_i$$$ burles per item. Each booth has an unlimited supply of candies.Polycarp has decided to spend at most $$$T$$$ burles at the fair. However, he has some plan in mind for his path across the booths: at first, he visits booth number $$$1$$$; if he has enough burles to buy exactly one candy from the current booth, then he buys it immediately; then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not). Polycarp's money is finite, thus the process will end once he can no longer buy candy at any booth.Calculate the number of candies Polycarp will buy.", "input_spec": "The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le T \\le 10^{18}$$$) \u2014 the number of booths at the fair and the initial amount of burles Polycarp has. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the price of the single candy at booth number $$$i$$$.", "output_spec": "Print a single integer \u2014 the total number of candies Polycarp will buy.", "sample_inputs": ["3 38\n5 2 5", "5 21\n2 4 100 2 6"], "sample_outputs": ["10", "6"], "notes": "NoteLet's consider the first example. Here are Polycarp's moves until he runs out of money: Booth $$$1$$$, buys candy for $$$5$$$, $$$T = 33$$$; Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 31$$$; Booth $$$3$$$, buys candy for $$$5$$$, $$$T = 26$$$; Booth $$$1$$$, buys candy for $$$5$$$, $$$T = 21$$$; Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 19$$$; Booth $$$3$$$, buys candy for $$$5$$$, $$$T = 14$$$; Booth $$$1$$$, buys candy for $$$5$$$, $$$T = 9$$$; Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 7$$$; Booth $$$3$$$, buys candy for $$$5$$$, $$$T = 2$$$; Booth $$$1$$$, buys no candy, not enough money; Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 0$$$. No candy can be bought later. The total number of candies bought is $$$10$$$.In the second example he has $$$1$$$ burle left at the end of his path, no candy can be bought with this amount."}, "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 var T = nl()\n val A = na(N)\n val flag = Array.ofDim[Boolean](N)\n\n var S = sumL(A)\n var c = N\n var ans = 0L\n while(c > 0) {\n val x = T / S\n ans += x * c\n T -= x * S\n\n rep(N) { i =>\n if (!flag(i) && A(i) <= T) {\n T -= A(i)\n ans += 1\n } else if (!flag(i)){\n flag(i) = true\n c -= 1\n S -= A(i)\n }\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}"}], "negative_code": [], "src_uid": "92db85bb3880b9d11f93cacd566ecda7"} {"nl": {"description": "It's a walking tour day in SIS.Winter, so $$$t$$$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters \"A\" and \"P\": \"A\" corresponds to an angry student \"P\" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $$$i$$$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $$$i+1$$$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.", "input_spec": "The first line contains a single integer $$$t$$$\u00a0\u2014 the number of groups of students ($$$1 \\le t \\le 100$$$). The following $$$2t$$$ lines contain descriptions of groups of students. The description of the group starts with an integer $$$k_i$$$ ($$$1 \\le k_i \\le 100$$$)\u00a0\u2014 the number of students in the group, followed by a string $$$s_i$$$, consisting of $$$k_i$$$ letters \"A\" and \"P\", which describes the $$$i$$$-th group of students.", "output_spec": "For every group output single integer\u00a0\u2014 the last moment a student becomes angry.", "sample_inputs": ["1\n4\nPPAP", "3\n12\nAPPAPPPAPPPP\n3\nAAP\n3\nPPA"], "sample_outputs": ["1", "4\n1\n0"], "notes": "NoteIn the first test, after $$$1$$$ minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after $$$1$$$ minute\u00a0\u2014 AAPAAPPAAPPP after $$$2$$$ minutes\u00a0\u2014 AAAAAAPAAAPP after $$$3$$$ minutes\u00a0\u2014 AAAAAAAAAAAP after $$$4$$$ minutes all $$$12$$$ students are angry In the second group after $$$1$$$ minute, all students are angry."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject AngryStudents extends App {\n\n val tests = StdIn.readLine().toInt\n\n for (i <- 1 to tests) {\n val k = StdIn.readLine().toInt\n val s = StdIn.readLine().toCharArray\n\n if (i == tests) {\n print(impl(s, k))\n } else {\n println(impl(s, k))\n }\n }\n\n def impl(students: Array[Char], len: Int): Int = {\n var time = 0\n var canChange = true\n var changedThisMinute = false\n\n while (canChange) {\n changedThisMinute = false\n for (i <- len - 1 to 1 by -1) {\n if ((i - 1) >= 0 && students(i - 1) == 'A' && students(i) == 'P') {\n students(i) = 'A'\n changedThisMinute = true\n }\n }\n if (!changedThisMinute) {\n canChange = false\n }\n\n if (canChange) {\n time += 1\n }\n }\n\n time\n }\n}\n"}], "negative_code": [], "src_uid": "1539fc8ef4f4cdcd1e14faf4f1b4ee8b"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. Find the maximum value of $$$max(a_l, a_{l + 1}, \\ldots, a_r) \\cdot min(a_l, a_{l + 1}, \\ldots, a_r)$$$ over all pairs $$$(l, r)$$$ of integers for which $$$1 \\le l < r \\le n$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$) \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer \u00a0\u2014 the maximum possible value of the product from the statement.", "sample_inputs": ["4\n3\n2 4 3\n4\n3 2 3 1\n2\n69 69\n6\n719313 273225 402638 473783 804745 323328"], "sample_outputs": ["12\n6\n4761\n381274500335"], "notes": "NoteLet $$$f(l, r) = max(a_l, a_{l + 1}, \\ldots, a_r) \\cdot min(a_l, a_{l + 1}, \\ldots, a_r)$$$.In the first test case, $$$f(1, 2) = max(a_1, a_2) \\cdot min(a_1, a_2) = max(2, 4) \\cdot min(2, 4) = 4 \\cdot 2 = 8$$$. $$$f(1, 3) = max(a_1, a_2, a_3) \\cdot min(a_1, a_2, a_3) = max(2, 4, 3) \\cdot min(2, 4, 3) = 4 \\cdot 2 = 8$$$. $$$f(2, 3) = max(a_2, a_3) \\cdot min(a_2, a_3) = max(4, 3) \\cdot min(4, 3) = 4 \\cdot 3 = 12$$$. So the maximum is $$$f(2, 3) = 12$$$.In the second test case, the maximum is $$$f(1, 2) = f(1, 3) = f(2, 3) = 6$$$."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa\u2009>\u2009pb, or pa\u2009=\u2009pb and ta\u2009<\u2009tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y\u2009+\u20091, y\u2009+\u20092, ..., y\u2009+\u2009x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y\u2009+\u2009x\u2009+\u20091-th place.Your task is to count what number of teams from the given list shared the k-th place. ", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200950). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1\u2009\u2264\u2009pi,\u2009ti\u2009\u2264\u200950) \u2014 the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. ", "output_spec": "In the only line print the sought number of teams that got the k-th place in the final results' table.", "sample_inputs": ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"], "sample_outputs": ["3", "4"], "notes": "NoteThe final results' table for the first sample is: 1-3 places \u2014 4 solved problems, the penalty time equals 10 4 place \u2014 3 solved problems, the penalty time equals 20 5-6 places \u2014 2 solved problems, the penalty time equals 1 7 place \u2014 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place \u2014 5 solved problems, the penalty time equals 3 2-5 places \u2014 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams."}, "positive_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 A = A.sortWith(compare)\n\n println(A.count(_ == A(k - 1)))\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 - 1)\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 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}"}, {"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}"}], "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"} {"nl": {"description": "Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi\u2009-\u2009(ti\u2009-\u2009k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value. ", "input_spec": "The first line contains two space-separated integers \u2014 n (1\u2009\u2264\u2009n\u2009\u2264\u2009104) and k (1\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers \u2014 fi (1\u2009\u2264\u2009fi\u2009\u2264\u2009109) and ti (1\u2009\u2264\u2009ti\u2009\u2264\u2009109) \u2014 the characteristics of the i-th restaurant.", "output_spec": "In a single line print a single integer \u2014 the maximum joy value that the Rabbits will get from the lunch. ", "sample_inputs": ["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"], "sample_outputs": ["4", "3", "-1"], "notes": null}, "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.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"}, {"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"} {"nl": {"description": "You are given a permutation $$$p$$$ of integers from $$$1$$$ to $$$n$$$, where $$$n$$$ is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: take two indices $$$i$$$ and $$$j$$$ such that $$$2 \\cdot |i - j| \\geq n$$$ and swap $$$p_i$$$ and $$$p_j$$$. There is no need to minimize the number of operations, however you should use no more than $$$5 \\cdot n$$$ operations. One can show that it is always possible to do that.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$, $$$n$$$ is even)\u00a0\u2014 the length of the permutation. The second line contains $$$n$$$ distinct integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\le p_i \\le n$$$)\u00a0\u2014 the given permutation.", "output_spec": "On the first line print $$$m$$$ ($$$0 \\le m \\le 5 \\cdot n$$$)\u00a0\u2014 the number of swaps to perform. Each of the following $$$m$$$ lines should contain integers $$$a_i, b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$, $$$|a_i - b_i| \\ge \\frac{n}{2}$$$)\u00a0\u2014 the indices that should be swapped in the corresponding swap. Note that there is no need to minimize the number of operations. We can show that an answer always exists.", "sample_inputs": ["2\n2 1", "4\n3 4 1 2", "6\n2 5 3 1 4 6"], "sample_outputs": ["1\n1 2", "4\n1 4\n1 4\n1 3\n2 4", "3\n1 5\n2 5\n1 4"], "notes": "NoteIn the first example, when one swap elements on positions $$$1$$$ and $$$2$$$, the array becomes sorted.In the second example, pay attention that there is no need to minimize number of swaps.In the third example, after swapping elements on positions $$$1$$$ and $$$5$$$ the array becomes: $$$[4, 5, 3, 1, 2, 6]$$$. After swapping elements on positions $$$2$$$ and $$$5$$$ the array becomes $$$[4, 2, 3, 1, 5, 6]$$$ and finally after swapping elements on positions $$$1$$$ and $$$4$$$ the array becomes sorted: $$$[1, 2, 3, 4, 5, 6]$$$."}, "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\nimport scala.util.Random\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 ps = readInts(n).map(_ - 1)\n\n def canSwap(i: Int, j: Int): Boolean = {\n 2 * Math.abs(i - j) >= n\n }\n\n val moves = ArrayBuffer.empty[(Int, Int)]\n\n def swap(i: Int, j: Int): Unit = {\n require(canSwap(i, j))\n moves += (i + 1) -> (j + 1)\n val t = ps(i)\n ps(i) = ps(j)\n ps(j) = t\n }\n\n var ok = true\n do {\n ok = true\n for (i <- 0 until n) {\n val p = ps(i)\n if (i != p) {\n ok = false\n if (canSwap(i, p)) {\n swap(i, p)\n } else {\n if (canSwap(i, n - 1) && canSwap(p, n - 1)) {\n swap(i, n - 1)\n swap(p, n - 1)\n } else if (canSwap(i, 0) && canSwap(p, 0)) {\n swap(i, 0)\n swap(p, 0)\n } else {\n val min = i min p\n val max = i max p\n swap(min, n - 1)\n swap(n - 1, 0)\n swap(0, max)\n }\n }\n }\n }\n } while (!ok)\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(moves.size)\n println(moves.map {\n case (i, j) => \"\" + i + \" \" + j\n }.mkString(\"\\n\"))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "b1706815238eb940060231848e43ffa8"} {"nl": {"description": "Little Dima has two sequences of points with integer coordinates: sequence (a1,\u20091),\u2009(a2,\u20092),\u2009...,\u2009(an,\u2009n) and sequence (b1,\u20091),\u2009(b2,\u20092),\u2009...,\u2009(bn,\u2009n).Now Dima wants to count the number of distinct sequences of points of length 2\u00b7n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.Dima considers two assembled sequences (p1,\u2009q1),\u2009(p2,\u2009q2),\u2009...,\u2009(p2\u00b7n,\u2009q2\u00b7n) and (x1,\u2009y1),\u2009(x2,\u2009y2),\u2009...,\u2009(x2\u00b7n,\u2009y2\u00b7n) distinct, if there is such i (1\u2009\u2264\u2009i\u2009\u2264\u20092\u00b7n), that (pi,\u2009qi)\u2009\u2260\u2009(xi,\u2009yi).As the answer can be rather large, print the remainder from dividing the answer by number m.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line contains n integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009109). The numbers in the lines are separated by spaces. The last line contains integer m (2\u2009\u2264\u2009m\u2009\u2264\u2009109\u2009+\u20097).", "output_spec": "In the single line print the remainder after dividing the answer to the problem by number m. ", "sample_inputs": ["1\n1\n2\n7", "2\n1 2\n2 3\n11"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample you can get only one sequence: (1,\u20091),\u2009(2,\u20091). In the second sample you can get such sequences : (1,\u20091),\u2009(2,\u20092),\u2009(2,\u20091),\u2009(3,\u20092); (1,\u20091),\u2009(2,\u20091),\u2009(2,\u20092),\u2009(3,\u20092). Thus, the answer is 2."}, "positive_code": [{"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i+1)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i+1)\n }\n arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n }\n else{\n ans*=i\n }\n ans%=m\n }\n ans\n }\n} \n\n\n"}], "negative_code": [{"source_code": "import collection.mutable.Map\nimport collection.mutable.ArrayBuffer\nimport java.util.Scanner\n\nobject test6 extends App {\n val sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=0\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n if(t>0){\n while(ans%2==0){ans/=2;t-=1}\n }\n ans*=i\n if(t==0) ans%=m\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=0\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n if(t>0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n }\n else{\n ans*=i\n ans%=m\n }\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i+1)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i+1)\n }\n arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n }\n else{\n ans*=i\n }\n ans%=m\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=1\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n if(t>0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n ans%=m\n }\n else{\n ans*=i\n ans%=m\n }\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=1\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n while(ans%2==0 && t>0){\n ans/=2\n t-=1\n }\n ans*=i\n if(t==0) ans%=m\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i+1)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i+1)\n }\n arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n ans%=m\n }\n else{\n ans*=i\n ans%=m\n }\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=0\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n while(ans%2==0 && t>0){\n ans/=2\n t-=1\n }\n ans*=i\n if(t==0) ans%=m\n }\n ans\n }\n} \n\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 b=readLine.split(\" \").map(_.toInt)\n val m=readInt\n val fact=new Array[Int](n+1)\n fact(0)=1\n for(i<-1 to n) fact(i)=(i*fact(i-1))%m\n val arr=a++b sorted\n var count:Long=1\n \n var i=0\n var j=0\n while(j<2*n){\n if(arr(j)==arr(i))\n j+=1\n else{\n count*=fact(j-i)\n count%=m\n i=j\n }\n }\n \n count*=fact(j-i)\n count%=m\n println(count)\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=0\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n if(t>0){\n while(ans%2==0){ans/=2;t-=1}\n }\n ans*=i\n ans%=m\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i+1)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i+1)\n }\n arr=arr.sortWith((x,y)=>x(0)0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n ans%=m\n }\n else{\n ans*=i\n ans%=m\n }\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortBy(aa=>aa(0))\n val m=sc.nextInt\n \n var count:Long=1\n var i=0\n var j=1\n var tmp=0\n while(j<2*n){\n if(arr(j)(0)==arr(i)(0)){\n if(arr(j)(1)==arr(i)(1)) tmp+=1\n }\n else{\n count*=fact(j-i,tmp)\n count%=m\n i=j\n tmp=0\n }\n j+=1\n }\n \n count*=fact(j-i, tmp)\n count%=m\n println(count)\n \n def fact(count:Int, tmp:Int):Long={\n var ans:Long=1\n var t=tmp\n for(i<-count to 2 by -1){\n if(t>0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n }\n else{\n ans*=i\n ans%=m\n }\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i+1)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i+1)\n }\n arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)0){\n while(ans%2==0 && t>0){\n ans/=2\n t-=1\n }\n }\n ans*=i\n if(t==0)ans%=m\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i)\n }\n arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)0){\n var tt=i\n while(tt%2==0 && t>0){\n tt/=2\n t-=1\n }\n ans*=tt\n ans%=m\n }\n else{\n ans*=i\n ans%=m\n }\n }\n ans\n }\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 sc=new Scanner(System.in)\n val n=sc.nextInt\n var arr=new Array[Array[Int]](2*n)\n for(i<-0 until n){\n arr(i)=Array(sc.nextInt,i+1)\n }\n for(i<-0 until n){\n arr(n+i)=Array(sc.nextInt,i+1)\n }\n arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)0){\n ans/=2\n t-=1\n }\n ans*=i\n if(t==0)ans%=m\n }\n ans\n }\n} \n\n\n"}], "src_uid": "c5bac81b91aee54b6f3f4554f4eb9d76"} {"nl": {"description": "Ashish has $$$n$$$ elements arranged in a line. These elements are represented by two integers $$$a_i$$$\u00a0\u2014 the value of the element and $$$b_i$$$\u00a0\u2014 the type of the element (there are only two possible types: $$$0$$$ and $$$1$$$). He wants to sort the elements in non-decreasing values of $$$a_i$$$.He can perform the following operation any number of times: Select any two elements $$$i$$$ and $$$j$$$ such that $$$b_i \\ne b_j$$$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $$$a_i$$$ after performing any number of operations.", "input_spec": "The first line contains one integer $$$t$$$ $$$(1 \\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ $$$(1 \\le n \\le 500)$$$\u00a0\u2014 the size of the arrays. The second line contains $$$n$$$ integers $$$a_i$$$ $$$(1 \\le a_i \\le 10^5)$$$ \u00a0\u2014 the value of the $$$i$$$-th element. The third line containts $$$n$$$ integers $$$b_i$$$ $$$(b_i \\in \\{0, 1\\})$$$ \u00a0\u2014 the type of the $$$i$$$-th element.", "output_spec": "For each test case, print \"Yes\" or \"No\" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value. You may print each letter in any case (upper or lower).", "sample_inputs": ["5\n4\n10 20 20 30\n0 1 0 1\n3\n3 1 2\n0 1 1\n4\n2 2 4 8\n1 1 1 1\n3\n5 15 4\n0 0 0\n4\n20 10 100 50\n1 0 0 1"], "sample_outputs": ["Yes\nYes\nYes\nNo\nYes"], "notes": "NoteFor the first case: The elements are already in sorted order.For the second case: Ashish may first swap elements at positions $$$1$$$ and $$$2$$$, then swap elements at positions $$$2$$$ and $$$3$$$.For the third case: The elements are already in sorted order.For the fourth case: No swap operations may be performed as there is no pair of elements $$$i$$$ and $$$j$$$ such that $$$b_i \\ne b_j$$$. The elements cannot be sorted.For the fifth case: Ashish may swap elements at positions $$$3$$$ and $$$4$$$, then elements at positions $$$1$$$ and $$$2$$$."}, "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 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"}, {"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"} {"nl": {"description": "For the given integer $$$n$$$ ($$$n > 2$$$) let's write down all the strings of length $$$n$$$ which contain $$$n-2$$$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string $$$s$$$ of length $$$n$$$ is lexicographically less than string $$$t$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \\le i \\le n$$$), that $$$s_i < t_i$$$, and for any $$$j$$$ ($$$1 \\le j < i$$$) $$$s_j = t_j$$$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if $$$n=5$$$ the strings are (the order does matter): aaabb aabab aabba abaab ababa abbaa baaab baaba babaa bbaaa It is easy to show that such a list of strings will contain exactly $$$\\frac{n \\cdot (n-1)}{2}$$$ strings.You are given $$$n$$$ ($$$n > 2$$$) and $$$k$$$ ($$$1 \\le k \\le \\frac{n \\cdot (n-1)}{2}$$$). Print the $$$k$$$-th string from the list.", "input_spec": "The input contains one or more test cases. The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case is written on the the separate line containing two integers $$$n$$$ and $$$k$$$ ($$$3 \\le n \\le 10^5, 1 \\le k \\le \\min(2\\cdot10^9, \\frac{n \\cdot (n-1)}{2})$$$. The sum of values $$$n$$$ over all test cases in the test doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print the $$$k$$$-th string from the list of all described above strings of length $$$n$$$. Strings in the list are sorted lexicographically (alphabetically).", "sample_inputs": ["7\n5 1\n5 2\n5 8\n5 10\n3 1\n3 2\n20 100"], "sample_outputs": ["aaabb\naabab\nbaaba\nbbaaa\nabb\nbab\naaaaabaaaaabaaaaaaaa"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "There are $$$n$$$ products in the shop. The price of the $$$i$$$-th product is $$$a_i$$$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product $$$i$$$ in such a way that the difference between the old price of this product $$$a_i$$$ and the new price $$$b_i$$$ is at most $$$k$$$. In other words, the condition $$$|a_i - b_i| \\le k$$$ should be satisfied ($$$|x|$$$ is the absolute value of $$$x$$$).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price $$$b_i$$$ of each product $$$i$$$ should be positive (i.e. $$$b_i > 0$$$ should be satisfied for all $$$i$$$ from $$$1$$$ to $$$n$$$).Your task is to find out the maximum possible equal price $$$B$$$ of all productts with the restriction that for all products the condiion $$$|a_i - B| \\le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the same new price of all products) or report that it is impossible to find such price $$$B$$$.Note that the chosen price $$$B$$$ should be integer.You should answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2014 the number of queries. Each query is presented by two lines. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 100, 1 \\le k \\le 10^8$$$) \u2014 the number of products and the value $$$k$$$. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^8$$$), where $$$a_i$$$ is the price of the $$$i$$$-th product.", "output_spec": "Print $$$q$$$ integers, where the $$$i$$$-th integer is the answer $$$B$$$ on the $$$i$$$-th query. If it is impossible to equalize prices of all given products with restriction that for all products the condition $$$|a_i - B| \\le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.", "sample_inputs": ["4\n5 1\n1 1 2 3 1\n4 2\n6 4 8 5\n2 2\n1 6\n3 5\n5 2 5"], "sample_outputs": ["2\n6\n-1\n7"], "notes": "NoteIn the first example query you can choose the price $$$B=2$$$. It is easy to see that the difference between each old price and each new price $$$B=2$$$ is no more than $$$1$$$.In the second example query you can choose the price $$$B=6$$$ and then all the differences between old and new price $$$B=6$$$ will be no more than $$$2$$$.In the third example query you cannot choose any suitable price $$$B$$$. For any value $$$B$$$ at least one condition out of two will be violated: $$$|1-B| \\le 2$$$, $$$|6-B| \\le 2$$$.In the fourth example query all values $$$B$$$ between $$$1$$$ and $$$7$$$ are valid. But the maximum is $$$7$$$, so it's the answer."}, "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"}, {"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"}], "negative_code": [], "src_uid": "3b158306d335459ff55dcf29e46010e8"} {"nl": {"description": "You are fed up with your messy room, so you decided to clean it up.Your room is a bracket sequence $$$s=s_{1}s_{2}\\dots s_{n}$$$ of length $$$n$$$. Each character of this string is either an opening bracket '(' or a closing bracket ')'.In one operation you can choose any consecutive substring of $$$s$$$ and reverse it. In other words, you can choose any substring $$$s[l \\dots r]=s_l, s_{l+1}, \\dots, s_r$$$ and change the order of elements in it into $$$s_r, s_{r-1}, \\dots, s_{l}$$$.For example, if you will decide to reverse substring $$$s[2 \\dots 4]$$$ of string $$$s=$$$\"((()))\" it will be equal to $$$s=$$$\"()(())\".A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences \"()()\", \"(())\" are regular (the resulting expressions are: \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.A prefix of a string $$$s$$$ is a substring that starts at position $$$1$$$. For example, for $$$s=$$$\"(())()\" there are $$$6$$$ prefixes: \"(\", \"((\", \"(()\", \"(())\", \"(())(\" and \"(())()\".In your opinion, a neat and clean room $$$s$$$ is a bracket sequence that: the whole string $$$s$$$ is a regular bracket sequence; and there are exactly $$$k$$$ prefixes of this sequence which are regular (including whole $$$s$$$ itself). For example, if $$$k = 2$$$, then \"(())()\" is a neat and clean room.You want to use at most $$$n$$$ operations to make your room neat and clean. Operations are applied one after another sequentially.It is guaranteed that the answer exists. Note that you do not need to minimize the number of operations: find any way to achieve the desired configuration in $$$n$$$ or less operations.", "input_spec": "The first line contains integer number $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le \\frac{n}{2}, 2 \\le n \\le 2000$$$, $$$n$$$ is even)\u00a0\u2014 length of $$$s$$$ and required number of regular prefixes. The second line of a test case contains $$$s$$$ of length $$$n$$$\u00a0\u2014 the given bracket sequence. It contains only '(' and ')'. It is guaranteed that there are exactly $$$\\frac{n}{2}$$$ characters '(' and exactly $$$\\frac{n}{2}$$$ characters ')' in the given string. The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$2000$$$.", "output_spec": "For each test case print an answer. In the first line print integer $$$m$$$ ($$$0 \\le m \\le n$$$)\u00a0\u2014 the number of operations. You do not need to minimize $$$m$$$, any value is suitable. In the following $$$m$$$ lines print description of the operations, each line should contain two integers $$$l,r$$$ ($$$1 \\le l \\le r \\le n$$$), representing single reverse operation of $$$s[l \\dots r]=s_{l}s_{l+1}\\dots s_{r}$$$. Operations are applied one after another sequentially. The final $$$s$$$ after all operations should be a regular, also it should be exactly $$$k$$$ prefixes (including $$$s$$$) which are regular. It is guaranteed that the answer exists. If there are several possible answers you can print any.", "sample_inputs": ["4\n8 2\n()(())()\n10 3\n))()()()((\n2 1\n()\n2 1\n)("], "sample_outputs": ["4\n3 4\n1 1\n5 8\n2 2\n3\n4 10\n1 4\n6 7\n0\n1\n1 2"], "notes": "NoteIn the first example, the final sequence is \"()(()())\", where two prefixes are regular, \"()\" and \"()(()())\". Note, that all the operations except \"5 8\" in the example output are useless (they do not change $$$s$$$)."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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"} {"nl": {"description": "A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative \u2014 it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X \u2014 the coefficient of income growth during one year. This coefficient should satisfy the equation:A\u00b7Xn\u2009=\u2009B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.", "input_spec": "The input contains three integers A, B, n (|A|,\u2009|B|\u2009\u2264\u20091000, 1\u2009\u2264\u2009n\u2009\u2264\u200910).", "output_spec": "Output the required integer coefficient X, or \u00abNo solution\u00bb, if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.", "sample_inputs": ["2 18 2", "-1 8 3", "0 0 10", "1 16 5"], "sample_outputs": ["3", "-2", "5", "No solution"], "notes": null}, "positive_code": [{"source_code": "object P030A {\n def errorOut():Unit = {\n println(\"No solution\")\n System.exit(0)\n }\n def earlyOut(x: Int): Unit = {\n println(x);\n System.exit(0);\n }\n def solve(y: Int, n: Int): Int = {\n return math.round(math.exp(math.log(y)/n)).toInt;\n }\n def pow(x: Int, n: Int):Int = {\n var y = 1\n for (i <- 1 to n) y *= x\n return y\n }\n def main(args: Array[String]) = {\n val Array(a, b, n) = readLine.split(\" \").map(_.toInt)\n if (a == 0 && b != 0) errorOut();\n if (a == 0 && b == 0) earlyOut(1);\n if (b % a != 0) errorOut();\n val y = b/a;\n if (y == 0) earlyOut(0);\n if (y < 0 && n % 2 == 0) errorOut();\n val x = if (y > 0) solve(y, n) else -solve(-y, n)\n if (pow(x, n) != y) errorOut();\n println(x)\n }\n}\n"}], "negative_code": [], "src_uid": "8a9adc116abbd387a6a64dd754436f8a"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\dots, p_n$$$. A permutation of length $$$n$$$ is a sequence such that each integer between $$$1$$$ and $$$n$$$ occurs exactly once in the sequence.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \\le l \\le r \\le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \\dots, p_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \\le l \\le r \\le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \\dots, p_r$$$ is exactly the given number $$$m$$$.", "input_spec": "The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$, $$$1 \\le m \\le n$$$) \u2014 the length of the given sequence and the required value of the median. The second line contains a permutation $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$). Each integer between $$$1$$$ and $$$n$$$ occurs in $$$p$$$ exactly once.", "output_spec": "Print the required number.", "sample_inputs": ["5 4\n2 4 5 3 1", "5 5\n1 2 3 4 5", "15 8\n1 15 2 14 3 13 4 8 12 5 11 6 10 7 9"], "sample_outputs": ["4", "1", "48"], "notes": "NoteIn the first example, the suitable pairs of indices are: $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$ and $$$(2, 4)$$$."}, "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, mid = ni()\n val A = map(N) { _ =>\n ni() match {\n case a if a > mid => 1\n case `mid` => 0\n case a if a < mid => -1\n }\n }\n val ix = A.indexWhere(_ == 0)\n\n val L = A.slice(0, ix + 1).reverse\n val R = A.slice(ix, N)\n\n def mkCount(nums: Array[Int]) = {\n val cum = cumSum(nums)\n val cnt = mutable.Map[Int, Int]().withDefaultValue(0)\n // index0\u306b\uff10\u500b\u30ab\u30a6\u30f3\u30c8\u3059\u308b\u3082\u306e\u304c\u5165\u3063\u3066\u3044\u308b\u306e\u3067\u9664\u5916\u3059\u308b\n REP(nums.length, 1) { i =>\n val n = cum(i)\n cnt(n) = cnt(n) + 1\n }\n cnt\n }\n\n val cntL = mkCount(L)\n val cntR = mkCount(R)\n\n var ans = 0L\n cntL.foreach { case (l, cnt) =>\n // \u5408\u8a08\u304c0\u304b1\u306a\u3089\u4e2d\u9593\u5024\u306b\u306a\u308b\n ans += cntR(-l) * cnt.toLong + cntR(-l + 1) * cnt.toLong\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, mid = ni()\n val A = map(N) { _ =>\n ni() match {\n case a if a > mid => 1\n case `mid` => 0\n case a if a < mid => -1\n }\n }\n val ix = A.indexWhere(_ == 0)\n\n val L = A.slice(0, ix + 1).reverse\n val R = A.slice(ix, N)\n\n def mkCount(nums: Array[Int]) = {\n val cum = cumSum(nums)\n val cnt = mutable.Map[Int, Int]().withDefaultValue(0)\n // index0\u306b\uff10\u500b\u30ab\u30a6\u30f3\u30c8\u3059\u308b\u3082\u306e\u304c\u5165\u3063\u3066\u3044\u308b\u306e\u3067\u9664\u5916\u3059\u308b\n REP(nums.length, 1) { i =>\n val n = cum(i)\n cnt(n) = cnt(n) + 1\n }\n cnt\n }\n\n val cntL = mkCount(L)\n val cntR = mkCount(R)\n\n var ans = 0L\n cntL.foreach { case (l, cnt) =>\n // \u5408\u8a08\u304c0\u304b1\u306a\u3089\u4e2d\u9593\u5024\u306b\u306a\u308b\n ans += cntR(-l) * cnt + cntR(-l + 1) * cnt\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}"}], "src_uid": "52e1fd9d3c82cd70c686e575c92c1442"} {"nl": {"description": "Little X and Little Z are good friends. They always chat online. But both of them have schedules.Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c1 and d1, between c2 and d2, ..., between cq and dq (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [ci\u2009+\u2009t,\u2009di\u2009+\u2009t] (for all i).If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l,\u2009r] suit for that?", "input_spec": "The first line contains four space-separated integers p,\u2009q,\u2009l,\u2009r (1\u2009\u2264\u2009\u2009p,\u2009q\u2009\u2264\u200950;\u00a00\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u20091000). Each of the next p lines contains two space-separated integers ai,\u2009bi (0\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u20091000). Each of the next q lines contains two space-separated integers cj,\u2009dj (0\u2009\u2264\u2009cj\u2009<\u2009dj\u2009\u2264\u20091000). It's guaranteed that bi\u2009<\u2009ai\u2009+\u20091 and dj\u2009<\u2009cj\u2009+\u20091 for all valid i and j.", "output_spec": "Output a single integer \u2014 the number of moments of time from the segment [l,\u2009r] which suit for online conversation.", "sample_inputs": ["1 1 0 4\n2 3\n0 1", "2 3 0 20\n15 17\n23 26\n1 4\n7 11\n15 17"], "sample_outputs": ["3", "20"], "notes": null}, "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": "\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}"}, {"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"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ and an integer $$$k$$$, such that $$$1 \\leq k \\leq n$$$. A permutation means that every number from $$$1$$$ to $$$n$$$ is contained in $$$p$$$ exactly once.Let's consider all partitions of this permutation into $$$k$$$ disjoint segments. Formally, a partition is a set of segments $$$\\{[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]\\}$$$, such that: $$$1 \\leq l_i \\leq r_i \\leq n$$$ for all $$$1 \\leq i \\leq k$$$; For all $$$1 \\leq j \\leq n$$$ there exists exactly one segment $$$[l_i, r_i]$$$, such that $$$l_i \\leq j \\leq r_i$$$. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as $$$\\sum\\limits_{i=1}^{k} {\\max\\limits_{l_i \\leq j \\leq r_i} {p_j}}$$$, for all possible partitions of the permutation into $$$k$$$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $$$998\\,244\\,353$$$.", "input_spec": "The first line contains two integers, $$$n$$$ and $$$k$$$ ($$$1 \\leq k \\leq n \\leq 200\\,000$$$)\u00a0\u2014 the size of the given permutation and the number of segments in a partition. The second line contains $$$n$$$ different integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\leq p_i \\leq n$$$)\u00a0\u2014 the given permutation.", "output_spec": "Print two integers\u00a0\u2014 the maximum possible partition value over all partitions of the permutation into $$$k$$$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $$$998\\,244\\,353$$$. Please note that you should only find the second value modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["3 2\n2 1 3", "5 5\n2 1 5 3 4", "7 3\n2 7 3 1 5 4 6"], "sample_outputs": ["5 2", "15 1", "18 6"], "notes": "NoteIn the first test, for $$$k = 2$$$, there exists only two valid partitions: $$$\\{[1, 1], [2, 3]\\}$$$ and $$$\\{[1, 2], [3, 3]\\}$$$. For each partition, the partition value is equal to $$$2 + 3 = 5$$$. So, the maximum possible value is $$$5$$$ and the number of partitions is $$$2$$$.In the third test, for $$$k = 3$$$, the partitions with the maximum possible partition value are $$$\\{[1, 2], [3, 5], [6, 7]\\}$$$, $$$\\{[1, 3], [4, 5], [6, 7]\\}$$$, $$$\\{[1, 4], [5, 5], [6, 7]\\}$$$, $$$\\{[1, 2], [3, 6], [7, 7]\\}$$$, $$$\\{[1, 3], [4, 6], [7, 7]\\}$$$, $$$\\{[1, 4], [5, 6], [7, 7]\\}$$$. For all of them, the partition value is equal to $$$7 + 5 + 6 = 18$$$. The partition $$$\\{[1, 2], [3, 4], [5, 7]\\}$$$, however, has the partition value $$$7 + 3 + 6 = 16$$$. This is not the maximum possible value, so we don't count it."}, "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 MOD = 998244353L\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val k = in.nextInt()\n val p = ListBuffer.empty[Int]\n var res = 0L\n (1 to n).foreach{ i =>\n val ai = in.nextInt()\n if(ai>(n-k)){\n p.append(i)\n res+=ai\n }\n }\n var acum = 1L\n val items = p.toList\n items.zip(items.tail).foreach{ case (i,j) =>\n\n acum = (acum*(j-i))%MOD\n }\n out.println(s\"$res $acum\")\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 val MOD = 998244353L\n def solve(inputStream: InputStream, out: PrintStream): Unit = {\n val in = new InputReader(inputStream)\n val n = in.nextInt()\n val k = in.nextInt()\n val p = ListBuffer.empty[Int]\n var res = 0\n (1 to n).foreach{ i =>\n val ai = in.nextInt()\n if(ai>(n-k)){\n p.append(i)\n res+=ai\n }\n }\n var acum = 1L\n val items = p.toList\n items.zip(items.tail).foreach{ case (i,j) =>\n\n acum = (acum*(j-i))%MOD\n }\n out.println(s\"$res $acum\")\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": "926c01419301caff034988aff98edc9d"} {"nl": {"description": "Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.", "input_spec": "The first line contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of vertices in the tree. Each of the next n\u2009-\u20091 lines contains two integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, u\u2009\u2260\u2009v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009105), denoting the colors of the vertices.", "output_spec": "Print \"NO\" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print \"YES\" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.", "sample_inputs": ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"], "sample_outputs": ["YES\n2", "YES\n2", "NO"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a positive integer written on it. Let's call a grid good, if in each row the sequence of numbers is sorted in a non-decreasing order. It means, that for each $$$1 \\le i \\le n$$$ and $$$2 \\le j \\le m$$$ the following holds: $$$a_{i,j} \\ge a_{i, j-1}$$$.You have to to do the following operation exactly once: choose two columns with indexes $$$i$$$ and $$$j$$$ (not necessarily different), $$$1 \\le i, j \\le m$$$, and swap them.You are asked to determine whether it is possible to make the grid good after the swap and, if it is, find the columns that need to be swapped.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of rows and columns respectively. Each of the next $$$n$$$ rows contains $$$m$$$ integers, $$$j$$$-th element of $$$i$$$-th row is $$$a_{i,j}$$$ ($$$1 \\le a_{i,j} \\le 10^9$$$)\u00a0\u2014 the number written in the $$$j$$$-th cell of the $$$i$$$-th row. It's guaranteed that the sum of $$$n \\cdot m$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "If after the swap it is impossible to get a good grid, output $$$-1$$$. In the other case output $$$2$$$ integers\u00a0\u2014 the indices of the columns that should be swapped to get a good grid. If there are multiple solutions, print any.", "sample_inputs": ["5\n\n2 3\n\n1 2 3\n\n1 1 1\n\n2 2\n\n4 1\n\n2 3\n\n2 2\n\n2 1\n\n1 1\n\n2 3\n\n6 2 1\n\n5 4 3\n\n2 1\n\n1\n\n2"], "sample_outputs": ["1 1\n-1\n1 2\n1 3\n1 1"], "notes": "NoteIn the first test case the grid is initially good, so we can, for example, swap the first column with itself.In the second test case it is impossible to make the grid good.In the third test case it is needed to swap the first and the second column, then the grid becomes good."}, "positive_code": [{"source_code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util\n\nobject Main {\n\n def findNotSortedRow(a: Array[Array[Int]]): Option[Int] = {\n a.indices.find { i =>\n (1 until a(i).length).exists { j =>\n a(i)(j - 1) > a(i)(j)\n }\n }\n }\n\n def swapColumns(a: Array[Array[Int]], i: Int, j: Int) = {\n a.foreach { row =>\n val temp = row(i)\n row(i) = row(j)\n row(j) = temp\n }\n }\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.nextInt()\n val m = reader.nextInt()\n val a = new Array[Array[Int]](n)\n a.indices.foreach(a(_) = new Array[Int](m))\n a.foreach { row =>\n row.indices.foreach(row(_) = reader.nextInt())\n }\n findNotSortedRow(a) match {\n case Some(rowId) =>\n val sortedRow = a(rowId).sorted\n val differentValues = new util.ArrayList[Int]()\n sortedRow.indices.foreach { i =>\n if (sortedRow(i) != a(rowId)(i)) differentValues.add(i)\n }\n if (differentValues.size() == 2) {\n swapColumns(a, differentValues.get(0), differentValues.get(1))\n if (findNotSortedRow(a).isEmpty) {\n System.out.println((differentValues.get(0) + 1) + \" \" + (differentValues.get(1) + 1))\n } else {\n System.out.println(\"-1\")\n }\n } else {\n System.out.println(\"-1\")\n }\n case None => System.out.println(\"1 1\")\n }\n\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 java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.util\n\nobject Main {\n\n def findNotSortedRow(a: Array[Array[Int]]): Option[Int] = {\n a.indices.find { i =>\n (1 until a(i).length).exists { j =>\n a(i)(j - 1) > a(i)(j)\n }\n }\n }\n\n def swapColumns(a: Array[Array[Int]], i: Int, j: Int) = {\n a.foreach { row =>\n val temp = row(i)\n row(i) = row(j)\n row(j) = temp\n }\n }\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.nextInt()\n val m = reader.nextInt()\n val a = new Array[Array[Int]](n)\n a.indices.foreach(a(_) = new Array[Int](m))\n a.foreach { row =>\n row.indices.foreach(row(_) = reader.nextInt())\n }\n findNotSortedRow(a) match {\n case Some(rowId) =>\n val sortedRow = a(rowId).sorted\n val differentValues = new util.ArrayList[Int]()\n sortedRow.indices.foreach { i =>\n if (sortedRow(i) != a(rowId)(i)) differentValues.add(i)\n }\n if (differentValues.size() == 2) {\n swapColumns(a, differentValues.get(0), differentValues.get(1))\n if (findNotSortedRow(a).isEmpty) {\n System.out.println((differentValues.get(0) + 1) + \" \" + (differentValues.get(1) + 1))\n } else {\n System.out.println(\"-1\")\n }\n } else {\n System.out.println(\"1 1\")\n }\n case None => System.out.println(\"1 1\")\n }\n\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"}], "src_uid": "cfe752f8ff049e535309c234da60472d"} {"nl": {"description": "Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j\u2009<\u2009i and j\u2009\u2265\u2009i\u2009-\u2009Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of guilty people. Second line contains n space-separated integers L1,\u2009L2,\u2009...,\u2009Ln (0\u2009\u2264\u2009Li\u2009\u2264\u2009109), where Li is the length of the i-th person's claw.", "output_spec": "Print one integer \u2014 the total number of alive people after the bell rings.", "sample_inputs": ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"], "sample_outputs": ["1", "2", "3"], "notes": "NoteIn first sample the last person kills everyone in front of him."}, "positive_code": [{"source_code": "object B extends App {\n val n = scala.io.StdIn.readLine().toInt\n val L = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val l = L.length - 1\n\n def survivors(i: Int = l, j: Int = l, s: Int = 0): Int = {\n if (j <= 0) L.length - s\n else {\n val t = 0 max (i - L(i))\n if (j >= t) survivors(i - 1, t, s + (j min i) - t)\n else survivors(i - 1, j, s)\n }\n }\n\n println(survivors())\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n val n = scala.io.StdIn.readLine().toInt\n val L = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val l = L.length - 1\n\n def survivors(i: Int = l, j: Int = l, s: Int = 0): Int = {\n if (j <= 0) L.length - s\n else {\n val t = 0 max (i - L(i))\n if (t < j) survivors(i - 1, t, s + (j min i - t) max 0)\n else survivors(i - 1, j, s)\n }\n }\n\n println(survivors())\n}\n"}], "src_uid": "beaeeb8757232b141d510547d73ade04"} {"nl": {"description": "You've got an array a, consisting of n integers a1,\u2009a2,\u2009...,\u2009an. You are allowed to perform two operations on this array: Calculate the sum of current array elements on the segment [l,\u2009r], that is, count value al\u2009+\u2009al\u2009+\u20091\u2009+\u2009...\u2009+\u2009ar. Apply the xor operation with a given number x to each array element on the segment [l,\u2009r], that is, execute . This operation changes exactly r\u2009-\u2009l\u2009+\u20091 array elements. Expression means applying bitwise xor operation to numbers x and y. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as \"^\", in Pascal \u2014 as \"xor\".You've got a list of m operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the array. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the original array. The third line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u20095\u00b7104) \u2014 the number of operations with the array. The i-th of the following m lines first contains an integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20092) \u2014 the type of the i-th query. If ti\u2009=\u20091, then this is the query of the sum, if ti\u2009=\u20092, then this is the query to change array elements. If the i-th operation is of type 1, then next follow two integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). If the i-th operation is of type 2, then next follow three integers li,\u2009ri,\u2009xi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009106). The numbers on the lines are separated by single spaces.", "output_spec": "For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams, or the %I64d specifier.", "sample_inputs": ["5\n4 10 3 13 7\n8\n1 2 4\n2 1 3 3\n1 2 4\n1 3 3\n2 2 5 5\n1 1 5\n2 1 2 10\n1 2 3", "6\n4 7 4 0 7 3\n5\n2 2 3 8\n1 1 5\n2 3 5 1\n2 4 5 6\n1 2 3"], "sample_outputs": ["26\n22\n0\n34\n11", "38\n28"], "notes": null}, "positive_code": [{"source_code": "object A extends App {\n class Tree(a: Array[Int]) {\n var n = a.size\n\n val s = new Array[Int](n * 2)\n val inv = new Array[Boolean](n * 2)\n\n build(0, n)\n\n def propagate(l: Int, r: Int) {\n if (inv(l+r)) {\n val m = (l+r) / 2\n inv(l+m) ^= inv(l+r)\n inv(m+r) ^= inv(l+r)\n inv(l+r) = false\n }\n }\n\n def sum(l: Int, r: Int, ll: Int, rr: Int): Int = {\n if (ll <= l && r <= rr)\n return if (inv(l+r)) r-l-s(l+r) else s(l+r)\n propagate(l, r)\n val m = (l+r) / 2\n var res = 0\n if (ll < m) res += sum(l, m, ll, rr)\n if (m < rr) res += sum(m, r, ll, rr)\n s(l+r) = sum(l, m, l, m) + sum(m, r, m, r)\n res\n }\n\n def invert(l: Int, r: Int, ll: Int, rr: Int) {\n if (ll <= l && r <= rr) {\n inv(l+r) ^= true\n return\n }\n propagate(l, r)\n val m = (l+r) / 2\n var res = 0\n if (ll < m) invert(l, m, ll, rr)\n if (m < rr) invert(m, r, ll, rr)\n s(l+r) = sum(l, m, l, m) + sum(m, r, m, r)\n }\n\n def build(l: Int, r: Int) {\n if (l == r-1)\n s(l+r) = a(l)\n else {\n val m = (l+r) / 2\n build(l, m)\n build(m, r)\n s(l+r) = s(l+m) + s(m+r)\n }\n }\n }\n\n val n = readInt\n var nn = n\n while ((nn & nn-1) > 0)\n nn += nn & -nn\n\n val a = readLine split ' ' map (_.toInt)\n val b = new Array[Int](nn)\n val trees = new Array[Tree](20)\n\n for (i <- 0 until 20) {\n for (j <- 0 until nn)\n b(j) = if (j < n && (a(j) & 1 << i) != 0) 1 else 0\n trees(i) = new Tree(b)\n }\n\n val m = readInt\n val res = new StringBuffer\n for (i <- 0 until m) {\n val o = readLine split ' ' map (_.toInt)\n if (o(0) == 1) {\n var s = 0L\n for (j <- 0 until 20)\n s += trees(j).sum(0, nn, o(1)-1, o(2)).toLong << j\n res append (s + \"\\n\")\n } else {\n for (j <- 0 until 20)\n if ((o(3) & 1 << j) != 0)\n trees(j).invert(0, nn, o(1)-1, o(2))\n }\n }\n print(res)\n}\n"}], "negative_code": [{"source_code": "object A extends App {\n class Tree(a: Array[Int]) {\n var n = a.size\n\n val s = new Array[Int](n * 2)\n val inv = new Array[Boolean](n * 2)\n\n build(0, n)\n\n def propagate(l: Int, r: Int) {\n if (inv(l+r)) {\n val m = (l+r) / 2\n inv(l+m) ^= inv(l+r)\n inv(m+r) ^= inv(l+r)\n inv(l+r) = false\n }\n }\n\n def sum(l: Int, r: Int, ll: Int, rr: Int): Int = {\n if (ll <= l && r <= rr)\n return if (inv(l+r)) r-l-s(l+r) else s(l+r)\n propagate(l, r)\n val m = (l+r) / 2\n var res = 0\n if (ll < m) res += sum(l, m, ll, rr)\n if (m < rr) res += sum(m, r, ll, rr)\n res\n }\n\n def invert(l: Int, r: Int, ll: Int, rr: Int) {\n if (ll <= l && r <= rr) {\n inv(l+r) ^= true\n return\n }\n propagate(l, r)\n val m = (l+r) / 2\n var res = 0\n if (ll < m) invert(l, m, ll, rr)\n if (m < rr) invert(m, r, ll, rr)\n s(l+r) = sum(l, m, l, m) + sum(m, r, m, r)\n }\n\n def build(l: Int, r: Int) {\n if (l == r-1)\n s(l+r) = a(l)\n else {\n val m = (l+r) / 2\n build(l, m)\n build(m, r)\n s(l+r) = s(l+m) + s(m+r)\n }\n }\n }\n\n val n = readInt\n var nn = n\n while ((nn & nn-1) > 0)\n nn += nn & -nn\n\n val a = readLine split ' ' map (_.toInt)\n val b = new Array[Int](nn)\n val trees = new Array[Tree](20)\n\n for (i <- 0 until 20) {\n for (j <- 0 until nn)\n b(j) = if (j < n && (a(j) & 1 << i) != 0) 1 else 0\n trees(i) = new Tree(b)\n }\n\n val m = readInt\n val res = new StringBuffer\n for (i <- 0 until m) {\n val o = readLine split ' ' map (_.toInt)\n if (o(0) == 1) {\n var s = 0L\n for (j <- 0 until 20)\n s += trees(j).sum(0, nn, o(1)-1, o(2)).toLong << j\n res append (s + \"\\n\")\n } else {\n for (j <- 0 until 20)\n if ((o(3) & 1 << j) != 0)\n trees(j).invert(0, nn, o(1)-1, o(2))\n }\n }\n print(res)\n}\n"}], "src_uid": "79bb09f5d8b591bfcfcea1b61be9d020"} {"nl": {"description": "Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i\u2009-\u20091 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n\u2009=\u20094, the array is changing as follows: You have to write a program that allows you to determine what number will be in the cell with index x (1\u2009\u2264\u2009x\u2009\u2264\u2009n) after Dima's algorithm finishes.", "input_spec": "The first line contains two integers n and q (1\u2009\u2264\u2009n\u2009\u2264\u20091018, 1\u2009\u2264\u2009q\u2009\u2264\u2009200\u2009000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.", "output_spec": "For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.", "sample_inputs": ["4 3\n2\n3\n4", "13 4\n10\n5\n4\n8"], "sample_outputs": ["3\n2\n4", "13\n3\n8\n9"], "notes": "NoteThe first example is shown in the picture.In the second example the final array is [1,\u200912,\u20092,\u20098,\u20093,\u200911,\u20094,\u20099,\u20095,\u200913,\u20096,\u200910,\u20097]."}, "positive_code": [{"source_code": "\n\nobject dTask4 {\n import scala.io.StdIn.{readLine,readLong}\n\n def main(args: Array[String]): Unit = {\n val n::q::Nil = readLine.split(\" \").map(_.toLong).toList\n def getNum(x: Long): Long = {\n if((x & 1) == 0) getNum(x/2 + n)\n else (x + 1) / 2\n }\n val arr = (0 until q.toInt).map(_ => readLong)\n println(arr.map(x => getNum(x)).mkString(\"\\n\"))\n }\n}\n"}], "negative_code": [], "src_uid": "756866daf45951854d5400b209af3bb0"} {"nl": {"description": "A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le k \\le n \\le 3 \\cdot 10^5$$$, $$$k$$$ is even) \u00a0\u2014 the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.", "sample_inputs": ["9\n6 4\n100110\n3 2\n1?1\n3 2\n1?0\n4 4\n????\n7 4\n1?0??1?\n10 10\n11??11??11\n4 2\n1??1\n4 4\n?0?0\n6 2\n????00"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES\nNO\nNO\nYES\nNO"], "notes": "NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110."}, "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 Array(n, k) = readLine().split(\" \").map(_.toInt)\n val sn = readLine()\n\n def isBalanced: Boolean = {\n var mk = Array.fill(k)('?')\n\n @annotation.tailrec\n def go(i: Int): Boolean =\n if (i == n) true\n else if (sn(i) == '?') go(i + 1)\n else if (mk(i % k) == '?') {\n mk(i % k) = sn(i)\n go(i + 1)\n } else mk(i % k) == sn(i) && go(i + 1)\n\n go(0) && mk.count(_ == '1') <= k / 2 && mk.count(_ == '0') <= k / 2\n }\n\n val ans = isBalanced match {\n case true => \"YES\"\n case _ => \"NO\"\n }\n\n println(ans)\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 Array(n, k) = readLine().split(\" \").map(_.toInt)\n val sn = readLine()\n\n def isBalanced: Boolean = {\n var mk = Array.fill(k)('?')\n\n @annotation.tailrec\n def go(i: Int): Boolean =\n if (i == n) true\n else if (mk(i % k) == '?') {\n mk(i % k) = sn(i)\n go(i + 1)\n } else mk(i % k) == sn(i) && go(i + 1)\n\n go(0) && {\n mk.count(_ == '1') <= k / 2 && mk.count(_ == '0') <= k / 2\n }\n }\n\n val ans = isBalanced match {\n case true => \"YES\"\n case _ => \"NO\"\n }\n\n println(ans)\n }\n}\n"}], "src_uid": "8e448883014bf7cd35fcca3fe0128af0"} {"nl": {"description": "There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i\u2009+\u20091)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i\u2009-\u20091)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s,\u2009t by looking at the footprints.", "input_spec": "The first line of the input contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u20091000). The second line contains the description of the road \u2014 the string that consists of n characters. Each character will be either \".\" (a block without footprint), or \"L\" (a block with a left footprint), \"R\" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to \".\". Also, the first and the last character will always be \".\". It's guaranteed that a solution exists.", "output_spec": "Print two space-separated integers \u2014 the values of s and t. If there are several possible solutions you can print any of them.", "sample_inputs": ["9\n..RRLL...", "11\n.RRRLLLLL.."], "sample_outputs": ["3 4", "7 5"], "notes": "NoteThe first test sample is the one in the picture."}, "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": "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}"}, {"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"} {"nl": {"description": "You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways: set (assign) $$$a := |a - b|$$$; set (assign) $$$b := |a - b|$$$, where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \\le a, b, x \\le 10^{18}$$$).", "output_spec": "For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.", "sample_inputs": ["8\n6 9 3\n15 38 7\n18 8 8\n30 30 30\n40 50 90\n24 28 20\n365 216 52\n537037812705867558 338887693834423551 3199921013340"], "sample_outputs": ["YES\nYES\nYES\nYES\nNO\nYES\nYES\nYES"], "notes": null}, "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 maxn = 10010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val a = readLong()\n val b = readLong()\n val k = readLong()\n def find(x: Long, y: Long): String = {\n if (x < k && y < k) {\n return \"NO\"\n }\n if (x == k || y == k) {\n return \"YES\"\n }\n if (x == 0 || y == 0) {\n return \"NO\"\n }\n if (x > y) {\n if (x % y == k % y)\n return \"YES\"\n else\n return find(x%y, y)\n } else {\n if (y % x == k % x)\n return \"YES\"\n else\n return find(y%x, x)\n }\n }\n writer.println(find(a, b))\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "7e23e222ce40547ed8a4f7f1372082d9"} {"nl": {"description": "The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.Let's consider a rectangular image that is represented with a table of size n\u2009\u00d7\u2009m. The table elements are integers that specify the brightness of each pixel in the image.A feature also is a rectangular table of size n\u2009\u00d7\u2009m. Each cell of a feature is painted black or white.To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W\u2009-\u2009B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.Some examples of the most popular Haar features are given below. Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values \u200b\u200bat any prefix rectangle, multiply it by any integer and add to variable value.You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of rows and columns in the feature. Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to \"W\", if this element of the feature is white and \"B\" if it is black.", "output_spec": "Print a single number \u2014 the minimum number of operations that you need to make to calculate the value of the feature.", "sample_inputs": ["6 8\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW", "3 3\nWBW\nBWW\nWWW", "3 6\nWWBBWW\nWWBBWW\nWWBBWW", "4 4\nBBBB\nBBBB\nBBBB\nBBBW"], "sample_outputs": ["2", "4", "3", "4"], "notes": "NoteThe first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6\u2009\u00d7\u20098 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations: add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame); add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient \u2009-\u20092 and variable value. Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1\u2009-\u20092\u2009=\u2009\u2009-\u20091, as required."}, "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": "// 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}"}, {"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"} {"nl": {"description": "All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.Treasure Island may be represented as a rectangular table $$$n \\times m$$$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $$$1$$$ to $$$n$$$ from top to bottom and columns with consecutive integers from $$$1$$$ to $$$m$$$ from left to right. Denote the cell in $$$r$$$-th row and $$$c$$$-th column as $$$(r, c)$$$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $$$(n, m)$$$.Vasya got off the ship in cell $$$(1, 1)$$$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $$$(x, y)$$$ he can move only to cells $$$(x+1, y)$$$ and $$$(x, y+1)$$$. Of course Vasya can't move through cells with impassable forests.Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $$$(1, 1)$$$ where Vasya got off his ship and $$$(n, m)$$$ where the treasure is hidden.Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.", "input_spec": "First line of input contains two positive integers $$$n$$$, $$$m$$$ ($$$3 \\le n \\cdot m \\le 1\\,000\\,000$$$), sizes of the island. Following $$$n$$$ lines contains strings $$$s_i$$$ of length $$$m$$$ describing the island, $$$j$$$-th character of string $$$s_i$$$ equals \"#\" if cell $$$(i, j)$$$ contains an impassable forest and \".\" if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell $$$(1, 1)$$$, i.e. the first cell of the first row, and he wants to reach cell $$$(n, m)$$$, i.e. the last cell of the last row. It's guaranteed, that cells $$$(1, 1)$$$ and $$$(n, m)$$$ are empty.", "output_spec": "Print the only integer $$$k$$$, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.", "sample_inputs": ["2 2\n..\n..", "4 4\n....\n#.#.\n....\n.#..", "3 4\n....\n.##.\n...."], "sample_outputs": ["2", "1", "2"], "notes": "NoteThe following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from $$$(1, 1)$$$ to $$$(n, m)$$$. Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from $$$(1, 1)$$$ to $$$(n, m)$$$ impossible. "}, "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 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"}, {"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"} {"nl": {"description": "One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect \u2013 it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated \u2013 it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly: It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.", "input_spec": "The first line of the input contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a\u2002b it connects (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n, a\u2009\u2260\u2009b).", "output_spec": "The output consists of one line, containing either yes or no depending on whether the nervous system is valid.", "sample_inputs": ["4 4\n1 2\n2 3\n3 1\n4 1", "6 5\n1 2\n2 3\n3 4\n4 5\n3 6"], "sample_outputs": ["no", "yes"], "notes": null}, "positive_code": [{"source_code": "/**\n * Created by John Compitello on 7/25/16.\n */\nobject Easy {\n def main(args: Array[String]): Unit = {\n val lines: Array[String] = (for (ln <- io.Source.stdin.getLines) yield ln).toArray\n val line0: Array[Int] = lines(0).split(\" \").map(_ toInt)\n val (numBrains, numConnectors): (Int, Int) = (line0(0), line0(1))\n\n if(numConnectors != numBrains - 1) {\n println(\"no\")\n }\n else {\n val connectionList: List[(Int, Int)] = (for {\n connection <- 1 to numConnectors\n tempArray: Array[Int] = lines(connection).split(\" \").map(x => x.toInt - 1)\n } yield (tempArray(0), tempArray(1))).toList\n\n\n val uf: UnionFind = new UnionFind(Vector.tabulate(numBrains)(x => x))\n val betterUf = connectionList.foldLeft(uf)((tempUf, pair) => tempUf.union(pair._1, pair._2))\n\n val rootList: List[Int] = (0 until numBrains).map(betterUf.root(_)) toList\n val bool: Boolean = rootList.forall(_ == rootList.head)\n\n if (bool) print(\"yes\") else print(\"no\")\n }\n }\n}\n\n\nclass UnionFind(val vect: Vector[Int]) {\n\n def root(n : Int): Int = {\n val pointsTo: Int = vect(n)\n if(n == pointsTo) n else root(pointsTo)\n }\n\n def union(a: Int, b: Int): UnionFind = {\n //Make it so that a's root points to b's root.\n val aRoot = root(a)\n val bRoot = root(b)\n new UnionFind(vect.updated(aRoot, bRoot))\n }\n}\n"}], "negative_code": [], "src_uid": "f0c91ae53d5b4fc8019f6a3294978398"} {"nl": {"description": "You are playing a game on a $$$n \\times m$$$ grid, in which the computer has selected some cell $$$(x, y)$$$ of the grid, and you have to determine which one. To do so, you will choose some $$$k$$$ and some $$$k$$$ cells $$$(x_1, y_1),\\, (x_2, y_2), \\ldots, (x_k, y_k)$$$, and give them to the computer. In response, you will get $$$k$$$ numbers $$$b_1,\\, b_2, \\ldots b_k$$$, where $$$b_i$$$ is the manhattan distance from $$$(x_i, y_i)$$$ to the hidden cell $$$(x, y)$$$ (so you know which distance corresponds to which of $$$k$$$ input cells). After receiving these $$$b_1,\\, b_2, \\ldots, b_k$$$, you have to be able to determine the hidden cell. What is the smallest $$$k$$$ for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?As a reminder, the manhattan distance between cells $$$(a_1, b_1)$$$ and $$$(a_2, b_2)$$$ is equal to $$$|a_1-a_2|+|b_1-b_2|$$$.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The description of test cases follows. The single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^9$$$)\u00a0\u2014 the number of rows and the number of columns in the grid.", "output_spec": "For each test case print a single integer\u00a0\u2014 the minimum $$$k$$$ for that test case.", "sample_inputs": ["2\n2 3\n3 1"], "sample_outputs": ["2\n1"], "notes": "NoteIn the first test case, the smallest such $$$k$$$ is $$$2$$$, for which you can choose, for example, cells $$$(1, 1)$$$ and $$$(2, 1)$$$.Note that you can't choose cells $$$(1, 1)$$$ and $$$(2, 3)$$$ for $$$k = 2$$$, as both cells $$$(1, 2)$$$ and $$$(2, 1)$$$ would give $$$b_1 = 1, b_2 = 2$$$, so we wouldn't be able to determine which cell is hidden if computer selects one of those.In the second test case, you should choose $$$k = 1$$$, for it you can choose cell $$$(3, 1)$$$ or $$$(1, 1)$$$."}, "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 Main2 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, c: Double)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (b == that.b)\n return -1 * c.compareTo(that.c)\n else\n return -1 * b.compareTo(that.b)\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 for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n if (n == 1 && m == 1)\n writer.println(0)\n else if (m == 1 || n == 1)\n writer.println(1)\n else\n writer.println(2)\n }\n writer.flush()\n}\n"}], "negative_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 Main2 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, c: Double)extends Ordered[pair] {\n override def compare(that: pair): Int = {\n if (b == that.b)\n return -1 * c.compareTo(that.c)\n else\n return -1 * b.compareTo(that.b)\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 for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n if (n == 1 && m == 1)\n writer.println(0)\n else\n writer.println(min(n, m))\n }\n writer.flush()\n}\n"}], "src_uid": "e5a01ebfdca3af987e93b68c96268c16"} {"nl": {"description": "The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of eggs. Next n lines contain two integers ai and gi each (0\u2009\u2264\u2009ai,\u2009gi\u2009\u2264\u20091000;\u00a0ai\u2009+\u2009gi\u2009=\u20091000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.", "output_spec": "If it is impossible to assign the painting, print \"-1\" (without quotes). Otherwise print a string, consisting of n letters \"G\" and \"A\". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter \"A\" represents A. and letter \"G\" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa\u2009\u2009-\u2009\u2009Sg|\u2009\u2009\u2264\u2009\u2009500. If there are several solutions, you are allowed to print any of them.", "sample_inputs": ["2\n1 999\n999 1", "3\n400 600\n400 600\n400 600"], "sample_outputs": ["AG", "AGA"], "notes": null}, "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(_ => 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}"}, {"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"}, {"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 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}"}], "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"} {"nl": {"description": "Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns \u2014 from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i,\u2009j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk,\u2009yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!", "input_spec": "The first line of the input contains fix integers n, m, x, y, z, p (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009109;\u00a00\u2009\u2264\u2009x,\u2009y,\u2009z\u2009\u2264\u2009109;\u00a01\u2009\u2264\u2009p\u2009\u2264\u2009105). Each of the following p lines contains two integers xk, yk (1\u2009\u2264\u2009xk\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009yk\u2009\u2264\u2009m) \u2014 the initial coordinates of the k-th candy. Two candies can lie on the same cell.", "output_spec": "For each of the p candies, print on a single line its space-separated new coordinates.", "sample_inputs": ["3 3 3 1 1 9\n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3"], "sample_outputs": ["1 3\n1 2\n1 1\n2 3\n2 2\n2 1\n3 3\n3 2\n3 1"], "notes": "NoteJust for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER REWQ ASDF -> FDSAZXCV VCXZ"}, "positive_code": [{"source_code": "import java.util.Scanner\nimport scala.collection.immutable.HashSet\n\n/**\n * Created by hama_du on 2014/02/24.\n */\nobject ProblemC extends App {\n val in = new Scanner(System.in)\n\n val n,m,x,y,z,p = in.nextInt()\n (0 until p).foreach(_ => {\n val i,j = in.nextInt()\n val newPosition = convert((n,m),(x%4,y%2,z%4),(i-1,j-1))\n println((newPosition._1+1) + \" \" + (newPosition._2+1))\n })\n\n def convert(mat:(Int,Int), ops:(Int,Int,Int), from:(Int,Int)): (Int,Int) = {\n val stat1 = (0 until ops._1).foldLeft((mat,from))((a,b) => convert90(a))\n val stat2 = (0 until ops._2).foldLeft(stat1)((a,b) => convertHFlip(a))\n val stat3 = (0 until ops._3).foldLeft(stat2)((a,b) => convert270(a))\n stat3._2\n }\n\n // ((n,m),(y,x)) => ((m,n),(y',x'))\n def convert90(state:((Int,Int),(Int,Int))): ((Int,Int),(Int,Int)) = {\n val map = state._1\n val pos = state._2\n ((map._2,map._1),(pos._2,map._1-pos._1-1))\n }\n\n def convertHFlip(state:((Int,Int),(Int,Int))): ((Int,Int),(Int,Int)) = {\n val map = state._1\n val pos = state._2\n ((map._1,map._2),(pos._1,map._2-pos._2-1))\n }\n\n def convert270(state:((Int,Int),(Int,Int))): ((Int,Int),(Int,Int)) = {\n val map = state._1\n val pos = state._2\n ((map._2,map._1),(map._2-pos._2-1,pos._1))\n }\n}\n"}], "negative_code": [], "src_uid": "14a56443e48c52c118788bd5c0031b0c"} {"nl": {"description": "You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character \"0\" and \"1\") a and b. Then you try to turn a into b using two types of operations: Write parity(a) to the end of a. For example, . Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of \"1\"s in the string, and 0 otherwise.", "input_spec": "The first line contains the string a and the second line contains the string b (1\u2009\u2264\u2009|a|,\u2009|b|\u2009\u2264\u20091000). Both strings contain only the characters \"0\" and \"1\". Here |x| denotes the length of the string x.", "output_spec": "Print \"YES\" (without quotes) if it is possible to turn a into b, and \"NO\" (without quotes) otherwise.", "sample_inputs": ["01011\n0110", "0011\n1110"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, the steps are as follows: 01011\u2009\u2192\u20091011\u2009\u2192\u2009011\u2009\u2192\u20090110"}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "cf86add6c92fa8a72b8e23efbdb38613"} {"nl": {"description": "Polycarp has $$$n$$$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: \"0001\", \"11\", \"0\" and \"0011100\".Polycarp wants to offer his set of $$$n$$$ binary words to play a game \"words\". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: \"0101\", \"1\", \"10\", \"00\", \"00001\".Word reversal is the operation of reversing the order of the characters. For example, the word \"0111\" after the reversal becomes \"1110\", the word \"11010\" after the reversal becomes \"01011\".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that: the final set of $$$n$$$ words still contains different words (i.e. all words are unique); there is a way to put all words of the final set of words in the order so that the final sequence of $$$n$$$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) \u2014 the number of words in the Polycarp's set. Next $$$n$$$ lines contain these words. All of $$$n$$$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $$$4\\cdot10^6$$$. All words are different. Guaranteed, that the sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\\cdot10^5$$$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $$$4\\cdot10^6$$$.", "output_spec": "Print answer for all of $$$t$$$ test cases in the order they appear. If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $$$k$$$ ($$$0 \\le k \\le n$$$) \u2014 the minimal number of words in the set which should be reversed. The second line of the output should contain $$$k$$$ distinct integers \u2014 the indexes of the words in the set which should be reversed. Words are numerated from $$$1$$$ to $$$n$$$ in the order they appear. If $$$k=0$$$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them.", "sample_inputs": ["4\n4\n0001\n1000\n0011\n0111\n3\n010\n101\n0\n2\n00000\n00001\n4\n01\n001\n0001\n00001"], "sample_outputs": ["1\n3 \n-1\n0\n\n2\n1 2"], "notes": null}, "positive_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 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 }"}, {"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"} {"nl": {"description": "There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met: there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$; pillar $$$i$$$ contains exactly one disk; either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?", "input_spec": "The first line contains one integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of pillars. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_i$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the radius of the disk initially placed on the $$$i$$$-th pillar. All numbers $$$a_i$$$ are distinct.", "output_spec": "Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).", "sample_inputs": ["4\n1 3 4 2", "3\n3 1 2"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first case it is possible to place all disks on pillar $$$3$$$ using the following sequence of actions: take the disk with radius $$$3$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$; take the disk with radius $$$1$$$ from pillar $$$1$$$ and place it on top of pillar $$$2$$$; take the disk with radius $$$2$$$ from pillar $$$4$$$ and place it on top of pillar $$$3$$$; take the disk with radius $$$1$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$. "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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) // \u5358\u8abf\u5897\u52a0\n i -= 1\n }\n i = p + 1\n while(i < N) {\n ok &&= A(i) < A(i - 1) // \u5358\u8abf\u6e1b\u5c11\n i += 1\n }\n if (ok) out.println(\"YES\")\n else out.println(\"NO\")\n }\n}"}, {"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"}], "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"} {"nl": {"description": "Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.", "input_spec": "The first line of the input contains one integer, n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive. ", "output_spec": "Print the maximum possible even sum that can be obtained if we use some of the given integers. ", "sample_inputs": ["3\n1 2 3", "5\n999999999 999999999 999999999 999999999 999999999"], "sample_outputs": ["6", "3999999996"], "notes": "NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999\u2009999\u2009999."}, "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 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"}, {"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"} {"nl": {"description": "You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string \"[[(){}]<>]\" is RBS, but the strings \"[)()\" and \"][()()\" are not.Determine the least number of replaces to make the string s RBS.", "input_spec": "The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.", "output_spec": "If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.", "sample_inputs": ["[<}){}", "{()}[]", "]]"], "sample_outputs": ["2", "0", "Impossible"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x\u2009<\u2009y) from the set, such that y\u2009=\u2009x\u00b7k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109). The next line contains a list of n distinct positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). All the numbers in the lines are separated by single spaces.", "output_spec": "On the only line of the output print the size of the largest k-multiple free subset of {a1,\u2009a2,\u2009...,\u2009an}.", "sample_inputs": ["6 2\n2 3 6 5 4 10"], "sample_outputs": ["3"], "notes": "NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}."}, "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(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}"}, {"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} "}, {"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"}], "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"} {"nl": {"description": "There are $$$n$$$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $$$1$$$ to $$$n$$$.Two fairs are currently taking place in Berland \u2014 they are held in two different cities $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le n$$$; $$$a \\ne b$$$).Find the number of pairs of cities $$$x$$$ and $$$y$$$ ($$$x \\ne a, x \\ne b, y \\ne a, y \\ne b$$$) such that if you go from $$$x$$$ to $$$y$$$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $$$x,y$$$ such that any path from $$$x$$$ to $$$y$$$ goes through $$$a$$$ and $$$b$$$ (in any order).Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $$$(x,y)$$$ and $$$(y,x)$$$ must be taken into account only once.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 4\\cdot10^4$$$) \u2014 the number of test cases in the input. Next, $$$t$$$ test cases are specified. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$4 \\le n \\le 2\\cdot10^5$$$, $$$n - 1 \\le m \\le 5\\cdot10^5$$$, $$$1 \\le a,b \\le n$$$, $$$a \\ne b$$$) \u2014 numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively. The following $$$m$$$ lines contain descriptions of roads between cities. Each of road description contains a pair of integers $$$u_i, v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$) \u2014 numbers of cities connected by the road. Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities. The sum of the values of $$$n$$$ for all sets of input data in the test does not exceed $$$2\\cdot10^5$$$. The sum of the values of $$$m$$$ for all sets of input data in the test does not exceed $$$5\\cdot10^5$$$.", "output_spec": "Print $$$t$$$ integers \u2014 the answers to the given test cases in the order they are written in the input.", "sample_inputs": ["3\n7 7 3 5\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 5\n4 5 2 3\n1 2\n2 3\n3 4\n4 1\n4 2\n4 3 2 1\n1 2\n2 3\n4 1"], "sample_outputs": ["4\n0\n1"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n, m, a, b = nextInt\n val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)\n for (_ <- 1 to m) {\n val u, v = nextInt - 1\n adjBuilders(u) += v\n adjBuilders(v) += u\n }\n val adjs = adjBuilders.map(_.result())\n\n def bfs(u0: Int, block: Int): Long = {\n val que = new java.util.ArrayDeque[Int]\n val visited = mutable.BitSet(n)\n visited(u0) = true\n que.add(u0)\n while (!que.isEmpty) {\n val u = que.pollFirst()\n if (u != block) {\n var i = 0\n while (i < adjs(u).length) {\n val v = adjs(u)(i)\n if (!visited(v)) {\n visited += v\n que.add(v)\n }\n i += 1\n }\n }\n }\n var i = 0\n var count = 0L\n while (i < n) {\n if (!visited(i)) count += 1\n i += 1\n }\n count\n }\n\n val c1 = bfs(a - 1, b - 1)\n val c2 = bfs(b - 1, a - 1)\n out.println(c1 * c2)\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": "7636c493ad91210ec7571895b4b71214"} {"nl": {"description": "Mihai has just learned about the MEX concept and since he liked it so much, he decided to use it right away.Given an array $$$a$$$ of $$$n$$$ non-negative integers, Mihai wants to create a new array $$$b$$$ that is formed in the following way:While $$$a$$$ is not empty: Choose an integer $$$k$$$ ($$$1 \\leq k \\leq |a|$$$). Append the MEX of the first $$$k$$$ numbers of the array $$$a$$$ to the end of array $$$b$$$ and erase them from the array $$$a$$$, shifting the positions of the remaining numbers in $$$a$$$. But, since Mihai loves big arrays as much as the MEX concept, he wants the new array $$$b$$$ to be the lexicographically maximum. So, Mihai asks you to tell him what the maximum array $$$b$$$ that can be created by constructing the array optimally is.An array $$$x$$$ is lexicographically greater than an array $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ $$$x_i > y_i$$$ or if $$$|x| > |y|$$$ and $$$y$$$ is a prefix of $$$x$$$ (where $$$|x|$$$ denotes the size of the array $$$x$$$).The MEX of a set of non-negative integers is the minimal non-negative integer such that it is not in the set. For example, MEX({$$${1, 2, 3}$$$}) $$$= 0$$$ and MEX({$$${0, 1, 2, 4, 5}$$$}) $$$= 3$$$.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) \u2014 the number of elements in the array $$$a$$$. The second line of each test case contains $$$n$$$ non-negative integers $$$a_1, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq n$$$), where $$$a_i$$$ is the $$$i$$$-th integer from the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print $$$m$$$ \u2014 the length of the maximum array $$$b$$$ Mihai can create, followed by $$$m$$$ integers denoting the elements of the array $$$b$$$.", "sample_inputs": ["6\n5\n1 0 2 0 3\n8\n2 2 3 4 0 1 2 0\n1\n1\n5\n0 1 2 3 4\n4\n0 1 1 0\n10\n0 0 2 1 1 1 0 0 1 1"], "sample_outputs": ["1\n4 \n2\n5 1 \n1\n0 \n1\n5 \n2\n2 2 \n4\n3 2 2 0"], "notes": "NoteIn the first test case, the lexicographically maximum array $$$b$$$ is obtained by selecting $$$k=5$$$, resulting in the $$$MEX$$$ of the whole array $$$a$$$. It is lexicographically maximum because an array starting with a smaller number than $$$4$$$ is lexicographically smaller, and choosing a $$$k<5$$$ would result in an array starting with a number smaller than $$$4$$$.In the second test case, there are two ways to obtain the maximum array: first selecting $$$k=6$$$, then $$$k=2$$$, or first selecting $$$k=7$$$ and then $$$k=1$$$."}, "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 arr = new Array[Int](n+2)\n val cnt = new Array[Int](n+2)\n var ans = Vector[Int]()\n for (i <- 1 to n) {\n arr(i) = readInt()\n cnt(arr(i)) += 1\n }\n var k = 0\n while (cnt(k) != 0) {\n k += 1\n }\n val mark = new Array[Boolean](n+2)\n var tmp = 0\n var po = 1\n var newk = k\n\n while (po <= n && k > 0) {\n tmp = -1\n while (tmp < k) {\n if (!mark(arr(po)) && arr(po) <= k) {\n mark(arr(po)) = true\n if (tmp == -1)\n tmp = 1\n else\n tmp += 1\n }\n cnt(arr(po)) -= 1\n if (cnt(arr(po)) == 0) {\n newk = min(newk, arr(po))\n }\n po += 1\n }\n for (i <- 0 to newk) {\n mark(i) = false\n }\n ans :+= k\n k = newk\n }\n while (po <= n) {\n ans :+= 0\n po += 1\n }\n writer.println(ans.length)\n for (m <- ans) {\n writer.print(m + \" \")\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}"}], "negative_code": [], "src_uid": "962c4354c936030da78261871dd6d55b"} {"nl": {"description": "As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define a correct bracket sequence as follows: An empty sequence is a correct bracket sequence. If {a1,\u2009a2,\u2009...,\u2009al} and {b1,\u2009b2,\u2009...,\u2009bk} are correct bracket sequences, then sequence {a1,\u2009a2,\u2009...,\u2009al,\u2009b1,\u2009b2,\u2009...,\u2009bk} (their concatenation) also is a correct bracket sequence. If {a1,\u2009a2,\u2009...,\u2009al} \u2014 is a correct bracket sequence, then sequence also is a correct bracket sequence, where v (v\u2009>\u20090) is an integer. For example, sequences {1,\u20091,\u2009\u2009-\u20091,\u20092,\u2009\u2009-\u20092,\u2009\u2009-\u20091} and {3,\u2009\u2009-\u20093} are correct bracket sequences, and {2,\u2009\u2009-\u20093} is not.Moreover, after Vova became a shaman, he learned the most important correct bracket sequence {x1,\u2009x2,\u2009...,\u2009xn}, consisting of n integers. As sequence x is the most important, Vova decided to encrypt it just in case.Encrypting consists of two sequences. The first sequence {p1,\u2009p2,\u2009...,\u2009pn} contains types of brackets, that is, pi\u2009=\u2009|xi| (1\u2009\u2264\u2009i\u2009\u2264\u2009n). The second sequence {q1,\u2009q2,\u2009...,\u2009qt} contains t integers \u2014 some positions (possibly, not all of them), which had negative numbers in sequence {x1,\u2009x2,\u2009...,\u2009xn}.Unfortunately, Vova forgot the main sequence. But he was lucky enough to keep the encryption: sequences {p1,\u2009p2,\u2009...,\u2009pn} and {q1,\u2009q2,\u2009...,\u2009qt}. Help Vova restore sequence x by the encryption. If there are multiple sequences that correspond to the encryption, restore any of them. If there are no such sequences, you should tell so.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106). The second line contains n integers: p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009109). The third line contains integer t (0\u2009\u2264\u2009t\u2009\u2264\u2009n), followed by t distinct integers q1,\u2009q2,\u2009...,\u2009qt (1\u2009\u2264\u2009qi\u2009\u2264\u2009n). The numbers in each line are separated by spaces.", "output_spec": "Print a single string \"NO\" (without the quotes) if Vova is mistaken and a suitable sequence {x1,\u2009x2,\u2009...,\u2009xn} doesn't exist. Otherwise, in the first line print \"YES\" (without the quotes) and in the second line print n integers x1,\u2009x2,\u2009...,\u2009xn (|xi|\u2009=\u2009pi;\u00a0xqj\u2009<\u20090). If there are multiple sequences that correspond to the encrypting, you are allowed to print any of them.", "sample_inputs": ["2\n1 1\n0", "4\n1 1 1 1\n1 3", "3\n1 1 1\n0", "4\n1 2 2 1\n2 3 4"], "sample_outputs": ["YES\n1 -1", "YES\n1 1 -1 -1", "NO", "YES\n1 2 -2 -1"], "notes": null}, "positive_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 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 \"\"\"2\n |1 1\n |0\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 ps = input.next().split(\" \").map(_.toInt)\n val qs = input.next().split(\" \").drop(1).map(_.toInt - 1)\n // val ps = (0 until 10000).map(i => 1)\n // val qs = Set.empty[Int]\n\n /** algorithm **/ ptime()\n\n /// copied... still don't know why greedy works\n\n qs.foreach(q => {\n val p = ps(q)\n ps(q) = -p\n })\n\n\n var i = ps.size - 1\n var stack = List.empty[Int]\n\n while (i >= 0) {\n val p = ps(i)\n if (p < 0) {\n stack = p +: stack\n i = i - 1\n } else {\n val valid = stack.nonEmpty && stack.head == -p\n if (valid) {\n stack = stack.tail\n i = i - 1\n } else {\n stack = -p +: stack\n ps(i) = -p\n i = i - 1\n }\n }\n }\n\n val sol = if (stack.isEmpty) {\n Some(ps)\n } else {\n None\n }\n\n // val sol = found.map(list => {\n // val m = list.toSet\n // ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)\n // })\n\n\n //// non-recursive one... but didn't not work, I need to know why the greedy one worked\n // var i = 0\n // var stack: Seq[Int] = List.empty\n // var comm: Seq[Int] = List.empty\n // var alternatives: Seq[() => Unit] = List.empty\n //\n // var found: Option[Seq[Int]] = None\n // var finished = false\n //\n //\n // def goBack() = {\n // if (alternatives.isEmpty) {\n // finished = true\n // } else {\n // val head = alternatives.head\n // alternatives = alternatives.tail\n // head()\n // }\n // }\n // while (!finished) {\n // while (i < ps.size) {\n // if (stack.size > ps.size - i) {\n // goBack()\n // } else {\n // val p = ps(i)\n // val q = qs(i)\n // if (q) {\n // if (stack.nonEmpty && p == stack.head) {\n // comm = i +: comm\n // i = i + 1\n // stack = stack.tail\n // } else {\n // goBack()\n // }\n // } else {\n // val valid = stack.nonEmpty && p == stack.head\n // if (valid) {\n // val cc = comm\n // val ss = p +: stack\n // val ii = i + 1\n // alternatives = (() => {\n // comm = cc\n // stack = ss\n // i = ii\n // }) +: alternatives\n // comm = i +: comm\n // i = i + 1\n // stack = stack.tail\n //// val cc = i +: comm\n //// val ii = i + 1\n //// val ss = stack.tail\n //// alternatives = (() => {\n //// i = ii\n //// stack = ss\n //// comm = cc\n //// }) +: alternatives\n // }\n // i = i + 1\n // stack = p +: stack\n // }\n // }\n // }\n // if (stack.isEmpty) {\n // found = Some(comm)\n // finished = true\n // } else {\n // goBack()\n // }\n // }\n //\n //\n\n\n //// recursive one, did not work\n\n // def rec(i: Int, stack: Seq[Int], comm: Seq[Int]): Option[Seq[Int]] = {\n // if (i == ps.length) {\n // if (stack.isEmpty) Some(comm)\n // else None\n // } else {\n // val p = ps(i)\n // val q = qs(i)\n // if (q) {\n // if (stack.nonEmpty && p == stack.head) {\n // rec(i + 1, stack.tail, i +: comm)\n // } else {\n // None\n // }\n // } else {\n // val valid = stack.nonEmpty && p == stack.head\n // if (valid) {\n // val k = rec(i + 1, stack.tail, i +: comm)\n // if (k.nonEmpty) return k\n // }\n // rec(i + 1, p +: stack, comm)\n // }\n // }\n // }\n\n /** print **/ ptime()\n\n// if (sol.isEmpty) {\n// println(\"NO\")\n// } else {\n// println(\"YES\")\n// val list = sol.get\n// var i = 0\n// while (i < list.size - 1) {\n// print(list(i))\n// print(\" \")\n// i += 1\n// }\n// println(list.last)\n// }\n println(sol.map(list => \"YES\\n\" + list.mkString(\" \")).getOrElse(\"NO\"))\n }\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 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 \"\"\"4\n |1 2 2 1\n |2 3 4\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 ps = input.next().split(\" \").map(_.toInt)\n val qs = input.next().split(\" \").drop(1).map(_.toInt - 1)\n // val ps = (0 until 10000).map(i => 1)\n // val qs = Set.empty[Int]\n\n /** algorithm **/ ptime()\n\n /// copied... still don't know why greedy works\n\n qs.foreach(q => {\n val p = ps(q)\n ps(q) = -p\n })\n\n\n var i = ps.size - 1\n var stack = List.empty[Int]\n\n while (i >= 0) {\n val p = ps(i)\n if (p < 0) {\n stack = p +: stack\n i = i - 1\n } else {\n val valid = stack.nonEmpty && stack.head == -p\n if (valid) {\n stack = stack.tail\n i = i - 1\n } else {\n stack = p +: stack\n ps(i) = -p\n i = i - 1\n }\n }\n }\n val sol = if (stack.isEmpty) {\n Some(ps)\n } else {\n None\n }\n\n // val sol = found.map(list => {\n // val m = list.toSet\n // ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)\n // })\n\n\n //// non-recursive one... but didn't not work, I need to know why the greedy one worked\n // var i = 0\n // var stack: Seq[Int] = List.empty\n // var comm: Seq[Int] = List.empty\n // var alternatives: Seq[() => Unit] = List.empty\n //\n // var found: Option[Seq[Int]] = None\n // var finished = false\n //\n //\n // def goBack() = {\n // if (alternatives.isEmpty) {\n // finished = true\n // } else {\n // val head = alternatives.head\n // alternatives = alternatives.tail\n // head()\n // }\n // }\n // while (!finished) {\n // while (i < ps.size) {\n // if (stack.size > ps.size - i) {\n // goBack()\n // } else {\n // val p = ps(i)\n // val q = qs(i)\n // if (q) {\n // if (stack.nonEmpty && p == stack.head) {\n // comm = i +: comm\n // i = i + 1\n // stack = stack.tail\n // } else {\n // goBack()\n // }\n // } else {\n // val valid = stack.nonEmpty && p == stack.head\n // if (valid) {\n // val cc = comm\n // val ss = p +: stack\n // val ii = i + 1\n // alternatives = (() => {\n // comm = cc\n // stack = ss\n // i = ii\n // }) +: alternatives\n // comm = i +: comm\n // i = i + 1\n // stack = stack.tail\n //// val cc = i +: comm\n //// val ii = i + 1\n //// val ss = stack.tail\n //// alternatives = (() => {\n //// i = ii\n //// stack = ss\n //// comm = cc\n //// }) +: alternatives\n // }\n // i = i + 1\n // stack = p +: stack\n // }\n // }\n // }\n // if (stack.isEmpty) {\n // found = Some(comm)\n // finished = true\n // } else {\n // goBack()\n // }\n // }\n //\n //\n\n\n //// recursive one, did not work\n\n // def rec(i: Int, stack: Seq[Int], comm: Seq[Int]): Option[Seq[Int]] = {\n // if (i == ps.length) {\n // if (stack.isEmpty) Some(comm)\n // else None\n // } else {\n // val p = ps(i)\n // val q = qs(i)\n // if (q) {\n // if (stack.nonEmpty && p == stack.head) {\n // rec(i + 1, stack.tail, i +: comm)\n // } else {\n // None\n // }\n // } else {\n // val valid = stack.nonEmpty && p == stack.head\n // if (valid) {\n // val k = rec(i + 1, stack.tail, i +: comm)\n // if (k.nonEmpty) return k\n // }\n // rec(i + 1, p +: stack, comm)\n // }\n // }\n // }\n\n /** print **/ ptime()\n\n if (sol.isEmpty) {\n println(\"NO\")\n } else {\n println(\"YES\")\n val list = sol.get\n var i = 0\n while (i < list.size - 1) {\n print(list(i))\n print(\" \")\n i += 1\n }\n println(list.last)\n }\n //println(sol.map(list => \"YES\\n\" + list.mkString(\" \")).getOrElse(\"NO\"))\n }\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 \"\"\"4\n |1 1 1 1\n |1 3\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 ps = input.next().split(\" \").map(_.toInt)\n val qs = input.next().split(\" \").drop(1).map(_.toInt - 1).toSet\n\n /** algorithm **/ ptime()\n\n\n def rec(i: Int, stack: Seq[Int]): Option[Seq[Int]] = {\n if (i == ps.length) {\n Some(List.empty[Int])\n } else {\n val p = ps(i)\n val q = qs(i)\n if (q) {\n if (stack.nonEmpty && p == stack.head) {\n rec(i + 1, stack.tail).map(l => i +: l)\n } else {\n None\n }\n } else {\n val valid = stack.nonEmpty && p == stack.head\n if (valid) {\n val k = rec(i + 1, stack.tail).map(l => i +: l)\n if (k.nonEmpty) return k\n }\n rec(i + 1, p +: stack)\n }\n }\n }\n\n val sol = rec(0, List.empty).map(list => {\n val m = list.toSet\n ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)\n })\n\n /** print **/ ptime()\n\n println(sol.map(list => \"YES\\n\" + list.mkString(\" \")).getOrElse(\"NO\"))\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 \"\"\"4\n |1 1 1 1\n |1 3\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 ps = input.next().split(\" \").map(_.toInt)\n val qs = input.next().split(\" \").drop(1).map(_.toInt - 1).toSet\n\n /** algorithm **/ ptime()\n\n\n def rec(i: Int, stack: Seq[Int]): Option[Seq[Int]] = {\n if (i == ps.length) {\n Some(List.empty[Int])\n } else {\n val p = ps(i)\n val q = qs(p)\n if (q) {\n if (stack.nonEmpty && p == stack.head) {\n rec(i + 1, stack.tail).map(l => i +: l)\n } else {\n None\n }\n } else {\n val valid = stack.nonEmpty && p == stack.head\n if (valid) {\n val k = rec(i + 1, stack.tail).map(l => i +: l)\n if (k.nonEmpty) return k\n }\n rec(i + 1, p +: stack)\n }\n }\n }\n\n val sol = rec(0, List.empty).map(list => {\n val m = list.toSet\n ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)\n })\n\n /** print **/ ptime()\n\n println(sol.map(list => \"YES\\n\" + list.mkString(\" \")).getOrElse(\"NO\"))\n }\n}"}], "src_uid": "be82b8f209217875221ebe5de8675971"} {"nl": {"description": "Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j]\u00a0(1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n) of array a\u2009=\u2009(a1,\u2009a2,\u2009...,\u2009an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j]\u2009=\u2009(ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj).", "input_spec": "The first line contains two space-separated integers n, k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20094\u00b7105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the array.", "output_spec": "Print the single number \u2014 the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. In is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4 2\n1 2 1 2", "5 3\n1 2 1 1 3", "3 1\n1 1 1"], "sample_outputs": ["3", "2", "6"], "notes": "NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1)."}, "positive_code": [{"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def solve(arr: Array[Int], k: Int): Long = {\n val map = new HashMap[Int, ArrayBuffer[Int]]()\n for (i <- 0 until arr.length) {\n map.getOrElseUpdate(arr(i), new ArrayBuffer[Int]).append(i)\n }\n\n var minRight = Array.fill(arr.length)(arr.length)\n for ((key, offsets) <- map) {\n for (i <- 0 to offsets.length-k) {\n minRight(offsets(i)) = offsets(i+k-1)\n }\n }\n\n minRight = minRight.scanRight(minRight.length)(_ min _)\n minRight.map(arr.length - _.toLong).sum\n }\n\n def main(args: Array[String]) {\n val k = readLine().split(\" \")(1).toInt\n val arr = readLine().split(\" \").map(_.toInt)\n println(solve(arr, k))\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def solve(arr: Array[Int], k: Int): Long = {\n val map = new HashMap[Int, ArrayBuffer[Int]]()\n for (i <- 0 until arr.length) {\n map.getOrElseUpdate(arr(i), ArrayBuffer(i)).append(i)\n }\n\n var minRight = Array.fill(arr.length)(arr.length)\n for ((key, offsets) <- map) {\n for (i <- 0 to offsets.length-k) {\n minRight(offsets(i)) = offsets(i+k-1)\n }\n }\n\n minRight = minRight.scanRight(minRight.length)(_ min _)\n minRight.map(arr.length - _.toLong).sum\n }\n\n def main(args: Array[String]) {\n val k = readLine().split(\" \")(1).toInt\n val arr = readLine().split(\" \").map(_.toInt)\n println(solve(arr, k))\n }\n}\n"}, {"source_code": "import scala.collection.mutable._\n\nobject Solution {\n def solve(arr: Array[Int], k: Int): Long = {\n val map = new HashMap[Int, ArrayBuffer[Int]]()\n for (i <- 0 until arr.length) {\n val x = arr(i)\n if (map.get(x).isEmpty) {\n map.put(x, new ArrayBuffer[Int])\n }\n map.get(x).get.append(i)\n }\n\n var minRight = Array.ofDim[Int](arr.length)\n for (i <- 0 until minRight.length) {\n minRight(i) = minRight.length\n }\n\n for ((key, value) <- map) {\n for (i <- 0 to value.length-k) {\n minRight(value(i)) = minRight(value(i)) min value(i+k-1)\n }\n }\n\n var ans: Long = 0;\n for (i <- 0 until minRight.length) {\n val j = minRight.length-i-1\n if (i > 0) {\n minRight(j) = minRight(j) min minRight(j+1)\n }\n ans += arr.length - minRight(i)\n }\n ans\n }\n\n def main(args: Array[String]) {\n val k = readLine().split(\" \")(1).toInt\n val arr = readLine().split(\" \").map(_.toInt)\n println(solve(arr, k))\n }\n}\n"}], "src_uid": "5346698abe40ce0477f743779da7c725"} {"nl": {"description": "You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009|s|) of string s\u2009\u2009=\u2009\u2009s1s2...s|s| (where |s| is the length of string s) is string \u2009slsl\u2009+\u20091...sr.The substring s[l...r] is good, if among the letters \u2009sl,\u2009sl\u2009+\u20091,\u2009...,\u2009sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y]\u2009\u2260\u2009s[p...q].", "input_spec": "The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters \"0\" and \"1\", the length is exactly 26 characters. If the i-th character of this string equals \"1\", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter \"a\", the second one corresponds to letter \"b\" and so on. The third line of the input consists a single integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009|s|) \u2014 the maximum acceptable number of bad characters in a good substring.", "output_spec": "Print a single integer \u2014 the number of distinct good substrings of string s.", "sample_inputs": ["ababab\n01000000000000000000000000\n1", "acbacbacaa\n00000000000000000000000000\n2"], "sample_outputs": ["5", "8"], "notes": "NoteIn the first example there are following good substrings: \"a\", \"ab\", \"b\", \"ba\", \"bab\".In the second example there are following good substrings: \"a\", \"aa\", \"ac\", \"b\", \"ba\", \"c\", \"ca\", \"cb\"."}, "positive_code": [{"source_code": "\n\nobject test5 extends App {\n val s=readLine\n val table=readLine.map(c=> if(c=='0') false else true) toArray\n val k=readInt\n val trie=new Trie(table,k)\n \n for(i<-0 until s.length){\n trie.insert(s,i)\n }\n println(trie.count)\n} \n\nclass Node{\n val children=new Array[Node](26)\n}\n\nclass Trie(table:Array[Boolean], k:Int){\n val root=new Node\n var count=0\n def insert(str:String, start:Int)={\n var score=0\n var node=root\n var i=start\n while(score<=k && 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 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"}, {"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"} {"nl": {"description": "A TV show called \"Guess a number!\" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: Is it true that y is strictly larger than number x? Is it true that y is strictly smaller than number x? Is it true that y is larger than or equal to number x? Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, \"yes\" or \"no\".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print \"Impossible\".", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910000) \u2014 the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: \"sign x answer\", where the sign is: \">\" (for the first type queries), \"<\" (for the second type queries), \">=\" (for the third type queries), \"<=\" (for the fourth type queries). All values of x are integer and meet the inequation \u2009-\u2009109\u2009\u2264\u2009x\u2009\u2264\u2009109. The answer is an English letter \"Y\" (for \"yes\") or \"N\" (for \"no\"). Consequtive elements in lines are separated by a single space.", "output_spec": "Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation \u2009-\u20092\u00b7109\u2009\u2264\u2009y\u2009\u2264\u20092\u00b7109. If there are many answers, print any of them. If such value doesn't exist, print word \"Impossible\" (without the quotes).", "sample_inputs": ["4\n>= 1 Y\n< 3 N\n<= -3 N\n> 55 N", "2\n> 100 Y\n< -100 Y"], "sample_outputs": ["17", "Impossible"], "notes": null}, "positive_code": [{"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"}, {"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 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"}], "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"} {"nl": {"description": "Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.", "input_spec": "The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.", "output_spec": "Print a single number \u2014 the number of distinct letters in Anton's set.", "sample_inputs": ["{a, b, c}", "{b, a, b, a}", "{}"], "sample_outputs": ["3", "2", "0"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.", "input_spec": "The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \\le K \\le N \\le 10^{18}$$$; $$$1 \\le M, \\,\\, L \\le 10^{18}$$$)\u00a0\u2014 quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.", "output_spec": "Print one number\u00a0\u2014 minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print \"-1\" (without quotes).", "sample_inputs": ["20 15 2 3", "10 11 2 4"], "sample_outputs": ["1", "-1"], "notes": "NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins."}, "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, 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}"}, {"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"} {"nl": {"description": "The only difference between easy and hard versions is constraints.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $$$a$$$ and $$$b$$$, $$$a$$$ can be equal $$$b$$$) and is as follows: $$$[\\underbrace{a, a, \\dots, a}_{x}, \\underbrace{b, b, \\dots, b}_{y}, \\underbrace{a, a, \\dots, a}_{x}]$$$. There $$$x, y$$$ are integers greater than or equal to $$$0$$$. For example, sequences $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ and $$$[1, 1, 2, 1, 1]$$$ are three block palindromes but $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ and $$$[1, 2]$$$ are not.Your task is to choose the maximum by length subsequence of $$$a$$$ that is a three blocks palindrome.You have to answer $$$t$$$ independent test cases.Recall that the sequence $$$t$$$ is a a subsequence of the sequence $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2000$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 26$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. Note that the maximum value of $$$a_i$$$ can be up to $$$26$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\\sum n \\le 2000$$$).", "output_spec": "For each test case, print the answer \u2014 the maximum possible length of some subsequence of $$$a$$$ that is a three blocks palindrome.", "sample_inputs": ["6\n8\n1 1 2 2 3 2 1 1\n3\n1 3 3\n4\n1 10 10 1\n1\n26\n2\n2 1\n3\n1 1 1"], "sample_outputs": ["7\n2\n4\n1\n1\n3"], "notes": null}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution_E1 extends App {\n\n val T = StdIn.readInt()\n for (_ <- 1 to T) {\n val N = StdIn.readInt()\n val array = StdIn.readLine().split(' ').map{_.toInt}\n val distinct = mutable.SortedSet[Int]()\n array foreach {x => distinct.add(x)}\n val distArray = distinct.toArray\n var result = 1\n val M = 200\n val sumsRight = Array.fill[Int](M+1, N)(0)\n val sumsLeft = Array.fill[Int](M+1, N)(0)\n sumsRight(array.last)(N - 1) = 1\n sumsLeft(array.head)(0) = 1\n for (idx <- N - 2 to 0 by -1) {\n for (j <- 1 to M) {\n sumsRight(j)(idx) = sumsRight(j)(idx + 1)\n }\n sumsRight(array(idx))(idx) += 1\n }\n for (idx <- 1 until N) {\n for (j <-1 to M) {\n sumsLeft(j)(idx) = sumsLeft(j)(idx - 1)\n }\n sumsLeft(array(idx))(idx) += 1\n }\n for (startY <- 1 until N - 1) {\n for (endY <- startY until N - 1) {\n var Y = 1\n distArray foreach { x =>\n val current = sumsRight(x)(startY) - sumsRight(x)(endY + 1)\n Y = Math.max(Y, current)\n }\n distArray foreach { x =>\n result = Math.max(result, Y + 2 * Math.min(sumsLeft(x)(startY-1), sumsRight(x)(endY + 1)))\n }\n }\n }\n val distinctM = Array.fill[Int](M + 1)(0)\n array foreach {x => distinctM(x) += 1}\n result = Math.max(result, distinctM.max)\n println(result)\n }\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution_E1 extends App {\n\n val T = StdIn.readInt()\n for (_ <- 1 to T) {\n StdIn.readInt()\n val array = StdIn.readLine().split(' ').map{_.toInt}\n val distinct = mutable.SortedSet[Int]()\n array foreach {x => distinct.add(x)}\n val distArray = distinct.toArray\n var result = 1\n for (a <- 0 until distArray.size) {\n for (b <- a + 1 until distArray.size) {\n val filteredArray = array.filter(x => x == distArray(a) || x == distArray(b))\n val N = filteredArray.length\n val repeatRight = Array.fill[Int](N)(1)\n val repeatLeft = Array.fill[Int](N)(1)\n for (idx <- N - 2 to 0 by -1) {\n val next = if (filteredArray(idx) == filteredArray(idx + 1)) {\n repeatRight(idx + 1) + 1\n } else {\n 1\n }\n repeatRight(idx) = next\n }\n for (idx <- 1 until N) {\n repeatLeft(idx) = if (filteredArray(idx) == filteredArray(idx - 1)) {\n repeatLeft(idx - 1) + 1\n } else {\n 1\n }\n }\n for (idx <- 0 until N) {\n val y = repeatRight(idx)\n val xLeft = if (idx > 0) {\n repeatLeft(idx - 1)\n } else {\n 0\n }\n val xRight = if (idx + y < N) {\n repeatRight(idx + y)\n } else {\n 0\n }\n result = Math.max(result, y)\n if (xLeft > 0 && xRight > 0) {\n if (filteredArray(idx - 1) == filteredArray (idx + y)) {\n val total = y + 2 * Math.min(xLeft, xRight)\n result = Math.max(result, total)\n }\n }\n }\n }\n }\n val distinctM = Array.fill[Int](201)(0)\n array foreach {x => distinctM(x) += 1}\n result = Math.max(result, distinctM.max)\n println(result)\n }\n}\n"}, {"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution_E1 extends App {\n\n val T = StdIn.readInt()\n for (_ <- 1 to T) {\n val N = StdIn.readInt()\n val array = StdIn.readLine().split(' ').map{_.toInt}\n val distinct = mutable.SortedSet[Int]()\n array foreach {x => distinct.add(x)}\n val distArray = distinct.toArray\n var result = 1\n for (a <- 0 until distArray.size) {\n for (b <- a + 1 until distArray.size) {\n val filteredArray = array.filter(x => x == distArray(a) || x == distArray(b))\n val N = filteredArray.length\n val repeatRight = Array.fill[Int](N)(1)\n val repeatLeft = Array.fill[Int](N)(1)\n for (idx <- N - 2 to 0 by -1) {\n val next = if (filteredArray(idx) == filteredArray(idx + 1)) {\n repeatRight(idx + 1) + 1\n } else {\n 1\n }\n repeatRight(idx) = next\n }\n for (idx <- 1 until N) {\n repeatLeft(idx) = if (filteredArray(idx) == filteredArray(idx - 1)) {\n repeatLeft(idx - 1) + 1\n } else {\n 1\n }\n }\n for (idx <- 0 until N) {\n val y = repeatRight(idx)\n val xLeft = if (idx > 0) {\n repeatLeft(idx - 1)\n } else {\n 0\n }\n val xRight = if (idx + y < N) {\n repeatRight(idx + y)\n } else {\n 0\n }\n result = Math.max(result, y)\n if (xLeft > 0 && xRight > 0) {\n if (repeatLeft(idx - 1) == repeatRight(idx + y)) {\n val total = y + 2 * Math.min(xLeft, xRight)\n result = Math.max(result, total)\n }\n }\n }\n }\n }\n val distinctM = Array.fill[Int](201)(0)\n array foreach {x => distinctM(x) += 1}\n result = Math.max(result, distinctM.max)\n println(result)\n }\n}\n"}], "src_uid": "2c1ee398ea86209335c2248eaa723aca"} {"nl": {"description": "Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.", "output_spec": "Print one integer\u00a0\u2014 the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.", "sample_inputs": ["5\nrbbrr", "5\nbbbbb", "3\nrbr"], "sample_outputs": ["1", "2", "0"], "notes": "NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0."}, "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()\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"}, {"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"} {"nl": {"description": "Given a positive integer $$$k$$$, two arrays are called $$$k$$$-similar if: they are strictly increasing; they have the same length; all their elements are positive integers between $$$1$$$ and $$$k$$$ (inclusive); they differ in exactly one position. You are given an integer $$$k$$$, a strictly increasing array $$$a$$$ and $$$q$$$ queries. For each query, you are given two integers $$$l_i \\leq r_i$$$. Your task is to find how many arrays $$$b$$$ exist, such that $$$b$$$ is $$$k$$$-similar to array $$$[a_{l_i},a_{l_i+1}\\ldots,a_{r_i}]$$$. ", "input_spec": "The first line contains three integers $$$n$$$, $$$q$$$ and $$$k$$$ ($$$1\\leq n, q \\leq 10^5$$$, $$$n\\leq k \\leq 10^9$$$)\u00a0\u2014 the length of array $$$a$$$, the number of queries and number $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots,a_n$$$ ($$$1 \\leq a_i \\leq k$$$). This array is strictly increasing \u00a0\u2014 $$$a_1 < a_2 < \\ldots < a_n$$$. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \\leq l_i \\leq r_i \\leq n$$$).", "output_spec": "Print $$$q$$$ lines. The $$$i$$$-th of them should contain the answer to the $$$i$$$-th query.", "sample_inputs": ["4 2 5\n1 2 4 5\n2 3\n3 4", "6 5 10\n2 4 6 7 8 9\n1 4\n1 2\n3 5\n1 6\n5 5"], "sample_outputs": ["4\n3", "8\n9\n7\n6\n9"], "notes": "NoteIn the first example:In the first query there are $$$4$$$ arrays that are $$$5$$$-similar to $$$[2,4]$$$: $$$[1,4],[3,4],[2,3],[2,5]$$$.In the second query there are $$$3$$$ arrays that are $$$5$$$-similar to $$$[4,5]$$$: $$$[1,5],[2,5],[3,5]$$$."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "740d2aba32f69b8cfe8f7cb624621a63"} {"nl": {"description": "Phoenix is playing with a new puzzle, which consists of $$$n$$$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below. A puzzle piece The goal of the puzzle is to create a square using the $$$n$$$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $$$n$$$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$)\u00a0\u2014 the number of puzzle pieces.", "output_spec": "For each test case, if Phoenix can create a square with the $$$n$$$ puzzle pieces, print YES. Otherwise, print NO.", "sample_inputs": ["3\n2\n4\n6"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteFor $$$n=2$$$, Phoenix can create a square like this: For $$$n=4$$$, Phoenix can create a square like this: For $$$n=6$$$, it is impossible for Phoenix to create a square."}, "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 = nextLong\n var ok = false\n if (n % 2 == 0) {\n val m = n / 2\n val s = Math.sqrt(m).toInt\n if (s * s == m) ok = true\n }\n if (n % 4 == 0) {\n val m = n / 4\n val s = Math.sqrt(m).toInt\n if (s * s == m) ok = true\n }\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": "6ae754639d96790c890f9d1ab259332a"} {"nl": {"description": "You are given a table consisting of n rows and m columns.Numbers in each row form a permutation of integers from 1 to m.You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed to perform from 0 to n\u2009+\u20091 actions in total. Operations can be performed in any order.You have to check whether it's possible to obtain the identity permutation 1,\u20092,\u2009...,\u2009m in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200920)\u00a0\u2014 the number of rows and the number of columns in the given table. Each of next n lines contains m integers\u00a0\u2014 elements of the table. It's guaranteed that numbers in each line form a permutation of integers from 1 to m.", "output_spec": "If there is a way to obtain the identity permutation in each row by following the given rules, print \"YES\" (without quotes) in the only line of the output. Otherwise, print \"NO\" (without quotes).", "sample_inputs": ["2 4\n1 3 2 4\n1 3 4 2", "4 4\n1 2 3 4\n2 3 4 1\n3 4 1 2\n4 1 2 3", "3 6\n2 1 3 4 5 6\n1 2 4 3 5 6\n1 2 3 4 6 5"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first sample, one can act in the following way: Swap second and third columns. Now the table is 1\u00a02\u00a03\u00a04 1\u00a04\u00a03\u00a02 In the second row, swap the second and the fourth elements. Now the table is 1\u00a02\u00a03\u00a04 1\u00a02\u00a03\u00a04 "}, "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": "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"}, {"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"} {"nl": {"description": "There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \\cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 200$$$) \u2014 the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either \"W\" or \"B\". If the $$$i$$$-th character is \"W\", then the $$$i$$$-th block is white. If the $$$i$$$-th character is \"B\", then the $$$i$$$-th block is black. ", "output_spec": "If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \\le k \\le 3 \\cdot n$$$) \u2014 the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \\dots, p_k$$$ $$$(1 \\le p_j \\le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.", "sample_inputs": ["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"], "sample_outputs": ["3\n6 2 4", "-1", "0", "2\n2 1"], "notes": "NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is \"BWWWWBBB\". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is \"BBBWWBB\". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is \"BBW\"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white)."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val S = ns(N)\n val cntB = S.count(_ == 'B')\n val cntW = N - cntB\n val target = N % 2\n\n def invert(i: Int): Unit = {\n val c = if (S(i) == 'B') 'W' else 'B'\n S(i) = c\n }\n\n def paint(c: Char): ArrayBuffer[Int] = {\n val ans = ArrayBuffer[Int]()\n REP(N - 1) { i =>\n if (S(i) != c) {\n ans += i + 1\n invert(i)\n invert(i + 1)\n }\n }\n ans\n }\n\n if (cntB % 2 != target && cntW % 2 != target) {\n out.println(-1)\n return\n }\n\n val ans = if (cntB % 2 == target) {\n paint('B')\n } else {\n paint('W')\n }\n\n out.println(ans.length)\n out.println(ans.mkString(\" \"))\n }\n}"}], "negative_code": [], "src_uid": "3336662e6362693b8ac9455d4c2fe158"} {"nl": {"description": "Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y\u2009=\u200910100.She then will slide the disks towards the line y\u2009=\u20090 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi,\u200910100). She will then push it so the disk\u2019s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y\u2009=\u20090 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.", "input_spec": "The first line will contain two integers n and r (1\u2009\u2264\u2009n,\u2009r\u2009\u2264\u20091\u2009000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u20091\u2009000)\u00a0\u2014 the x-coordinates of the disks.", "output_spec": "Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10\u2009-\u20096. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if for all coordinates.", "sample_inputs": ["6 2\n5 5 6 8 3 12"], "sample_outputs": ["2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"], "notes": "NoteThe final positions of the disks will look as follows: In particular, note the position of the last disk. "}, "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": "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"}, {"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"} {"nl": {"description": "You are given a tree consisting of $$$n$$$ vertices. A tree is an undirected connected acyclic graph. Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $$$(x, y, z)$$$ such that $$$x \\neq y, y \\neq z, x \\neq z$$$, $$$x$$$ is connected by an edge with $$$y$$$, and $$$y$$$ is connected by an edge with $$$z$$$. The colours of $$$x$$$, $$$y$$$ and $$$z$$$ should be pairwise distinct. Let's call a painting which meets this condition good.You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.", "input_spec": "The first line contains one integer $$$n$$$ $$$(3 \\le n \\le 100\\,000)$$$ \u2014 the number of vertices. The second line contains a sequence of integers $$$c_{1, 1}, c_{1, 2}, \\dots, c_{1, n}$$$ $$$(1 \\le c_{1, i} \\le 10^{9})$$$, where $$$c_{1, i}$$$ is the cost of painting the $$$i$$$-th vertex into the first color. The third line contains a sequence of integers $$$c_{2, 1}, c_{2, 2}, \\dots, c_{2, n}$$$ $$$(1 \\le c_{2, i} \\le 10^{9})$$$, where $$$c_{2, i}$$$ is the cost of painting the $$$i$$$-th vertex into the second color. The fourth line contains a sequence of integers $$$c_{3, 1}, c_{3, 2}, \\dots, c_{3, n}$$$ $$$(1 \\le c_{3, i} \\le 10^{9})$$$, where $$$c_{3, i}$$$ is the cost of painting the $$$i$$$-th vertex into the third color. Then $$$(n - 1)$$$ lines follow, each containing two integers $$$u_j$$$ and $$$v_j$$$ $$$(1 \\le u_j, v_j \\le n, u_j \\neq v_j)$$$ \u2014 the numbers of vertices connected by the $$$j$$$-th undirected edge. It is guaranteed that these edges denote a tree.", "output_spec": "If there is no good painting, print $$$-1$$$. Otherwise, print the minimum cost of a good painting in the first line. In the second line print $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ $$$(1 \\le b_i \\le 3)$$$, where the $$$i$$$-th integer should denote the color of the $$$i$$$-th vertex. If there are multiple good paintings with minimum cost, print any of them.", "sample_inputs": ["3\n3 2 3\n4 3 2\n3 1 3\n1 2\n2 3", "5\n3 4 2 1 2\n4 2 1 5 4\n5 3 2 1 1\n1 2\n3 2\n4 3\n5 3", "5\n3 4 2 1 2\n4 2 1 5 4\n5 3 2 1 1\n1 2\n3 2\n4 3\n5 4"], "sample_outputs": ["6\n1 3 2", "-1", "9\n1 3 2 1 3"], "notes": "NoteAll vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color $$$1$$$, the second vertex \u2014 into color $$$3$$$, and the third vertex \u2014 into color $$$2$$$. The cost of this painting is $$$3 + 2 + 1 = 6$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2\u2009=\u2009q\u2009+\u20091, and she thinks it would make a good base for her new unique system. She called it \"golden system\". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.", "input_spec": "Input consists of two lines \u2014 one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.", "output_spec": "Print \">\" if the first number is larger, \"<\" if it is smaller and \"=\" if they are equal.", "sample_inputs": ["1000\n111", "00100\n11", "110\n101"], "sample_outputs": ["<", "=", ">"], "notes": "NoteIn the first example first number equals to , while second number is approximately 1.6180339882\u2009+\u20091.618033988\u2009+\u20091\u2009\u2248\u20095.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is \u2009\u2248\u20092.618."}, "positive_code": [{"source_code": "import java.io.PrintWriter\nimport java.util.Scanner\n\n/**\n * Created by arseny on 10.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\n var s = nextString.reverse.toCharArray\n var t = nextString.reverse.toCharArray\n\n def less(s: Array[Char], t: Array[Char], n: Int, m: Int): Int = {\n var nn = n\n while(nn > 0 && s(nn - 1) == '0') {\n nn -= 1\n }\n var mm = m\n while(mm > 0 && t(mm - 1) == '0') {\n mm -= 1\n }\n if(nn == 0 && mm > 0) {\n -1\n } else if(mm == 0 && nn > 0) {\n 1\n } else if (nn + 2 <= mm) {\n -1\n } else if(mm + 2 <= nn) {\n 1\n } else if(nn == mm) {\n if(nn == 0) {\n 0\n } else {\n less(s, t, nn - 1, mm - 1)\n }\n } else {\n if(nn == mm + 1) {\n if(s(mm - 1) == '1') {\n 1\n } else if(nn == 2 && mm == 1) {\n 1\n } else if(s(nn - 3) == '0') {\n s(nn - 3) = '1'\n less(s, t, nn - 2, mm - 1)\n } else if(t(mm - 2) == '1') {\n s(nn - 3) = '0'\n t(mm - 2) = '0'\n less(s, t, nn, mm)\n } else {\n 1\n }\n } else if(mm == nn + 1) {\n if(t(nn - 1) == '1') {\n -1\n } else if(mm == 2 && nn == 1) {\n -1\n } else if(t(mm - 3) == '0') {\n t(mm - 3) = '1'\n less(s, t, nn - 1, mm - 2)\n } else if(s(nn - 2) == '1') {\n t(mm - 3) = '0'\n s(nn - 2) = '0'\n less(s, t, nn, mm)\n } else {\n -1\n }\n } else {\n 0\n }\n }\n }\n\n val l = less(s, t, s.length, t.length)\n l match {\n case -1 => println('<')\n case 1 => println('>')\n case 0 => println('=')\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": "7c0a288a2777894bdfd75cb9703346e9"} {"nl": {"description": "This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting \"+\" and \"1\" into it we get a correct mathematical expression. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are regular, while \")(\", \"(()\" and \"(()))(\" are not. You have a pattern of a bracket sequence that consists of characters \"(\", \")\" and \"?\". You have to replace each character \"?\" with a bracket so, that you get a regular bracket sequence.For each character \"?\" the cost of its replacement with \"(\" and \")\" is given. Among all the possible variants your should choose the cheapest.", "input_spec": "The first line contains a non-empty pattern of even length, consisting of characters \"(\", \")\" and \"?\". Its length doesn't exceed 5\u00b7104. Then there follow m lines, where m is the number of characters \"?\" in the pattern. Each line contains two integer numbers ai and bi (1\u2009\u2264\u2009ai,\u2009\u2009bi\u2009\u2264\u2009106), where ai is the cost of replacing the i-th character \"?\" with an opening bracket, and bi \u2014 with a closing one.", "output_spec": "Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. ", "sample_inputs": ["(??)\n1 2\n2 8"], "sample_outputs": ["4\n()()"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.", "input_spec": "The first line contains the integer n (4\u2009\u2264\u2009n\u2009\u2264\u2009255)\u00a0\u2014 the length of the genome. The second line contains the string s of length n\u00a0\u2014 the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.", "output_spec": "If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: \"===\" (without quotes).", "sample_inputs": ["8\nAG?C??CT", "4\nAGCT", "6\n????G?", "4\nAA??"], "sample_outputs": ["AGACGTCT", "AGCT", "===", "==="], "notes": "NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom. "}, "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _747B extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val s = read[String]\n val nucleotides = \"ACGT\".toSeq\n\n val count = s.toSeq.toMultiSet\n\n val ans = s.toCharArray\n var i = 0\n\n def fill(c: Char, x: Int): Unit = if(x > 0 && i < n) {\n if (ans(i) == '?') {\n ans(i) = c\n i += 1\n fill(c, x - 1)\n } else {\n i += 1\n fill(c, x)\n }\n }\n\n val m = nucleotides.map(count).max\n nucleotides.foreach(c => fill(c, m - count(c)))\n nucleotides.foreach(c => fill(c, (n - 4*m)/4))\n\n val isOkay = {\n val finalCount = ans.toSeq.toMultiSet\n finalCount('?') == 0 && finalCount.size == 4 && finalCount.values.toSet.size == 1\n }\n\n write(if (isOkay) ans.mkString else \"===\")\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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": "d6423f380e6ba711d175d91e73f97b47"} {"nl": {"description": "Boy Dima gave Julian a birthday present\u00a0\u2014 set $$$B$$$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $$$i$$$ and $$$j$$$ with an edge if $$$|i - j|$$$ belongs to $$$B$$$.Unfortunately, Julian doesn't like the graph, that was built using $$$B$$$. Alex decided to rectify the situation, so he wants to erase some numbers from $$$B$$$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from $$$B$$$ so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.", "input_spec": "First line contains an integer $$$n ~ (1 \\leqslant n \\leqslant 200\\,000)$$$\u00a0\u2014 size of $$$B$$$ Second line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n ~ (1 \\leqslant b_i \\leqslant 10^{18})$$$\u00a0\u2014 numbers of $$$B$$$, all $$$b_i$$$ are unique", "output_spec": "In the first line print single integer $$$k$$$ \u2013 the number of erased elements. In the second line print $$$k$$$ integers\u00a0\u2014 values of erased elements. If there are multiple answers, print any of them.", "sample_inputs": ["3\n1 2 3", "2\n2 6"], "sample_outputs": ["1\n2", "0"], "notes": null}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val n = ni()\n val b = nal(n)\n val b2 = b.clone()\n val deleted = ArrayBuffer[Int]()\n val best = ArrayBuffer[Int]()\n REP(n) { i =>\n if (b2(i) % 2 == 0) best += i\n }\n\n def showResult(): Unit = {\n out.println(best.length)\n out.println(best.map(b).mkString(\" \"))\n }\n\n def removeOdds(): Unit = {\n var i = 0\n while(i < n) {\n if (b2(i) % 2 == 1) {\n b2(i) = 0\n deleted += i\n }\n i += 1\n }\n }\n\n def devide(g: Long) = {\n var i = 0\n while(i < n) {\n b2(i) /= g\n i += 1\n }\n }\n\n def updateAnsAsDelEven(cntOdd: Int, cntEven: Int): Unit = {\n if (deleted.length + cntEven < best.length) {\n best.clear()\n best ++= deleted\n var i = 0\n while(i < n) {\n if (b2(i) != 0 && b2(i) % 2 == 0) {\n best += i\n }\n i += 1\n }\n }\n }\n\n while(true) {\n val cntOdd = b2.count(_ % 2 == 1)\n val remain = n - deleted.length\n val cntEven = remain - cntOdd\n debug(s\"remain:$remain cntOdd$cntOdd cntEven:$cntEven\")\n updateAnsAsDelEven(cntOdd, cntEven)\n\n if (cntEven == 0) {\n showResult()\n return\n }\n\n removeOdds()\n\n val g = gcd(b2)\n devide(g)\n }\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n def gcd(as: Array[Long]): Long = {\n var res = as(0)\n var i = 1\n while (i < as.length) {\n res = gcd(res, as(i))\n i += 1\n }\n res\n }\n}"}], "negative_code": [], "src_uid": "679f7243fe1e072af826a779c44b5056"} {"nl": {"description": "Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person. A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \\le a,b,c \\le 10^8$$$).", "output_spec": "For each test case output in a separate line a single integer $$$d$$$ \u2014 the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.", "sample_inputs": ["7\n6 2 4\n2 3 1\n2 4 10\n5 3 4\n1 3 2\n2 5 4\n4 3 2"], "sample_outputs": ["8\n-1\n-1\n-1\n4\n1\n-1"], "notes": "NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n\u2009\u00d7\u2009n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n\u2009-\u20091, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.", "input_spec": "The first line contains one integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000), n is even.", "output_spec": "Output n lines with n numbers each \u2014 the required matrix. Separate numbers with spaces. If there are several solutions, output any.", "sample_inputs": ["2", "4"], "sample_outputs": ["0 1\n1 0", "0 1 3 2\n1 0 2 3\n3 2 0 1\n2 3 1 0"], "notes": null}, "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"}, {"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}"}], "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"} {"nl": {"description": "Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from \u2009-\u2009x to x. ", "input_spec": "The first line contains two integers: n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of found cards and x (1\u2009\u2264\u2009x\u2009\u2264\u20091000) \u2014 the maximum absolute value of the number on a card. The second line contains n space-separated integers \u2014 the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.", "output_spec": "Print a single number \u2014 the answer to the problem.", "sample_inputs": ["3 2\n-1 1 2", "2 3\n-2 -2"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value."}, "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": "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"}, {"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"} {"nl": {"description": "A sportsman starts from point xstart\u2009=\u20090 and runs to point with coordinate xfinish\u2009=\u2009m (on a straight line). Also, the sportsman can jump \u2014 to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.On the way of an athlete are n obstacles at coordinates x1,\u2009x2,\u2009...,\u2009xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.", "input_spec": "The first line of the input containsd four integers n, m, s and d (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 2\u2009\u2264\u2009m\u2009\u2264\u2009109, 1\u2009\u2264\u2009s,\u2009d\u2009\u2264\u2009109)\u00a0\u2014 the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009m\u2009-\u20091)\u00a0\u2014 the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.", "output_spec": "If the runner cannot reach the finishing point, print in the first line of the output \"IMPOSSIBLE\" (without the quotes). If the athlete can get from start to finish, print any way to do this in the following format: print a line of form \"RUN X>\" (where \"X\" should be a positive integer), if the athlete should run for \"X\" more meters; print a line of form \"JUMP Y\" (where \"Y\" should be a positive integer), if the sportsman starts a jump and should remain in air for \"Y\" more meters. All commands \"RUN\" and \"JUMP\" should strictly alternate, starting with \"RUN\", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish.", "sample_inputs": ["3 10 1 3\n3 4 7", "2 9 2 3\n6 4"], "sample_outputs": ["RUN 2\nJUMP 3\nRUN 1\nJUMP 2\nRUN 2", "IMPOSSIBLE"], "notes": null}, "positive_code": [{"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.io.Codec\n\n/**\n * @author itegulov\n */\nobject D extends App {\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 m = in.nextInt()\n val s = in.nextInt()\n val d = in.nextInt()\n var a: Array[Int] = Array.ofDim(n + 2)\n a(0) = 0\n a(n + 1) = m + 1\n\n for (i <- 1 to n) {\n a(i) = in.nextInt()\n }\n\n a = a.sorted\n\n if (a(1) - a(0) - 1 < s) {\n println(\"IMPOSSIBLE\")\n } else {\n var lastJumpIndex = 0\n\n val jumpFrom: Array[Int] = Array.fill(n + 1)(-1)\n\n for (i <- 1 to n)\n if ((a(i) + 1) - (a(lastJumpIndex + 1) - 1) <= d) {\n jumpFrom(i) = lastJumpIndex\n if ((a(i + 1) - 1) - (a(i) + 1) >= s) lastJumpIndex = i\n }\n\n if (jumpFrom(n) == -1) {\n println(\"IMPOSSIBLE\")\n } else {\n val answer: mutable.ArrayBuffer[String] = mutable.ArrayBuffer()\n\n var last = n\n while (last > 0) {\n if (a(last + 1) - 1 - (a(last) + 1) > 0) answer += (\"RUN \" + (a(last + 1) - 1 - (a(last) + 1)))\n answer += (\"JUMP \" + (a(last) + 1 - (a(jumpFrom(last) + 1) - 1)))\n last = jumpFrom(last)\n }\n answer += (\"RUN \" + (a(1) - 1 - a(0)))\n\n answer.reverse.foreach(out.println)\n }\n }\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"}], "negative_code": [{"source_code": "import java.io._\nimport java.nio.file._\nimport java.util.StringTokenizer\n\nimport scala.collection.mutable\nimport scala.io.Codec\n\n/**\n * @author itegulov\n */\nobject D extends App {\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 m = in.nextInt()\n val s = in.nextInt()\n val d = in.nextInt()\n var a: Array[Int] = Array.ofDim(n + 2)\n a(0) = 0\n a(n + 1) = m + 1\n\n for (i <- 1 to n) {\n a(i) = in.nextInt()\n }\n\n a = a.sorted\n\n if (a(1) - a(0) - 1 < s) {\n println(\"IMPOSSIBLE\")\n } else {\n var lastJumpIndex = 0\n\n val jumpFrom: Array[Int] = Array.fill(n + 1)(-1)\n\n for (i <- 1 to n)\n if ((a(i) + 1) - (a(lastJumpIndex + 1) - 1) <= d) {\n jumpFrom(i) = lastJumpIndex\n if (a(i + 1) - a(i) - 1 >= s) lastJumpIndex = i\n }\n\n if (jumpFrom(n) == -1) {\n println(\"IMPOSSIBLE\")\n } else {\n val answer: mutable.ArrayBuffer[String] = mutable.ArrayBuffer()\n\n var last = n\n while (last > 0) {\n if (a(last + 1) - 1 - (a(last) + 1) > 0) answer += (\"RUN \" + (a(last + 1) - 1 - (a(last) + 1)))\n answer += (\"JUMP \" + (a(last) + 1 - (a(jumpFrom(last) + 1) - 1)))\n last = jumpFrom(last)\n }\n answer += (\"RUN \" + (a(1) - 1 - a(0)))\n\n answer.reverse.foreach(out.println)\n }\n }\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.collection.mutable\nimport scala.io.Codec\n\n/**\n * @author itegulov\n */\nobject D extends App {\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 m = in.nextInt()\n val s = in.nextInt()\n val d = in.nextInt()\n var a: Array[Int] = Array.ofDim(n + 2)\n a(0) = 0\n a(n + 1) = m + 1\n\n for (i <- 1 to n) {\n a(i) = in.nextInt()\n }\n\n a = a.sorted\n\n if (a(1) - a(0) - 1 < s) {\n println(\"IMPOSSIBLE\")\n } else {\n var lastJumpIndex = 0\n\n val jumpFrom: Array[Int] = Array.fill(n + 1)(-1)\n\n for (i <- 1 to n)\n if ((a(i) + 1) - (a(lastJumpIndex + 1) - 1) <= d) {\n jumpFrom(i) = lastJumpIndex\n if (a(i + 1) - a(i) - 1 >= s) lastJumpIndex = i\n }\n\n if (jumpFrom(n) == -1) {\n println(\"IMPOSSIBLE\")\n } else {\n val answer: mutable.ArrayBuffer[String] = mutable.ArrayBuffer()\n\n var last = n\n while (last > 0) {\n answer += (\"RUN \" + (a(last + 1) - 1 - (a(last) + 1)))\n answer += (\"JUMP \" + (a(last) + 1 - (a(jumpFrom(last) + 1) - 1)))\n last = jumpFrom(last)\n }\n answer += (\"RUN \" + (a(1) - 1 - a(0)))\n\n answer.reverse.foreach(out.println)\n }\n }\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"}], "src_uid": "215b450fd48ffca3101aa51cf6f33f6b"} {"nl": {"description": "YouKn0wWho has two even integers $$$x$$$ and $$$y$$$. Help him to find an integer $$$n$$$ such that $$$1 \\le n \\le 2 \\cdot 10^{18}$$$ and $$$n \\bmod x = y \\bmod n$$$. Here, $$$a \\bmod b$$$ denotes the remainder of $$$a$$$ after division by $$$b$$$. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$2 \\le x, y \\le 10^9$$$, both are even).", "output_spec": "For each test case, print a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^{18}$$$) that satisfies the condition mentioned in the statement. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.", "sample_inputs": ["4\n4 8\n4 2\n420 420\n69420 42068"], "sample_outputs": ["4\n10\n420\n9969128"], "notes": "NoteIn the first test case, $$$4 \\bmod 4 = 8 \\bmod 4 = 0$$$.In the second test case, $$$10 \\bmod 4 = 2 \\bmod 10 = 2$$$.In the third test case, $$$420 \\bmod 420 = 420 \\bmod 420 = 0$$$."}, "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 = readLong()\n val m = readLong()\n var k = 0L\n if (n > m) {\n k = 1000000000L*n+m\n } else {\n k = (m/n).toLong\n k *= n\n k = (m + k)/2L\n }\n writer.println(k)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "a24aac9152417527d43b9b422e3d2303"} {"nl": {"description": "You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have $$$n$$$ bacteria in the Petri dish and size of the $$$i$$$-th bacteria is $$$a_i$$$. Also you know intergalactic positive integer constant $$$K$$$.The $$$i$$$-th bacteria can swallow the $$$j$$$-th bacteria if and only if $$$a_i > a_j$$$ and $$$a_i \\le a_j + K$$$. The $$$j$$$-th bacteria disappear, but the $$$i$$$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $$$i$$$ can swallow any bacteria $$$j$$$ if $$$a_i > a_j$$$ and $$$a_i \\le a_j + K$$$. The swallow operations go one after another.For example, the sequence of bacteria sizes $$$a=[101, 53, 42, 102, 101, 55, 54]$$$ and $$$K=1$$$. The one of possible sequences of swallows is: $$$[101, 53, 42, 102, \\underline{101}, 55, 54]$$$ $$$\\to$$$ $$$[101, \\underline{53}, 42, 102, 55, 54]$$$ $$$\\to$$$ $$$[\\underline{101}, 42, 102, 55, 54]$$$ $$$\\to$$$ $$$[42, 102, 55, \\underline{54}]$$$ $$$\\to$$$ $$$[42, 102, 55]$$$. In total there are $$$3$$$ bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.", "input_spec": "The first line contains two space separated positive integers $$$n$$$ and $$$K$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le K \\le 10^6$$$) \u2014 number of bacteria and intergalactic constant $$$K$$$. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$) \u2014 sizes of bacteria you have.", "output_spec": "Print the only integer \u2014 minimal possible number of bacteria can remain.", "sample_inputs": ["7 1\n101 53 42 102 101 55 54", "6 5\n20 15 10 15 20 25", "7 1000000\n1 1 1 1 1 1 1"], "sample_outputs": ["3", "1", "7"], "notes": "NoteThe first example is clarified in the problem statement.In the second example an optimal possible sequence of swallows is: $$$[20, 15, 10, 15, \\underline{20}, 25]$$$ $$$\\to$$$ $$$[20, 15, 10, \\underline{15}, 25]$$$ $$$\\to$$$ $$$[20, 15, \\underline{10}, 25]$$$ $$$\\to$$$ $$$[20, \\underline{15}, 25]$$$ $$$\\to$$$ $$$[\\underline{20}, 25]$$$ $$$\\to$$$ $$$[25]$$$.In the third example no bacteria can swallow any other bacteria."}, "positive_code": [{"source_code": "object B extends App {\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n var c = 0\n var r = 1\n var j = a.head\n for (i <- a.tail) {\n if (i == j) r += 1\n else {\n if (i - j > k) c += r\n r = 1\n }\n\n j = i\n }\n\n println(c + r)\n}\n"}], "negative_code": [{"source_code": "object B extends App {\n val Array(n, k) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).sorted\n\n var c = 0\n var r = 1\n var j = a.head\n for (i <- a.tail) {\n if (i == j) r += 1\n else {\n if (i - j > k) c += 1\n r = 1\n }\n\n j = i\n }\n\n println(c + r)\n}\n"}], "src_uid": "be8be333d036f6c19b9a6eb33f96ba75"} {"nl": {"description": "A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ are permutations, and $$$[1, 1]$$$, $$$[0, 1]$$$, $$$[2, 2, 1, 4]$$$ are not.There was a permutation $$$p[1 \\dots n]$$$. It was merged with itself. In other words, let's take two instances of $$$p$$$ and insert elements of the second $$$p$$$ into the first maintaining relative order of elements. The result is a sequence of the length $$$2n$$$.For example, if $$$p=[3, 1, 2]$$$ some possible results are: $$$[3, 1, 2, 3, 1, 2]$$$, $$$[3, 3, 1, 1, 2, 2]$$$, $$$[3, 1, 3, 1, 2, 2]$$$. The following sequences are not possible results of a merging: $$$[1, 3, 2, 1, 2, 3$$$], [$$$3, 1, 2, 3, 2, 1]$$$, $$$[3, 3, 1, 2, 2, 1]$$$.For example, if $$$p=[2, 1]$$$ the possible results are: $$$[2, 2, 1, 1]$$$, $$$[2, 1, 2, 1]$$$. The following sequences are not possible results of a merging: $$$[1, 1, 2, 2$$$], [$$$2, 1, 1, 2]$$$, $$$[1, 2, 2, 1]$$$.Your task is to restore the permutation $$$p$$$ by the given resulting sequence $$$a$$$. It is guaranteed that the answer exists and is unique.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 400$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the length of permutation. The second line of the test case contains $$$2n$$$ integers $$$a_1, a_2, \\dots, a_{2n}$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the array $$$a$$$ represents the result of merging of some permutation $$$p$$$ with the same permutation $$$p$$$.", "output_spec": "For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$), representing the initial permutation. It is guaranteed that the answer exists and is unique.", "sample_inputs": ["5\n2\n1 1 2 2\n4\n1 3 1 4 3 4 2 2\n5\n1 2 1 2 3 4 3 5 4 5\n3\n1 2 3 1 2 3\n4\n2 3 2 4 1 3 4 1"], "sample_outputs": ["1 2 \n1 3 4 2 \n1 2 3 4 5 \n1 2 3 \n2 3 4 1"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.", "input_spec": "The first line contains two space-separated integers, n and m (3\u2009\u2264\u2009n\u2009\u2264\u20094000, 0\u2009\u2264\u2009m\u2009\u2264\u20094000) \u2014 respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.", "output_spec": "If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print \"-1\" (without the quotes).", "sample_inputs": ["5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5", "7 4\n2 1\n3 6\n5 1\n1 7"], "sample_outputs": ["2", "-1"], "notes": "NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0\u2009+\u20091\u2009+\u20091\u2009=\u20092.The other possible triple is 2,\u20093,\u20094 but it has greater sum of recognitions, equal to 1\u2009+\u20091\u2009+\u20091\u2009=\u20093.In the second sample there is no triple of warriors knowing each other."}, "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 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}"}, {"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"} {"nl": {"description": "You are given a permutation $$$p$$$ of $$$n$$$ integers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once).Let's call some subsegment $$$p[l, r]$$$ of this permutation special if $$$p_l + p_r = \\max \\limits_{i = l}^{r} p_i$$$. Please calculate the number of special subsegments.", "input_spec": "The first line contains one integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ ($$$1 \\le p_i \\le n$$$). All these integers are pairwise distinct.", "output_spec": "Print the number of special subsegments of the given permutation.", "sample_inputs": ["5\n3 4 1 5 2", "3\n1 3 2"], "sample_outputs": ["2", "1"], "notes": "NoteSpecial subsegments in the first example are $$$[1, 5]$$$ and $$$[1, 3]$$$.The only special subsegment in the second example is $$$[1, 3]$$$."}, "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) 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 scala.reflect.ClassTag\n\n // toInt\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n\n override def run(): Unit = {\n val N = ni()\n val A = na(N)\n val R = Array.ofDim[Int](N + 1)\n REP(N) { i =>\n R(A(i)) = i\n }\n val t = new SegmentTree(N, 0)(max)\n REP(N) { i =>\n t.update(i, A(i))\n }\n\n // [l, r)\n def f(l: Int, r: Int): Long = {\n if (r <= l) 0L\n else {\n debug(s\"f($l, $r)\")\n val mx = t.query(l, r)\n val i = R(mx)\n val llen = i - l\n val rlen = r - i - 1\n val (from, to, opl, opr) = if (llen <= rlen) {\n (l, i - 1, i + 1, r)\n } else {\n (i + 1, r - 1, l, i)\n }\n\n var res = 0\n TO(from, to) { j =>\n val d = A(i) - A(j)\n debug(s\"i:$i j:$j d:$d\")\n if (R(d) >= opl && R(d) < opr) res += 1\n }\n res + f(l, i) + f(i + 1, r)\n }\n }\n val ans = f(0, N)\n out.println(ans)\n }\n\n def solve(): Unit = {\n val t = new Thread(null, this, \"solve\", 1 << 26)\n t.start()\n t.join()\n }\n\n /**\n * @param n \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\n * type A = Int\n */\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\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) 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 scala.reflect.ClassTag\n\n // toInt\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n\n override def run(): Unit = {\n val N = ni()\n val A = na(N)\n val R = Array.ofDim[Int](N + 1)\n REP(N) { i =>\n R(A(i)) = i\n }\n val t = new SegmentTree(N, 0)(max)\n REP(N) { i =>\n t.update(i, A(i))\n }\n\n // [l, r)\n def f(l: Int, r: Int): Long = {\n if (r <= l) 0L\n else {\n debug(s\"f($l, $r)\")\n val mx = t.query(l, r)\n val i = R(mx)\n val llen = i - l\n val rlen = r - i - 1\n val (from, to) = if (llen <= rlen) {\n (l, i - 1)\n } else {\n (i + 1, r - 1)\n }\n\n var res = 0\n TO(from, to) { j =>\n val d = A(i) - A(j)\n debug(s\"i:$i j:$j d:$d\")\n if (R(d) >= l && R(d) < r) res += 1\n }\n res + f(l, i) + f(i + 1, r)\n }\n }\n val ans = f(0, N)\n out.println(ans)\n }\n\n def solve(): Unit = {\n val t = new Thread(null, this, \"solve\", 1 << 26)\n t.start()\n t.join()\n }\n\n /**\n * @param n \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\n * type A = Int\n */\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\n }\n }\n}"}], "src_uid": "97f03ede9f5e9108b0b0f2d4b418a540"} {"nl": {"description": "You are given an integer $$$n$$$ and an array $$$a_1, a_2, \\ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \\ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \\ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\\sum\\limits_{i=1}^{n} \\textbf{MEX}(b_1, b_2, \\ldots, b_i)$$$ is maximized.$$$\\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\\textbf{MEX}(\\{1, 2, 3\\}) = 0$$$, $$$\\textbf{MEX}(\\{0, 1, 2, 4, 5\\}) = 3$$$.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 100)$$$ \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \\le n \\le 100)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(0 \\le a_i \\le 100)$$$.", "output_spec": "For each test case print an array $$$b_1, b_2, \\ldots, b_n$$$ \u00a0\u2014 the optimal reordering of $$$a_1, a_2, \\ldots, a_n$$$, so the sum of $$$\\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.", "sample_inputs": ["3\n7\n4 2 0 1 3 3 7\n5\n2 2 8 6 9\n1\n0"], "sample_outputs": ["0 1 2 3 4 7 3 \n2 6 8 9 2 \n0"], "notes": "NoteIn the first test case in the answer $$$\\textbf{MEX}$$$ for prefixes will be: $$$\\textbf{MEX}(\\{0\\}) = 1$$$ $$$\\textbf{MEX}(\\{0, 1\\}) = 2$$$ $$$\\textbf{MEX}(\\{0, 1, 2\\}) = 3$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3\\}) = 4$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3, 4\\}) = 5$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3, 4, 7\\}) = 5$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3, 4, 7, 3\\}) = 5$$$ The sum of $$$\\textbf{MEX} = 1 + 2 + 3 + 4 + 5 + 5 + 5 = 25$$$. It can be proven, that it is a maximum possible sum of $$$\\textbf{MEX}$$$ on prefixes."}, "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"}, {"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"}], "negative_code": [], "src_uid": "69838d9f9214c65b84a21d4eb546ea4b"} {"nl": {"description": "Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.", "input_spec": "A single line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000) \u2014 the number of digits in the set. The second line contains n digits, the digits are separated by a single space. ", "output_spec": "On a single line print the answer to the problem. If such number does not exist, then you should print -1.", "sample_inputs": ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"], "sample_outputs": ["0", "5554443330", "-1"], "notes": "NoteIn the first sample there is only one number you can make \u2014 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number."}, "positive_code": [{"source_code": "object B{\n def main(args: Array[String]){\n\n val n=readLine.toInt\n\n val a=readLine.split(\" \").toList.map(_.toInt)\n\n if(a.count(_==0)==0){\n //NG\n println(-1)\n return\n }\n\n val sum=a.sum\n\n val pl=\n if(sum%3==0){\n //OK\n a\n }else{\n val l0=a.filter(_%3==0)\n val l1=a.filter(_%3==sum%3)\n val l2=a.filter(_%3+sum%3==3)\n\n if(l1.length>=1){\n //OK\n l1.sorted.tail:::l0:::l2\n }else if(l2.length>=2){\n //OK\n l2.sorted.tail.tail:::l0:::l1\n }else{\n l0\n }\n }\n\n //print\n if(pl.count(_!=0)==0){\n println(0)\n }else{\n println(pl.sorted.reverse.mkString)\n }\n }\n}\n"}], "negative_code": [{"source_code": "object B{\n def main(args: Array[String]){\n\n val n=readLine.toInt\n\n val a=readLine.split(\" \").toList.map(_.toInt)\n\n if(a.count(_==0)==0){\n //NG\n println(-1)\n return\n }\n\n val sum=a.sum\n\n val pl=\n if(sum%3==0){\n //OK\n a\n }else{\n val l0=a.filter(_%3==0)\n val l1=a.filter(_%3==sum%3)\n val l2=a.filter(_%3+sum%3==3)\n\n if(l1.length>=1){\n //OK\n l1.sorted.tail:::l0:::l2\n }else if(l2.length>=2){\n //OK\n l2.sorted.tail.tail:::l0:::l1\n }else{\n l0\n }\n }\n\n //print\n if(pl.head==0){\n println(0)\n }else{\n println(pl.sorted.reverse.mkString)\n }\n }\n}\n"}, {"source_code": "object B{\n def main(args: Array[String]){\n\n val n=readLine.toInt\n\n val a=readLine.split(\" \").toList.map(_.toInt)\n\n if(a.count(_==0)==0){\n //NG\n println(-1)\n return\n }\n\n val sum=a.sum\n\n val pl=\n if(sum%3==0){\n //OK\n a\n }else{\n val l0=a.filter(_%3==0)\n val l1=a.filter(_%3==sum%3)\n val l2=a.filter(_%3+sum%3==3)\n\n if(l1.length>=1){\n //OK\n l1.sorted.tail:::l0:::l2\n }else if(l2.length>=2){\n //OK\n l2.sorted.tail.tail:::l0:::l1\n }else{\n //0,3,6,9\n if(l0.count(_!=0)==0){\n List(0)\n }else{\n l0\n }\n }\n }\n\n //print\n println(pl.sorted.reverse.mkString)\n }\n}\n"}, {"source_code": "object B{\n def main(args: Array[String]){\n\n val n=readLine.toInt\n\n val a=readLine.split(\" \").toList.map(_.toInt)\n\n if(a.count(_==0)==0){\n //NG\n println(-1)\n return\n }\n\n val sum=a.sum\n\n val pl=\n if(a.count(_!=0)==0){\n List(0)\n }else if(sum%3==0){\n //OK\n a\n }else{\n val l0=a.filter(_%3==0)\n val l1=a.filter(_%3==sum%3)\n val l2=a.filter(_%3+sum%3==3)\n\n if(l1.length>=1){\n //OK\n l1.sorted.tail:::l0:::l2\n }else if(l2.length>=2){\n //OK\n l2.sorted.tail.tail:::l0:::l1\n }else{\n l0\n }\n }\n\n //print\n println(pl.sorted.reverse.mkString)\n }\n}\n"}], "src_uid": "b263917e47e1c84340bcb1c77999fd7e"} {"nl": {"description": "Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions: a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009an; a1\u2009\u2265\u2009a2\u2009\u2265\u2009...\u2009\u2265\u2009an. Help Petya find the two required positions to swap or else say that they do not exist.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n non-negative space-separated integers a1,\u2009a2,\u2009...,\u2009an \u2014 the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.", "output_spec": "If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.", "sample_inputs": ["1\n1", "2\n1 2", "4\n1 2 3 4", "3\n1 1 1"], "sample_outputs": ["-1", "-1", "1 2", "-1"], "notes": "NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted."}, "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 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"}, {"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"} {"nl": {"description": "Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.", "input_spec": "The first line of the input contains three integers n, n1 and n2 (1\u2009\u2264\u2009n,\u2009n1,\u2009n2\u2009\u2264\u2009100\u2009000, n1\u2009+\u2009n2\u2009\u2264\u2009n)\u00a0\u2014 the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100\u2009000), the i-th of them is equal to the wealth of the i-th candidate.", "output_spec": "Print one real value\u00a0\u2014 the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["2 1 1\n1 5", "4 2 1\n1 4 2 3"], "sample_outputs": ["6.00000000", "6.50000000"], "notes": "NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3\u2009+\u2009a4)\u2009/\u20092\u2009+\u2009a2\u2009=\u2009(3\u2009+\u20092)\u2009/\u20092\u2009+\u20094\u2009=\u20096.5"}, "positive_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).foldLeft(0l)(_+_).toDouble / min + a.drop(min).foldLeft(0l)(_+_).toDouble / max)\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 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"} {"nl": {"description": " While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $$$a_1, a_2, \\ldots, a_n$$$ to $$$-a_1, -a_2, \\ldots, -a_n$$$. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $$$5\\,000$$$ and after every operation no variable can have an absolute value greater than $$$10^{18}$$$. William can perform actions of two types for two chosen variables with indices $$$i$$$ and $$$j$$$, where $$$i < j$$$: Perform assignment $$$a_i = a_i + a_j$$$ Perform assignment $$$a_j = a_j - a_i$$$ William wants you to develop a strategy that will get all the internal variables to the desired values.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 20$$$). Description of the test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \\le n \\le 10^3$$$), which is the number of internal variables. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$, which are initial values of internal variables.", "output_spec": "For each test case print the answer in the following format: The first line of output must contain the total number of actions $$$k$$$, which the strategy will perform. Note that you do not have to minimize $$$k$$$. The inequality $$$k \\le 5\\,000$$$ must be satisfied. Each of the next $$$k$$$ lines must contain actions formatted as \"type i j\", where \"type\" is equal to \"1\" if the strategy needs to perform an assignment of the first type and \"2\" if the strategy needs to perform an assignment of the second type. Note that $$$i < j$$$ should hold. We can show that an answer always exists.", "sample_inputs": ["2\n4\n1 1 1 1\n4\n4 3 1 2"], "sample_outputs": ["8\n2 1 2\n2 1 2\n2 1 3\n2 1 3\n2 1 4\n2 1 4\n1 1 2\n1 1 2\n8\n2 1 4\n1 2 4\n1 2 4\n1 2 4\n1 3 4\n1 1 2\n1 1 2\n1 1 4"], "notes": "NoteFor the first sample test case one possible sequence of operations is as follows: \"2 1 2\". Values of variables after performing the operation: [1, 0, 1, 1] \"2 1 2\". Values of variables after performing the operation: [1, -1, 1, 1] \"2 1 3\". Values of variables after performing the operation: [1, -1, 0, 1] \"2 1 3\". Values of variables after performing the operation: [1, -1, -1, 1] \"2 1 4\". Values of variables after performing the operation: [1, -1, -1, 0] \"2 1 4\". Values of variables after performing the operation: [1, -1, -1, -1] \"1 1 2\". Values of variables after performing the operation: [0, -1, -1, -1] \"1 1 2\". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows: \"2 1 4\". Values of variables after performing the operation: [4, 3, 1, -2] \"1 2 4\". Values of variables after performing the operation: [4, 1, 1, -2] \"1 2 4\". Values of variables after performing the operation: [4, -1, 1, -2] \"1 2 4\". Values of variables after performing the operation: [4, -3, 1, -2] \"1 3 4\". Values of variables after performing the operation: [4, -3, -1, -2] \"1 1 2\". Values of variables after performing the operation: [1, -3, -1, -2] \"1 1 2\". Values of variables after performing the operation: [-2, -3, -1, -2] \"1 1 4\". Values of variables after performing the operation: [-4, -3, -1, -2] "}, "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()\r\n\r\n println(n / 2 * 6)\r\n\r\n (1 until (n, 2)).foreach { i =>\r\n val j = i + 1\r\n\r\n println(s\"1 ${i} ${j}\")\r\n println(s\"2 ${i} ${j}\")\r\n println(s\"1 ${i} ${j}\")\r\n println(s\"1 ${i} ${j}\")\r\n println(s\"2 ${i} ${j}\")\r\n println(s\"1 ${i} ${j}\")\r\n }\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "980d2b3b6b80358b3757db8fe19e8287"} {"nl": {"description": "Recently, Norge found a string $$$s = s_1 s_2 \\ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \\ldots b] = s_{a} s_{a + 1} \\ldots s_{b}$$$ ($$$1 \\leq a \\leq b \\leq n$$$). For example, \"auto\" and \"ton\" are substrings of \"automaton\".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \\ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.", "input_spec": "The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$, $$$1 \\leq k \\leq 26$$$) \u2014 the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \\ldots, c_k$$$ \u2014 the letters still available on the keyboard.", "output_spec": "Print a single number \u2014 the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \\ldots, c_k$$$.", "sample_inputs": ["7 2\nabacaba\na b", "10 3\nsadfaasdda\nf a d", "7 1\naaaaaaa\nb"], "sample_outputs": ["12", "21", "0"], "notes": "NoteIn the first example Norge can print substrings $$$s[1\\ldots2]$$$, $$$s[2\\ldots3]$$$, $$$s[1\\ldots3]$$$, $$$s[1\\ldots1]$$$, $$$s[2\\ldots2]$$$, $$$s[3\\ldots3]$$$, $$$s[5\\ldots6]$$$, $$$s[6\\ldots7]$$$, $$$s[5\\ldots7]$$$, $$$s[5\\ldots5]$$$, $$$s[6\\ldots6]$$$, $$$s[7\\ldots7]$$$."}, "positive_code": [{"source_code": "object CF605C extends App {\n\n import scala.io.StdIn\n\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val string = StdIn.readLine\n val available = StdIn.readLine.split(' ').map(_.toCharArray.head)\n if (k == 26) {\n println((n.toLong*(n.toLong+1))/2)\n } else {\n val notAvailable = \"abcdefghijklmnopqrstuvwxyz\".toCharArray.filter(!available.contains(_))\n val split = string.split(notAvailable)\n println(split.map(s => (s.length.toLong*(s.length.toLong+1))/2).sum)\n }\n}\n"}], "negative_code": [{"source_code": "object CF605C extends App {\n\n import scala.io.StdIn\n\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val string = StdIn.readLine\n val available = StdIn.readLine.split(' ').map(_.toCharArray.head)\n val notAvailable = \"abcdefghijklmnopqrstuvwxyz\".toCharArray.filter(!available.contains(_))\n val split = if (notAvailable.isEmpty) List(string).toArray else string.split(notAvailable)\n println(split.map(s => (s.length*(s.length+1))/2).sum)\n}"}, {"source_code": "object CF605C extends App {\n\n import scala.io.StdIn\n\n val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)\n val string = StdIn.readLine\n val available = StdIn.readLine.split(' ').map(_.toCharArray.head)\n if (k == 26) {\n println((n*(n+1))/2)\n } else {\n val notAvailable = \"abcdefghijklmnopqrstuvwxyz\".toCharArray.filter(!available.contains(_))\n val split = string.split(notAvailable)\n println(split.map(s => (s.length*(s.length+1))/2).sum)\n }\n}\n"}], "src_uid": "4c260e7c6fd9c573ee4f3b1822f3c7c3"} {"nl": {"description": "Toad Pimple has an array of integers $$$a_1, a_2, \\ldots, a_n$$$.We say that $$$y$$$ is reachable from $$$x$$$ if $$$x<y$$$ and there exists an integer array $$$p$$$ such that $$$x = p_1 < p_2 < \\ldots < p_k=y$$$, and $$$a_{p_i}\\, \\&\\, a_{p_{i+1}} > 0$$$ for all integers $$$i$$$ such that $$$1 \\leq i < k$$$.Here $$$\\&$$$ denotes the bitwise AND operation.You are given $$$q$$$ pairs of indices, check reachability for each of them.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\leq n \\leq 300\\,000$$$, $$$1 \\leq q \\leq 300\\,000$$$)\u00a0\u2014 the number of integers in the array and the number of queries you need to answer. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 300\\,000$$$)\u00a0\u2014 the given array. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th of them contains two space-separated integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\leq x_i < y_i \\leq n$$$). You need to check if $$$y_i$$$ is reachable from $$$x_i$$$. ", "output_spec": "Output $$$q$$$ lines. In the $$$i$$$-th of them print \"Shi\" if $$$y_i$$$ is reachable from $$$x_i$$$, otherwise, print \"Fou\".", "sample_inputs": ["5 3\n1 3 0 2 1\n1 3\n2 4\n1 4"], "sample_outputs": ["Fou\nShi\nShi"], "notes": "NoteIn the first example, $$$a_3 = 0$$$. You can't reach it, because AND with it is always zero. $$$a_2\\, \\&\\, a_4 > 0$$$, so $$$4$$$ is reachable from $$$2$$$, and to go from $$$1$$$ to $$$4$$$ you can use $$$p = [1, 2, 4]$$$."}, "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 @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}"}, {"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 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"}], "negative_code": [], "src_uid": "6e2e7fd13e9f79267baa4bfd75444f32"} {"nl": {"description": "Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.", "input_spec": "The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1\u2009\u2264\u2009n\u2009\u2264\u200990) \u2014 the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1\u2009\u2264\u2009t\u2009\u2264\u200990) \u2014 the minute when the foul occurs; then goes letter \"h\" or letter \"a\" \u2014 if the letter is \"h\", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1\u2009\u2264\u2009m\u2009\u2264\u200999); then goes letter \"y\" or letter \"r\" \u2014 if the letter is \"y\", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.", "output_spec": "For each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards).", "sample_inputs": ["MC\nCSKA\n9\n28 a 3 y\n62 h 25 y\n66 h 42 y\n70 h 25 y\n77 a 4 y\n79 a 25 y\n82 h 42 r\n89 h 16 y\n90 a 13 r"], "sample_outputs": ["MC 25 70\nMC 42 82\nCSKA 13 90"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "\u041a\u0430\u043a \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0432 \u0442\u0435\u043f\u043b\u0443\u044e \u043f\u043e\u0433\u043e\u0434\u0443 \u043c\u043d\u043e\u0433\u0438\u0435 \u0436\u0438\u0442\u0435\u043b\u0438 \u043a\u0440\u0443\u043f\u043d\u044b\u0445 \u0433\u043e\u0440\u043e\u0434\u043e\u0432 \u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0442\u0441\u044f \u0441\u0435\u0440\u0432\u0438\u0441\u0430\u043c\u0438 \u0433\u043e\u0440\u043e\u0434\u0441\u043a\u043e\u0433\u043e \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0430. \u0412\u043e\u0442 \u0438 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u0441\u0435\u0433\u043e\u0434\u043d\u044f \u0431\u0443\u0434\u0435\u0442 \u0434\u043e\u0431\u0438\u0440\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u0448\u043a\u043e\u043b\u044b \u0434\u043e \u0434\u043e\u043c\u0430, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u0433\u043e\u0440\u043e\u0434\u0441\u043a\u0438\u0435 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u044b.\u0428\u043a\u043e\u043b\u0430 \u0438 \u0434\u043e\u043c \u043d\u0430\u0445\u043e\u0434\u044f\u0442\u0441\u044f \u043d\u0430 \u043e\u0434\u043d\u043e\u0439 \u043f\u0440\u044f\u043c\u043e\u0439 \u0443\u043b\u0438\u0446\u0435, \u043a\u0440\u043e\u043c\u0435 \u0442\u043e\u0433\u043e, \u043d\u0430 \u0442\u043e\u0439 \u0436\u0435 \u0443\u043b\u0438\u0446\u0435 \u0435\u0441\u0442\u044c n \u0442\u043e\u0447\u0435\u043a, \u0433\u0434\u0435 \u043c\u043e\u0436\u043d\u043e \u0432\u0437\u044f\u0442\u044c \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434 \u0432 \u043f\u0440\u043e\u043a\u0430\u0442 \u0438\u043b\u0438 \u0441\u0434\u0430\u0442\u044c \u0435\u0433\u043e. \u041f\u0435\u0440\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0432 \u0442\u043e\u0447\u043a\u0435 x1 \u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440\u043e\u0432 \u0432\u0434\u043e\u043b\u044c \u0443\u043b\u0438\u0446\u044b, \u0432\u0442\u043e\u0440\u043e\u0439\u00a0\u2014 \u0432 \u0442\u043e\u0447\u043a\u0435 x2 \u0438 \u0442\u0430\u043a \u0434\u0430\u043b\u0435\u0435, n-\u0439 \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0432 \u0442\u043e\u0447\u043a\u0435 xn. \u0428\u043a\u043e\u043b\u0430 \u0410\u0440\u043a\u0430\u0434\u0438\u044f \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0432 \u0442\u043e\u0447\u043a\u0435 x1 (\u0442\u043e \u0435\u0441\u0442\u044c \u0442\u0430\u043c \u0436\u0435, \u0433\u0434\u0435 \u0438 \u043f\u0435\u0440\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442), \u0430 \u0434\u043e\u043c\u00a0\u2014 \u0432 \u0442\u043e\u0447\u043a\u0435 xn (\u0442\u043e \u0435\u0441\u0442\u044c \u0442\u0430\u043c \u0436\u0435, \u0433\u0434\u0435 \u0438 n-\u0439 \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442). \u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e xi\u2009<\u2009xi\u2009+\u20091 \u0434\u043b\u044f \u0432\u0441\u0435\u0445 1\u2009\u2264\u2009i\u2009<\u2009n.\u0421\u043e\u0433\u043b\u0430\u0441\u043d\u043e \u043f\u0440\u0430\u0432\u0438\u043b\u0430\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0430, \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u043c\u043e\u0436\u0435\u0442 \u0431\u0440\u0430\u0442\u044c \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434 \u0432 \u043f\u0440\u043e\u043a\u0430\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u043d\u0430 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u043d\u043e\u0435 \u0432\u0440\u0435\u043c\u044f, \u043f\u043e\u0441\u043b\u0435 \u044d\u0442\u043e\u0433\u043e \u043e\u043d \u0434\u043e\u043b\u0436\u0435\u043d \u043e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u0432\u0435\u0440\u043d\u0443\u0442\u044c \u0435\u0433\u043e \u0432 \u043e\u0434\u043d\u043e\u0439 \u0438\u0437 \u0442\u043e\u0447\u0435\u043a \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0430, \u043e\u0434\u043d\u0430\u043a\u043e, \u043e\u043d \u0442\u0443\u0442 \u0436\u0435 \u043c\u043e\u0436\u0435\u0442 \u0432\u0437\u044f\u0442\u044c \u043d\u043e\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434, \u0438 \u043e\u0442\u0441\u0447\u0435\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043f\u043e\u0439\u0434\u0435\u0442 \u0437\u0430\u043d\u043e\u0432\u043e. \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u043c\u043e\u0436\u0435\u0442 \u0431\u0440\u0430\u0442\u044c \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u043e\u0434\u043d\u043e\u0433\u043e \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430 \u0432 \u043f\u0440\u043e\u043a\u0430\u0442 \u043e\u0434\u043d\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e. \u0415\u0441\u043b\u0438 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u0440\u0435\u0448\u0430\u0435\u0442 \u0432\u0437\u044f\u0442\u044c \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434 \u0432 \u043a\u0430\u043a\u043e\u0439-\u0442\u043e \u0442\u043e\u0447\u043a\u0435 \u043f\u0440\u043e\u043a\u0430\u0442\u0430, \u0442\u043e \u043e\u043d \u0441\u0434\u0430\u0451\u0442 \u0442\u043e\u0442 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434, \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043e\u043d \u0434\u043e \u043d\u0435\u0433\u043e \u0434\u043e\u0435\u0445\u0430\u043b, \u0431\u0435\u0440\u0451\u0442 \u0440\u043e\u0432\u043d\u043e \u043e\u0434\u0438\u043d \u043d\u043e\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434 \u0438 \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0430\u0435\u0442 \u043d\u0430 \u043d\u0451\u043c \u0441\u0432\u043e\u0451 \u0434\u0432\u0438\u0436\u0435\u043d\u0438\u0435.\u0417\u0430 \u043e\u0442\u0432\u0435\u0434\u0435\u043d\u043d\u043e\u0435 \u0432\u0440\u0435\u043c\u044f, \u043d\u0435\u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e \u043e\u0442 \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u043e\u0433\u043e \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430, \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u0443\u0441\u043f\u0435\u0432\u0430\u0435\u0442 \u043f\u0440\u043e\u0435\u0445\u0430\u0442\u044c \u043d\u0435 \u0431\u043e\u043b\u044c\u0448\u0435 k \u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440\u043e\u0432 \u0432\u0434\u043e\u043b\u044c \u0443\u043b\u0438\u0446\u044b. \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435, \u0441\u043c\u043e\u0436\u0435\u0442 \u043b\u0438 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u0434\u043e\u0435\u0445\u0430\u0442\u044c \u043d\u0430 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430\u0445 \u043e\u0442 \u0448\u043a\u043e\u043b\u044b \u0434\u043e \u0434\u043e\u043c\u0430, \u0438 \u0435\u0441\u043b\u0438 \u0434\u0430, \u0442\u043e \u043a\u0430\u043a\u043e\u0435 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0440\u0430\u0437 \u0435\u043c\u0443 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0431\u0443\u0434\u0435\u0442 \u0432\u0437\u044f\u0442\u044c \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434 \u0432 \u043f\u0440\u043e\u043a\u0430\u0442, \u0432\u043a\u043b\u044e\u0447\u0430\u044f \u043f\u0435\u0440\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434? \u0423\u0447\u0442\u0438\u0442\u0435, \u0447\u0442\u043e \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u043d\u0435 \u043d\u0430\u043c\u0435\u0440\u0435\u043d \u0441\u0435\u0433\u043e\u0434\u043d\u044f \u0445\u043e\u0434\u0438\u0442\u044c \u043f\u0435\u0448\u043a\u043e\u043c.", "input_spec": "\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043b\u0435\u0434\u0443\u044e\u0442 \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 k (2\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009100\u2009000) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u043e\u0432 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u043c\u043e\u0436\u0435\u0442 \u043f\u0440\u043e\u0435\u0445\u0430\u0442\u044c \u043d\u0430 \u043e\u0434\u043d\u043e\u043c \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0435. \u0412 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0441\u043b\u0435\u0434\u0443\u0435\u0442 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b x1,\u2009x2,\u2009...,\u2009xn (0\u2009\u2264\u2009x1\u2009<\u2009x2\u2009<\u2009...\u2009<\u2009xn\u2009\u2264\u2009100\u2009000) \u2014 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u0442\u043e\u0447\u0435\u043a, \u0432 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0430\u0445\u043e\u0434\u044f\u0442\u0441\u044f \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u044b. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u043e\u0432 \u0437\u0430\u0434\u0430\u043d\u044b \u0432 \u043f\u043e\u0440\u044f\u0434\u043a\u0435 \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430\u043d\u0438\u044f.", "output_spec": "\u0415\u0441\u043b\u0438 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u043d\u0435 \u0441\u043c\u043e\u0436\u0435\u0442 \u0434\u043e\u0431\u0440\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u0448\u043a\u043e\u043b\u044b \u0434\u043e \u0434\u043e\u043c\u0430 \u0442\u043e\u043b\u044c\u043a\u043e \u043d\u0430 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430\u0445, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 -1. \u0412 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435, \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0410\u0440\u043a\u0430\u0434\u0438\u044e \u043d\u0443\u0436\u043d\u043e \u0432\u0437\u044f\u0442\u044c \u0432 \u0442\u043e\u0447\u043a\u0430\u0445 \u043f\u0440\u043e\u043a\u0430\u0442\u0430.", "sample_inputs": ["4 4\n3 6 8 10", "2 9\n10 20", "12 3\n4 6 7 9 10 11 13 15 17 18 20 21"], "sample_outputs": ["2", "-1", "6"], "notes": "\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u0434\u043e\u043b\u0436\u0435\u043d \u0432\u0437\u044f\u0442\u044c \u043f\u0435\u0440\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434 \u0432 \u043f\u0435\u0440\u0432\u043e\u043c \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0435 \u0438 \u0434\u043e\u0435\u0445\u0430\u0442\u044c \u043d\u0430 \u043d\u0451\u043c \u0434\u043e \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0430. \u0412\u043e \u0432\u0442\u043e\u0440\u043e\u043c \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0435 \u043e\u043d \u0434\u043e\u043b\u0436\u0435\u043d \u0432\u0437\u044f\u0442\u044c \u043d\u043e\u0432\u044b\u0439 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434, \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043e\u043d \u0441\u043c\u043e\u0436\u0435\u0442 \u0434\u043e\u0431\u0440\u0430\u0442\u044c\u0441\u044f \u0434\u043e \u0447\u0435\u0442\u0432\u0435\u0440\u0442\u043e\u0433\u043e \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0430, \u0440\u044f\u0434\u043e\u043c \u0441 \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u0438 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0435\u0433\u043e \u0434\u043e\u043c. \u041f\u043e\u044d\u0442\u043e\u043c\u0443 \u0410\u0440\u043a\u0430\u0434\u0438\u044e \u043d\u0443\u0436\u043d\u043e \u0432\u0441\u0435\u0433\u043e \u0434\u0432\u0430 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430, \u0447\u0442\u043e\u0431\u044b \u0434\u043e\u0431\u0440\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u0448\u043a\u043e\u043b\u044b \u0434\u043e \u0434\u043e\u043c\u0430.\u0412\u043e \u0432\u0442\u043e\u0440\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0432\u0441\u0435\u0433\u043e \u0434\u0432\u0430 \u0432\u0435\u043b\u043e\u043f\u0440\u043e\u043a\u0430\u0442\u0430, \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u043c\u0435\u0436\u0434\u0443 \u043a\u043e\u0442\u043e\u0440\u044b\u043c\u0438 10. \u041d\u043e \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u043e\u0435\u0445\u0430\u0442\u044c \u043d\u0430 \u043e\u0434\u043d\u043e\u043c \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0435, \u0440\u0430\u0432\u043d\u043e 9. \u041f\u043e\u044d\u0442\u043e\u043c\u0443 \u0410\u0440\u043a\u0430\u0434\u0438\u0439 \u043d\u0435 \u0441\u043c\u043e\u0436\u0435\u0442 \u0434\u043e\u0431\u0440\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u0448\u043a\u043e\u043b\u044b \u0434\u043e \u0434\u043e\u043c\u0430 \u0442\u043e\u043b\u044c\u043a\u043e \u043d\u0430 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430\u0445."}, "positive_code": [{"source_code": " object CF928A extends App {\n val sc = new java.util.Scanner(System.in)\n val n: Int = sc.nextInt()\n val k: Int = sc.nextInt()\n val checkPoints: List[Int] = (1 to n).toList.foldLeft(List.empty[Int]){case (list, _) => list :+ sc.nextInt()}\n def shortWay(checkPoints: List[Int], result: Int): Int = {\n def nextCheckPoint(checkPoints: List[Int], kmRemaining: Int): List[Int] = if (checkPoints.tail.nonEmpty) {\n val a = checkPoints.head + kmRemaining - checkPoints.tail.head\n if (a >= 0){\n nextCheckPoint(checkPoints.tail, a)\n } else {\n checkPoints\n }\n } else checkPoints\n if (checkPoints.tail.nonEmpty) {\n val remainingList = nextCheckPoint(checkPoints, k)\n if (remainingList.tail.nonEmpty) {\n if (remainingList.tail.head - remainingList.head > k || remainingList == checkPoints) {\n -1\n } else {\n shortWay(remainingList, result + 1)\n }\n } else result\n } else result\n }\n println(shortWay(checkPoints, 1))\n }"}], "negative_code": [], "src_uid": "874c4847db340f10ac55259cba259723"} {"nl": {"description": "Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $$$a$$$ with elements $$$a_1, a_2, \\ldots, a_{2k-1}$$$, is the array $$$b$$$ with elements $$$b_1, b_2, \\ldots, b_{k}$$$ such that $$$b_i$$$ is equal to the median of $$$a_1, a_2, \\ldots, a_{2i-1}$$$ for all $$$i$$$. Omkar has found an array $$$b$$$ of size $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$, $$$-10^9 \\leq b_i \\leq 10^9$$$). Given this array $$$b$$$, Ray wants to test Omkar's claim and see if $$$b$$$ actually is an OmkArray of some array $$$a$$$. Can you help Ray?The median of a set of numbers $$$a_1, a_2, \\ldots, a_{2i-1}$$$ is the number $$$c_{i}$$$ where $$$c_{1}, c_{2}, \\ldots, c_{2i-1}$$$ represents $$$a_1, a_2, \\ldots, a_{2i-1}$$$ sorted in nondecreasing order. ", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) \u2014 the length of the array $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$-10^9 \\leq b_i \\leq 10^9$$$) \u2014 the elements of $$$b$$$. It is guaranteed the sum of $$$n$$$ across all test cases does not exceed $$$2 \\cdot 10^5$$$. ", "output_spec": "For each test case, output one line containing YES if there exists an array $$$a$$$ such that $$$b_i$$$ is the median of $$$a_1, a_2, \\dots, a_{2i-1}$$$ for all $$$i$$$, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).", "sample_inputs": ["5\n4\n6 2 1 3\n1\n4\n5\n4 -8 5 6 -7\n2\n3 3\n4\n2 1 2 3", "5\n8\n-8 2 -6 -5 -4 3 3 2\n7\n1 1 3 1 0 -2 -1\n7\n6 12 8 6 2 6 10\n6\n5 1 2 3 6 7\n5\n1 3 4 3 0"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES", "NO\nYES\nNO\nNO\nNO"], "notes": "NoteIn the second case of the first sample, the array $$$[4]$$$ will generate an OmkArray of $$$[4]$$$, as the median of the first element is $$$4$$$.In the fourth case of the first sample, the array $$$[3, 2, 5]$$$ will generate an OmkArray of $$$[3, 3]$$$, as the median of $$$3$$$ is $$$3$$$ and the median of $$$2, 3, 5$$$ is $$$3$$$.In the fifth case of the first sample, the array $$$[2, 1, 0, 3, 4, 4, 3]$$$ will generate an OmkArray of $$$[2, 1, 2, 3]$$$ as the median of $$$2$$$ is $$$2$$$ the median of $$$0, 1, 2$$$ is $$$1$$$ the median of $$$0, 1, 2, 3, 4$$$ is $$$2$$$ and the median of $$$0, 1, 2, 3, 3, 4, 4$$$ is $$$3$$$. In the second case of the second sample, the array $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ will generate an OmkArray of $$$[1, 1, 3, 1, 0, -2, -1]$$$, as the median of $$$1$$$ is $$$1$$$ the median of $$$0, 1, 4$$$ is $$$1$$$ the median of $$$0, 1, 3, 4, 5$$$ is $$$3$$$ the median of $$$-2, -2, 0, 1, 3, 4, 5$$$ is $$$1$$$ the median of $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$0$$$ the median of $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$-2$$$ and the median of $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ is $$$-1$$$ For all cases where the answer is NO, it can be proven that it is impossible to find an array $$$a$$$ such that $$$b$$$ is the OmkArray of $$$a$$$."}, "positive_code": [{"source_code": "//package codeforces\n\nimport java.util.TreeSet\n\nobject P1536D extends App {\n\n val cases = lines.next().toInt\n (0 until cases).foreach { _ =>\n lines.next()\n val xs = lines.next().split(\" \").map(_.toInt)\n if (solve(xs)) println(\"YES\")\n else println(\"NO\")\n }\n\n lazy val lines = if (System.getProperty(\"user.dir\").contains(\"algosscala\")) {\n \"\"\"5\n |4\n |6 2 1 3\n |1\n |4\n |5\n |4 -8 5 6 -7\n |2\n |3 3\n |4\n |2 1 2 3\n |\"\"\".stripMargin.linesIterator\n } else {\n io.Source.stdin.getLines()\n }\n\n def solve(xs: Array[Int]) = {\n val s = new TreeSet[Int]()\n s.add(xs.head)\n var prev = xs.head\n !xs.tail.exists { x =>\n val lowerLimit = Option(s.floor(prev - 1)).getOrElse(Int.MinValue)\n val higherLimit = Option(s.ceiling(prev + 1)).getOrElse(Int.MaxValue)\n if (lowerLimit <= x && x <= higherLimit) {\n s.add(x)\n prev = x\n false\n } else {\n true\n }\n }\n }\n\n}\n"}], "negative_code": [{"source_code": "//package codeforces\n\nobject Testing extends App {\n lazy val lines = if (System.getProperty(\"user.dir\").contains(\"algosscala\")) {\n \"\"\"2\n |6 4\n |1 2\n |6 7\n |9 12\n |24 24\n |24 25\n |41 50\n |14 24 24 24 24 4\n |1 1\n |42 42\n |24\n |\"\"\".stripMargin.linesIterator\n } else {\n io.Source.stdin.getLines()\n }\n\n}\n"}], "src_uid": "6ed24fef3b7f0f0dc040fc5bed535209"} {"nl": {"description": "Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n\u2009=\u2009p1\u00b7p2\u00b7...\u00b7pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109\u2009+\u20097 is the password to the secret data base. Now he wants to calculate this value.", "input_spec": "The first line of the input contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of primes in factorization of n. The second line contains m primes numbers pi (2\u2009\u2264\u2009pi\u2009\u2264\u2009200\u2009000).", "output_spec": "Print one integer\u00a0\u2014 the product of all divisors of n modulo 109\u2009+\u20097.", "sample_inputs": ["2\n2 3", "3\n2 3 2"], "sample_outputs": ["36", "1728"], "notes": "NoteIn the first sample n\u2009=\u20092\u00b73\u2009=\u20096. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1\u00b72\u00b73\u00b76\u2009=\u200936.In the second sample 2\u00b73\u00b72\u2009=\u200912. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1\u00b72\u00b73\u00b74\u00b76\u00b712\u2009=\u20091728."}, "positive_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 % 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"}, {"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"} {"nl": {"description": "President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The \u00abperiod\u00bb character (\u00ab.\u00bb) stands for an empty cell. ", "input_spec": "The first line contains two separated by a space integer numbers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the length and the width of the office-room, and c character \u2014 the President's desk colour. The following n lines contain m characters each \u2014 the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.", "output_spec": "Print the only number \u2014 the amount of President's deputies.", "sample_inputs": ["3 4 R\nG.B.\n.RR.\nTTT.", "3 3 Z\n...\n.H.\n..Z"], "sample_outputs": ["2", "0"], "notes": null}, "positive_code": [{"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}"}, {"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 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"}, {"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"}], "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"} {"nl": {"description": "Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1){ int j = i; while (j > 0 && a[j] < a[j - 1]) { swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1] j = j - 1; }}Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n\u2009-\u20091. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the length of the permutation. The second line contains n different integers from 0 to n\u2009-\u20091, inclusive \u2014 the actual permutation.", "output_spec": "Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i,\u2009j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.", "sample_inputs": ["5\n4 0 3 1 2", "5\n1 2 3 4 0"], "sample_outputs": ["3 2", "3 4"], "notes": "NoteIn the first sample the appropriate pairs are (0,\u20093) and (0,\u20094). In the second sample the appropriate pairs are (0,\u20094), (1,\u20094), (2,\u20094) and (3,\u20094)."}, "positive_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\n val n = readInt\n val as = readInts(n)\n\n var swaps = 0\n \n val dR = Array.fill(n, n)(0)\n \n for (i <- n - 2 to 0 by - 1) {\n \tfor (x <- 0 until as(i + 1)) dR(i)(x) = dR(i + 1)(x)\n \tfor (x <- as(i + 1) until n) dR(i)(x) = dR(i + 1)(x) + 1\n \tswaps += dR(i)(as(i))\n }\n\n var minSwaps = swaps\n var count = 0\n\n for (i <- 0 until n) {\n val swapsii = dR(i)(as(i))\n for (j <- i + 1 until n) if (as(j) < as(i)) {\n \tval swapsij = dR(j)(as(i))\n \tval swapsji = dR(i)(as(j))\n \tval swapsjj = dR(j)(as(j))\n \tval swaps2 = swaps - 2 * (swapsii + swapsjj - swapsij - swapsji) - 1\n \tif (swaps2 < minSwaps) {\n \t\tminSwaps = swaps2\n \t\tcount = 1\n \t} else if (swaps2 == minSwaps) count += 1\n }\n }\n\n println(minSwaps + \" \" + count)\n}"}], "negative_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 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\n println()\n}"}], "src_uid": "38dc16395b742f2a0e9f359a8bf33061"} {"nl": {"description": "You are given $$$n$$$ blocks, each of them is of the form [color$$$_1$$$|value|color$$$_2$$$], where the block can also be flipped to get [color$$$_2$$$|value|color$$$_1$$$]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.The value of the sequence is defined as the sum of the values of the blocks in this sequence.Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.", "input_spec": "The first line of input contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of given blocks. Each of the following $$$n$$$ lines describes corresponding block and consists of $$$\\mathrm{color}_{1,i}$$$, $$$\\mathrm{value}_i$$$ and $$$\\mathrm{color}_{2,i}$$$ ($$$1 \\le \\mathrm{color}_{1,i}, \\mathrm{color}_{2,i} \\le 4$$$, $$$1 \\le \\mathrm{value}_i \\le 100\\,000$$$).", "output_spec": "Print exactly one integer\u00a0\u2014 the maximum total value of the subset of blocks, which makes a valid sequence.", "sample_inputs": ["6\n2 1 4\n1 2 4\n3 4 4\n2 8 3\n3 16 3\n1 32 2", "7\n1 100000 1\n1 100000 2\n1 100000 2\n4 50000 3\n3 50000 4\n4 50000 4\n3 50000 3", "4\n1 1000 1\n2 500 2\n3 250 3\n4 125 4"], "sample_outputs": ["63", "300000", "1000"], "notes": "NoteIn the first example, it is possible to form a valid sequence from all blocks.One of the valid sequences is the following:[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]The first block from the input ([2|1|4] $$$\\to$$$ [4|1|2]) and second ([1|2|4] $$$\\to$$$ [4|2|1]) are flipped.In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):[2|100000|1] [1|100000|1] [1|100000|2]In the third example, it is not possible to form a valid sequence of two or more blocks, so the answer is a sequence consisting only of the first block since it is the block with the largest value."}, "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 color = Array(\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (1, 2),\n (1, 3),\n (1, 4),\n (2, 3),\n (2, 4),\n (3, 4)\n ) map (a => (a._1 - 1, a._2 - 1))\n\n val edge = {\n val map = color.zipWithIndex.toMap\n\n (c1: Int, c2: Int) => {\n map(min(c1, c2), max(c1, c2))\n }\n }\n\n val E = Array.fill[ArrayBuffer[Int]](10)(ArrayBuffer())\n\n rep(N) { _ =>\n val c1 = ni() - 1\n val v = ni()\n val c2 = ni() - 1\n E(edge(c1, c2)) += v\n }\n\n val sum = E map (_.sum)\n val ms = E map (a => if (a.isEmpty) -1 else a.min)\n\n def containsEdge(colors: Array[Int], e: Int) = {\n val (c1, c2) = color(e)\n (colors contains c1) && (colors contains c2)\n }\n\n var ans = 0\n rep(1 << 10) { bitSet =>\n var valid = true // \u3053\u306eset\u306e\u8fba\u306e\u524a\u9664\u3092\u884c\u3048\u308b\u304b\n val uf = new UnionFind(4)\n rep(10) { i =>\n val len = if ((bitSet & (1 << i)) > 0) E(i).length - 1 else E(i).length\n if (len < 0) valid = false\n else if (len > 0){\n val (c1, c2) = color(i)\n uf.unite(c1, c2)\n }\n }\n if (valid) {\n disjointSets(uf).filter(_.nonEmpty) foreach { set =>\n val deg = Array.ofDim[Int](4)\n var S = 0\n rep(10) { i =>\n if (containsEdge(set, i)) {\n val (c1, c2) = color(i)\n val remove = (bitSet & (1 << i)) > 0\n val len = if (remove) E(i).length - 1 else E(i).length\n deg(c1) += len\n deg(c2) += len\n S += sum(i) - (if (remove) ms(i) else 0)\n }\n }\n val odds = deg count (_ % 2 == 1)\n if (odds == 0 || odds == 2) ans = max(ans, S)\n }\n }\n }\n\n out.println(ans)\n }\n\n def disjointSets(uf: UnionFind): Array[Array[Int]] = {\n val N = uf.n\n val cnt = Array.ofDim[Int](N)\n val disjoints = Array.ofDim[Array[Int]](N)\n rep(N) { i => cnt(uf.find(i)) += 1 }\n rep(N) { i => disjoints(i) = Array.ofDim(cnt(uf.find(i))) }\n rep(N) { i =>\n val id = uf.find(i)\n disjoints(id)(cnt(id) - 1) = i\n cnt(id) -= 1\n }\n disjoints\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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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}"}], "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 color = Array(\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (1, 2),\n (1, 3),\n (1, 4),\n (2, 3),\n (2, 4),\n (3, 4)\n ) map (a => (a._1 - 1, a._2 - 1))\n\n val edge = {\n val map = color.zipWithIndex.toMap\n\n (c1: Int, c2: Int) => {\n map(min(c1, c2), max(c1, c2))\n }\n }\n\n val E = Array.fill[ArrayBuffer[Int]](10)(ArrayBuffer())\n val deg = Array.ofDim[Int](4)\n val uf = new UnionFind(4)\n\n rep(N) { _ =>\n val c1 = ni() - 1\n val v = ni()\n val c2 = ni() - 1\n uf.unite(c1, c2)\n E(edge(c1, c2)) += v\n deg(c1) += 1\n deg(c2) += 1\n }\n\n val joints = Array.fill[mutable.Set[Int]](4)(mutable.Set())\n rep(4) { i =>\n joints(uf.find(i)) += i\n }\n\n val ms = E map (a => if (a.isEmpty) -1 else a.min)\n\n def containsEdge(colors: mutable.Set[Int], e: Int) = {\n val (c1, c2) = color(e)\n (colors contains c1) && (colors contains c2)\n }\n\n var ans = 0\n joints.filter(_.nonEmpty) foreach { colors =>\n val S = E.zipWithIndex\n .filter(a => containsEdge(colors, a._2))\n .map(_._1.sum).sum\n \n rep(1 << 10) { set =>\n val d = deg.clone()\n var valid = true // \u3053\u306eset\u306e\u8fba\u306e\u524a\u9664\u3092\u884c\u3048\u308b\u304b\n var subtracts = 0\n rep(10) { i =>\n if (((set >>> i) & 1) > 0) {\n if (ms(i) == -1 || !containsEdge(colors, i)) valid = false\n else {\n val (c1, c2) = color(i)\n d(c1) -= 1\n d(c2) -= 1\n subtracts += ms(i)\n }\n }\n }\n val odds = d count (_ % 2 == 1)\n if (valid && odds == 0 || odds == 2) ans = max(ans, S - subtracts)\n }\n }\n\n out.println(ans)\n }\n\n class UnionFind(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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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 N = ni()\n val color = Array(\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (1, 2),\n (1, 3),\n (1, 4),\n (2, 3),\n (2, 4),\n (3, 4)\n ) map (a => (a._1 - 1, a._2 - 1))\n\n val edge = {\n val map = color.zipWithIndex.toMap\n\n (c1: Int, c2: Int) => {\n map(min(c1, c2), max(c1, c2))\n }\n }\n\n val E = Array.fill[ArrayBuffer[Int]](10)(ArrayBuffer())\n val deg = Array.ofDim[Int](4)\n val uf = new UnionFind(4)\n\n rep(N) { _ =>\n val c1 = ni() - 1\n val v = ni()\n val c2 = ni() - 1\n uf.unite(c1, c2)\n E(edge(c1, c2)) += v\n deg(c1) += 1\n deg(c2) += 1\n }\n\n val joints = Array.fill[mutable.Set[Int]](4)(mutable.Set())\n rep(4) { i =>\n joints(uf.find(i)) += i\n }\n\n val ms = E map (a => if (a.isEmpty) -1 else a.min)\n\n def containsEdge(colors: mutable.Set[Int], e: Int) = {\n val (c1, c2) = color(e)\n (colors contains c1) && (colors contains c2)\n }\n\n var ans = 0\n joints.filter(_.nonEmpty) foreach { colors =>\n val S = E.zipWithIndex\n .filter(a => containsEdge(colors, a._2))\n .map(_._1.sum).sum\n \n rep(1 << 10) { set =>\n val d = Array.ofDim[Int](4)\n rep(4)(i => if (containsEdge(colors, i)) d(i) = deg(i)) // colors\u306b\u542b\u307e\u308c\u3066\u3044\u308b\u3082\u306e\u3060\u3051\u30b3\u30d4\u30fc\u3059\u308b\n\n var valid = true // \u3053\u306eset\u306e\u8fba\u306e\u524a\u9664\u3092\u884c\u3048\u308b\u304b\n var subtracts = 0\n rep(10) { i =>\n if (((set >>> i) & 1) > 0) {\n if (ms(i) == -1 || !containsEdge(colors, i)) valid = false\n else {\n val (c1, c2) = color(i)\n d(c1) -= 1\n d(c2) -= 1\n subtracts += ms(i)\n }\n }\n }\n val odds = d count (_ % 2 == 1)\n if (valid && odds == 0 || odds == 2) ans = max(ans, S - subtracts)\n }\n }\n\n out.println(ans)\n }\n\n class UnionFind(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 class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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}"}], "src_uid": "6832d12db46bce3bb1bd6b0950b1eb32"} {"nl": {"description": "One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.We assume that valid addresses are only the e-mail addresses which meet the following criteria: the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter; then must go character '@'; then must go a non-empty sequence of letters or numbers; then must go character '.'; the address must end with a non-empty sequence of letters. You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers l1,\u2009l1\u2009+\u20091,\u2009l1\u2009+\u20092,\u2009...,\u2009r1 and the other one consisting of the characters of the string with numbers l2,\u2009l2\u2009+\u20091,\u2009l2\u2009+\u20092,\u2009...,\u2009r2, are considered distinct if l1\u2009\u2260\u2009l2 or r1\u2009\u2260\u2009r2.", "input_spec": "The first and the only line contains the sequence of characters s1s2... sn (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the saved string. It is guaranteed that the given string contains only small English letters, digits and characters '.', '_', '@'.", "output_spec": "Print in a single line the number of substrings that are valid e-mail addresses.", "sample_inputs": ["gerald.agapov1991@gmail.com", "x@x.x@x.x_e_@r1.com", "a___@1.r", ".asd123__..@"], "sample_outputs": ["18", "8", "1", "0"], "notes": "NoteIn the first test case all the substrings that are correct e-mail addresses begin from one of the letters of the word agapov and end in one of the letters of the word com.In the second test case note that the e-mail x@x.x is considered twice in the answer. Note that in this example the e-mail entries overlap inside the string."}, "positive_code": [{"source_code": "/**\n * I've tried to make this piece of code as readable as possible.\n * Enjoy hacking it!\n */\nimport Character._\n\nobject E extends App {\n\n val s = readLine.toCharArray\n var res = 0L\n\n var start = 0\n while (start < s.length) {\n val c = s(start)\n if (isLetter(c)) {\n var eta = start + 1\n var let = 1L\n while (eta < s.length && (isLetterOrDigit(s(eta)) || s(eta) == '_')) {\n if (isLetter(s(eta))) let += 1\n eta += 1\n }\n if (eta < s.length && s(eta) == '@') {\n var dot = eta + 1\n while (dot < s.length && isLetterOrDigit(s(dot))) dot += 1\n if (dot > eta + 1 && dot < s.length && s(dot) == '.') {\n var end = dot + 1\n while (end < s.length && isLetter(s(end))) end += 1\n res += let * (end - dot - 1)\n start = dot\n } else start = eta\n } else start = eta\n }\n start += 1\n }\n\n println(res)\n}"}], "negative_code": [], "src_uid": "08924ff11b857559a44c1637761b508a"} {"nl": {"description": "You are given an array of integers $$$a_1,a_2,\\ldots,a_n$$$. Find the maximum possible value of $$$a_ia_ja_ka_la_t$$$ among all five indices $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\le t\\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$5\\le n\\le 10^5$$$) \u2014 the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$-3\\times 10^3\\le a_i\\le 3\\times 10^3$$$) \u2014 given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, print one integer \u2014 the answer to the problem.", "sample_inputs": ["4\n5\n-1 -2 -3 -4 -5\n6\n-1 -2 -3 1 2 -1\n6\n-1 0 0 0 -1 -1\n6\n-9 -7 -5 -3 -2 1"], "sample_outputs": ["-120\n12\n0\n945"], "notes": "NoteIn the first test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\\cdot (-2) \\cdot (-3)\\cdot (-4)\\cdot (-5)=-120$$$.In the second test case, choosing $$$a_1,a_2,a_3,a_5,a_6$$$ is a best choice: $$$(-1)\\cdot (-2) \\cdot (-3)\\cdot 2\\cdot (-1)=12$$$.In the third test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\\cdot 0\\cdot 0\\cdot 0\\cdot (-1)=0$$$.In the fourth test case, choosing $$$a_1,a_2,a_3,a_4,a_6$$$ is a best choice: $$$(-9)\\cdot (-7) \\cdot (-5)\\cdot (-3)\\cdot 1=945$$$."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given a set Y of n distinct positive integers y1,\u2009y2,\u2009...,\u2009yn.Set X of n distinct positive integers x1,\u2009x2,\u2009...,\u2009xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: Take any integer xi and multiply it by two, i.e. replace xi with 2\u00b7xi. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2\u00b7xi\u2009+\u20091. Note that integers in X are not required to be distinct after each operation.Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.Note, that any set of integers (or its permutation) generates itself.You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950\u2009000)\u00a0\u2014 the number of elements in Y. The second line contains n integers y1,\u2009...,\u2009yn (1\u2009\u2264\u2009yi\u2009\u2264\u2009109), that are guaranteed to be distinct.", "output_spec": "Print n integers\u00a0\u2014 set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them.", "sample_inputs": ["5\n1 2 3 4 5", "6\n15 14 3 13 1 12", "6\n9 7 13 17 5 11"], "sample_outputs": ["4 5 2 3 1", "12 13 14 7 3 1", "4 5 2 6 3 1"], "notes": null}, "positive_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 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"}, {"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"} {"nl": {"description": "You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.", "input_spec": "The first line contains two integers nA,\u2009nB (1\u2009\u2264\u2009nA,\u2009nB\u2009\u2264\u2009105), separated by a space \u2014 the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1\u2009\u2264\u2009k\u2009\u2264\u2009nA,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009nB), separated by a space. The third line contains nA numbers a1,\u2009a2,\u2009... anA (\u2009-\u2009109\u2009\u2264\u2009a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009anA\u2009\u2264\u2009109), separated by spaces \u2014 elements of array A. The fourth line contains nB integers b1,\u2009b2,\u2009... bnB (\u2009-\u2009109\u2009\u2264\u2009b1\u2009\u2264\u2009b2\u2009\u2264\u2009...\u2009\u2264\u2009bnB\u2009\u2264\u2009109), separated by spaces \u2014 elements of array B.", "output_spec": "Print \"YES\" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print \"NO\" (without the quotes).", "sample_inputs": ["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: ."}, "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 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 "}, {"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"} {"nl": {"description": "Luke likes to eat. There are $$$n$$$ piles of food aligned in a straight line in front of him. The $$$i$$$-th pile contains $$$a_i$$$ units of food. Luke will walk from the $$$1$$$-st pile towards the $$$n$$$-th pile, and he wants to eat every pile of food without walking back. When Luke reaches the $$$i$$$-th pile, he can eat that pile if and only if $$$|v - a_i| \\leq x$$$, where $$$x$$$ is a fixed integer, and $$$v$$$ is Luke's food affinity.Before Luke starts to walk, he can set $$$v$$$ to any integer. Also, for each $$$i$$$ ($$$1 \\leq i \\leq n$$$), Luke can change his food affinity to any integer before he eats the $$$i$$$-th pile.Find the minimum number of changes needed to eat every pile of food.Note that the initial choice for $$$v$$$ is not considered as a change.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. The description of test cases follows. For each test case, the first line contains two integers, $$$n, x$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$, $$$1 \\leq x \\leq 10^9$$$) \u2014 the number of piles, and the maximum difference between the size of a pile and Luke's food affinity, such that Luke can eat the pile. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots , a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output an integer on a separate line, which is the minimum number of changes needed.", "sample_inputs": ["7\n\n5 3\n\n3 8 5 6 7\n\n5 3\n\n3 10 9 8 7\n\n12 8\n\n25 3 3 17 8 6 1 16 15 25 17 23\n\n10 2\n\n1 2 3 4 5 6 7 8 9 10\n\n8 2\n\n2 4 6 8 6 4 12 14\n\n8 2\n\n2 7 8 9 6 13 21 28\n\n15 5\n\n11 4 13 23 7 10 5 21 20 11 17 5 29 16 11"], "sample_outputs": ["0\n1\n2\n1\n2\n4\n6"], "notes": "NoteIn the first test case, Luke can set $$$v$$$ to $$$5$$$ before he starts to walk. And he can walk straight to eat every piles of food without changing $$$v$$$.In the second test case, Luke can set $$$v$$$ to $$$3$$$ before he starts to walk. And he could change $$$v$$$ to $$$10$$$ before he eats the second pile. After that, he can walk straight to eat remaining food without changing $$$v$$$.In the fourth test case, Luke can set $$$v$$$ to $$$3$$$ before he starts to walk. And he could change $$$v$$$ to $$$8$$$ before he eats the sixth pile. After that, he can walk straight to eat remaining food without changing $$$v$$$.In the fifth test case, Luke can set $$$v$$$ to $$$4$$$ before he starts to walk. And he could change $$$v$$$ to $$$6$$$ before he eats the fourth pile. Then he could change $$$v$$$ to $$$12$$$ before he eats the seventh pile. After that, he can walk straight to eat remaining food without changing $$$v$$$."}, "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 var c: Long = 0\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l1 = tokenizer.nextToken().toInt\r\n val l2 = tokenizer.nextToken().toInt * 2\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val a0 = tokenizer.nextToken().toInt\r\n var l = a0\r\n var m = a0\r\n for (i <- 1 until l1) {\r\n val a = tokenizer.nextToken().toInt\r\n l = min(a,l)\r\n m = max(a,m)\r\n if (m-l > l2) {\r\n l = a\r\n m = a\r\n c+=1\r\n }\r\n }\r\n println(c)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "1f520f2796094b0f0c4e11e231f9ca8c"} {"nl": {"description": "Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\\frac{n}{2}$$$ elements (where $$$n$$$ \u2014 length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \\dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^3$$$, $$$n$$$ is even) \u00a0\u2014 length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 1$$$) \u00a0\u2014 elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.", "output_spec": "For each test case, firstly, print $$$k$$$ ($$$\\frac{n}{2} \\leq k \\leq n$$$) \u2014 number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them. ", "sample_inputs": ["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"], "sample_outputs": ["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"], "notes": "NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything."}, "positive_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\"$req\\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 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"}, {"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"}], "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"} {"nl": {"description": "You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second: Select some distinct indices $$$i_{1}, i_{2}, \\ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \\ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \\le a_{2} \\le \\ldots \\le a_{n}$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \\le n \\le 10^{5}$$$)\u00a0\u2014 the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$ ($$$-10^{9} \\le a_{i} \\le 10^{9}$$$).", "output_spec": "For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.", "sample_inputs": ["3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4"], "sample_outputs": ["2\n0\n3"], "notes": "NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$."}, "positive_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 val (_, diff) = an.tail.foldLeft((an.head, 0)) { case ((p, d), c) => if (c >= p) (c, d) else (p, d.max(p - c)) }\n val sec = 1 + -1.max(math.floor(math.log10(diff) / math.log10(2)).toInt)\n\n println(sec)\n }\n}\n"}], "negative_code": [], "src_uid": "bfc2e7de37db4a0a74cdd55f2124424a"} {"nl": {"description": "Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^5$$$) \u2014 the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \\le k, n \\le 10^9, 1 \\le b < a \\le 10^9$$$) \u2014 the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.", "output_spec": "For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.", "sample_inputs": ["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"], "sample_outputs": ["4\n-1\n5\n2\n0\n1"], "notes": "NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string \"for\" is contained as a substring in strings \"codeforces\", \"for\" and \"therefore\", but is not contained as a substring in strings \"four\", \"fofo\" and \"rof\".", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.", "output_spec": "If it is impossible to reorder $$$n$$$ given strings in required order, print \"NO\" (without quotes). Otherwise print \"YES\" (without quotes) and $$$n$$$ given strings in required order.", "sample_inputs": ["5\na\naba\nabacaba\nba\naba", "5\na\nabacaba\nba\naba\nabab", "3\nqwerty\nqwerty\nqwerty"], "sample_outputs": ["YES\na\nba\naba\naba\nabacaba", "NO", "YES\nqwerty\nqwerty\nqwerty"], "notes": "NoteIn the second example you cannot reorder the strings because the string \"abab\" is not a substring of the string \"abacaba\"."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "5c33d1f970bcc2ffaea61d5407b877b2"} {"nl": {"description": "Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.", "input_spec": "The first line contains two space-separated integers: n and p (1\u2009\u2264\u2009n\u2009\u2264\u20091000; 1\u2009\u2264\u2009p\u2009\u2264\u200926). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).", "output_spec": "If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print \"NO\" (without the quotes).", "sample_inputs": ["3 3\ncba", "3 4\ncba", "4 4\nabcd"], "sample_outputs": ["NO", "cbd", "abda"], "notes": "NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1\u2009=\u2009t1, ..., si\u2009=\u2009ti, si\u2009+\u20091\u2009>\u2009ti\u2009+\u20091.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of elements in a and the parameter k. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091) \u2014 the elements of a.", "output_spec": "On the first line print a non-negative integer z \u2014 the maximal value of f(a) after no more than k changes of zeroes to ones. On the second line print n integers aj \u2014 the elements of the array a after the changes. If there are multiple answers, you can print any one of them.", "sample_inputs": ["7 1\n1 0 0 1 1 0 1", "10 2\n1 0 0 1 0 1 0 1 0 1"], "sample_outputs": ["4\n1 0 0 1 1 1 1", "5\n1 0 0 1 1 1 1 1 0 1"], "notes": null}, "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().filter(_ != ' ')\n val res = data.indices.foldLeft((0, 0, k, 0, (0, 0))) {\n case (acc@(max, soFar, leftover, start, maxPair), i) =>\n// println(acc)\n if (data(i) == '1' || leftover > 0) {\n val nLeftover = if (data(i) == '0') leftover - 1 else leftover\n if (max < soFar + 1)\n (soFar + 1, soFar + 1, nLeftover, start, (start, i))\n else\n (max, soFar + 1, nLeftover, start, maxPair)\n }\n else {\n val nStart = (start to i).find(i => data(i) == '0').get + 1\n (max, soFar + start - nStart + 1, 0, nStart, maxPair)\n }\n }\n println(res._1)\n println(data.indices.map{ i =>\n if (k > 0 && i >= res._5._1 && i <= res._5._2)\n '1'\n else\n data(i)\n }.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) = in.next().split(' ').map(_.toInt)\n val data = in.next().filter(_ != ' ')\n val res = data.indices.foldLeft((0, 0, k, 0, (0, 0))) {\n case (acc@(max, soFar, leftover, start, maxPair), i) =>\n// println(acc)\n if (data(i) == '1' || leftover > 0) {\n val nLeftover = if (data(i) == '0') leftover - 1 else leftover\n if (max < soFar + 1)\n (soFar + 1, soFar + 1, nLeftover, start, (start, i))\n else\n (max, soFar + 1, nLeftover, start, maxPair)\n }\n else {\n val nStart = (start to i).find(i => data(i) == '0').get\n// println(\"nStart = \" + nStart)\n (max, soFar + start - nStart, Math.max(0, nStart - start - 1), nStart + 1, maxPair)\n }\n }\n// println(res)\n println(res._1)\n println(data.indices.map{ i =>\n if (k > 0 && i >= res._5._1 && i <= res._5._2)\n '1'\n else\n data(i)\n }.mkString(\" \"))\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 = in.next().filter(_ != ' ')\n val res = data.indices.foldLeft((0, 0, k, 0, (0, 0))) {\n case (acc@(max, soFar, leftover, start, maxPair), i) =>\n// println(acc)\n if (data(i) == '1' || leftover > 0) {\n val nLeftover = if (data(i) == '0') leftover - 1 else leftover\n if (max < soFar + 1)\n (soFar + 1, soFar + 1, nLeftover, start, (start, i))\n else\n (max, soFar + 1, nLeftover, start, maxPair)\n }\n else {\n val nStart = (start to i).find(i => data(i) == '0').get\n// println(\"nStart = \" + nStart)\n (max, soFar + start - nStart, Math.max(0, nStart - start - 1), nStart + 1, maxPair)\n }\n }\n// println(res)\n println(res._1)\n println(data.indices.map{ i =>\n if (i >= res._5._1 && i <= res._5._2)\n '1'\n else\n data(i)\n }.mkString(\" \"))\n}\n"}], "src_uid": "ec9b03577868d8999bcc54dfc1aae056"} {"nl": {"description": "Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \\times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \\times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \\times 3$$$ square. What is the maximum side length of the square Ujan can get?", "input_spec": "The first line of input contains a single integer $$$k$$$ ($$$1 \\leq k \\leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 1\\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq n$$$), the lengths of the planks.", "output_spec": "For each of the test cases, output a single integer, the maximum possible side length of the square.", "sample_inputs": ["4\n5\n4 3 1 4 5\n4\n4 4 4 4\n3\n1 1 1\n5\n5 5 1 1 5"], "sample_outputs": ["3\n4\n1\n3"], "notes": "NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \\times 4$$$ square.In the third sample, the maximum possible square is $$$1 \\times 1$$$ and can be taken simply as any of the planks."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "09236a3faa7fce573a4e5e758287040f"} {"nl": {"description": "Our old friend Alexey has finally entered the University of City N \u2014 the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer \u2014 a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (li,\u2009ri) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n\u2009-\u20091) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The (i\u2009+\u20091)-th line contains integers li and ri (0\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009100) \u2014\u00a0the endpoints of the corresponding segment for the i-th student.", "output_spec": "On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.", "sample_inputs": ["3\n0 5\n2 8\n1 6", "3\n0 10\n1 5\n7 15"], "sample_outputs": ["1", "3"], "notes": "NoteNote that it's not important are clothes drying on the touching segments (e.g. (0,\u20091) and (1,\u20092)) considered to be touching or not because you need to find the length of segments.In the first test sample Alexey may use the only segment (0,\u20091). In such case his clothes will not touch clothes on the segments (1,\u20096) and (2,\u20098). The length of segment (0,\u20091) is 1.In the second test sample Alexey may dry his clothes on segments (0,\u20091) and (5,\u20097). Overall length of these segments is 3."}, "positive_code": [{"source_code": "object A extends App {\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextInt()\n val in = Array.fill(n)((sc.nextInt(), sc.nextInt()))\n var t = Array.fill(100)(false)\n for (r <- in.tail) {\n for (i <- r._1 until r._2) {\n t(i) = true;\n }\n }\n println(t.slice(in.head._1, in.head._2).count(_ == false));\n}\n"}], "negative_code": [], "src_uid": "00c29b9f74b6564e41837704c24fc318"} {"nl": {"description": "You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: the Power Gem of purple color, the Time Gem of green color, the Space Gem of blue color, the Soul Gem of orange color, the Reality Gem of red color, the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.", "input_spec": "In the first line of input there is one integer $$$n$$$ ($$$0 \\le n \\le 6$$$)\u00a0\u2014 the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.", "output_spec": "In the first line output one integer $$$m$$$ ($$$0 \\le m \\le 6$$$)\u00a0\u2014 the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.", "sample_inputs": ["4\nred\npurple\nyellow\norange", "0"], "sample_outputs": ["2\nSpace\nTime", "6\nTime\nMind\nSoul\nPower\nReality\nSpace"], "notes": "NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six."}, "positive_code": [{"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": "/**\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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends \u2014 the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way: if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal; if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal; if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase \u2014 you may know that some kick will/won't be scored, but the referee doesn't.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1\\,000$$$) \u2014 the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.", "output_spec": "For each test case, print one integer \u2014 the minimum possible number of kicks in the penalty phase.", "sample_inputs": ["4\n1?0???1001\n1111111111\n??????????\n0100000000"], "sample_outputs": ["7\n10\n6\n9"], "notes": "NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick."}, "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 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"}, {"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"} {"nl": {"description": "Amugae has a sentence consisting of $$$n$$$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges \"sample\" and \"please\" into \"samplease\".Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the number of the words in Amugae's sentence. The second line contains $$$n$$$ words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed $$$10^6$$$.", "output_spec": "In the only line output the compressed word after the merging process ends as described in the problem.", "sample_inputs": ["5\nI want to order pizza", "5\nsample please ease in out"], "sample_outputs": ["Iwantorderpizza", "sampleaseinout"], "notes": null}, "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\n val Array(n) = readInts(1)\n\n val PRIME = 1303L\n val MOD = 1000000007L\n var pmul = 1L\n\n val ps, pinvs = Array.ofDim[Long](1000001)\n val hs, hs2 = Array.ofDim[Long](1000001)\n\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 for (i <- ps.indices) {\n ps(i) = pmul\n pinvs(i) = modInverse(pmul, MOD)\n pmul = pmul * PRIME % MOD\n }\n\n def hash(from: Int, until: Int) = (hs(until) - hs(from) + MOD) * pinvs(from) % MOD\n\n def hash2(from: Int, until: Int) = (hs2(until) - hs2(from) + MOD) * pinvs(from) % MOD\n\n val ws = readLine.split(' ')\n\n val w0 = ws.head\n var h = 0L\n for (i <- 0 to w0.length) {\n hs(i) = h\n if (i < w0.length) h = (h + w0(i) * ps(i)) % MOD\n }\n\n val resBuilder = new StringBuilder(w0)\n\n def can(i: Int): Boolean = {\n hash(resBuilder.size - i, resBuilder.size) == hash2(0, i)\n }\n\n for (wi <- 1 until n) {\n val w = ws(wi)\n\n var h2 = 0L\n for (i <- 0 to w.length) {\n hs2(i) = h2\n if (i < w.length) h2 = (h2 + w(i) * ps(i)) % MOD\n }\n var prefLen = 0\n var drop = 0\n while (prefLen <= w.length && prefLen <= resBuilder.size) {\n if (can(prefLen)) drop = prefLen\n prefLen += 1\n }\n for (i <- drop until w.length) {\n val c = w(i)\n resBuilder += c\n h = (h + c * ps(resBuilder.size - 1)) % MOD\n hs(resBuilder.size) = h\n }\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(resBuilder.result())\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "586341bdd33b1dc3ab8e7f9865b5f6f6"} {"nl": {"description": "It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0\u2009<\u2009w1\u2009\u2264\u2009w2\u2009\u2264\u2009...\u2009\u2264\u2009wk holds.Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?", "input_spec": "The first line contains three integers n,\u2009m,\u2009k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species.", "output_spec": "Output \"YES\" (without quotes) if it is possible, and \"NO\" (without quotes) otherwise.", "sample_inputs": ["3 3 3\n2 2 2\n1 1 3", "4 7 9\n5 2 7 3\n3 5 2 7 3 8 7"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, if w1\u2009=\u20091,\u2009w2\u2009=\u20092,\u2009w3\u2009=\u20092.5, then Alice has a total of 2\u2009+\u20092\u2009+\u20092\u2009=\u20096 weight units, while Bob only has 1\u2009+\u20091\u2009+\u20092.5\u2009=\u20094.5.In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob\u2019s fish is always not less than the total weight of Alice\u2019s fish."}, "positive_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val line1 = readLine().split(\" \").map(_.toInt)\n val n = line1(0)\n val m = line1(1)\n val k = line1(2)\n\n val alice = readLine().split(\" \").map(_.toInt).sorted.reverse\n val bob = readLine().split(\" \").map(_.toInt).sorted.reverse.filter(_ >= alice.last)\n\n val possible = alice.size > bob.size || \n alice.zip(bob).exists((x: (Int, Int)) => x._1 > x._2)\n\n println(if (possible) \"YES\" else \"NO\")\n }\n}\n"}], "negative_code": [{"source_code": "object Main {\n def main(args: Array[String]) = {\n val line1 = readLine().split(\" \").map(_.toInt)\n val n = line1(0)\n val m = line1(1)\n val k = line1(2)\n\n val alice = readLine().split(\" \").map(_.toInt).sorted\n val bob = readLine().split(\" \").map(_.toInt).sorted.filter(_ >= alice(0))\n\n val possible = alice.size > bob.size || \n alice.zip(bob).contains((x: (Int, Int)) => x._1 > x._2)\n\n println(if (possible) \"YES\" else \"NO\")\n }\n}\n"}, {"source_code": "object Main {\n def main(args: Array[String]) = {\n val line1 = readLine().split(\" \").map(_.toInt)\n val n = line1(0)\n val m = line1(1)\n val k = line1(2)\n\n val alice = readLine().split(\" \").map(_.toInt).sorted\n val bob = readLine().split(\" \").map(_.toInt).sorted.filter(_ >= alice(0))\n\n val possible = alice.size > bob.size || \n alice.zip(bob).exists((x: (Int, Int)) => x._1 > x._2)\n\n println(if (possible) \"YES\" else \"NO\")\n }\n}\n"}], "src_uid": "01cd3f0c6bc2975118075d180bfeba2d"} {"nl": {"description": "Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit. For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \\leq x_1, y_1, x_2, y_2 \\leq 10^9)$$$, describing the next test case.", "output_spec": "For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.", "sample_inputs": ["2\n1 2 2 2\n1 1 2 2"], "sample_outputs": ["1\n4"], "notes": "NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds."}, "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"}, {"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"}], "negative_code": [], "src_uid": "6a333044e2ed8f9f4fa44bc16b994418"} {"nl": {"description": "You are fighting with Zmei Gorynich \u2014 a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2013 the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le x \\le 10^9$$$) \u2014 the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \\le d_i, h_i \\le 10^9$$$) \u2014 the description of the $$$i$$$-th blow.", "output_spec": "For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print $$$-1$$$.", "sample_inputs": ["3\n3 10\n6 3\n8 2\n1 4\n4 10\n4 1\n3 2\n2 6\n1 100\n2 15\n10 11\n14 100"], "sample_outputs": ["2\n3\n-1"], "notes": "NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?"}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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 (_ \u2190 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 \u21d2 b.damage > b.heal) match {\n case e if e.nonEmpty \u21d2\n val efficient = e.maxBy(_.pureDamage)\n println((x - fatal + efficient.pureDamage - 1) / efficient.pureDamage + 1)\n case _ \u21d2 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"} {"nl": {"description": "A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say \"I live in three passages from the ringroad\" and another one could reply \"you loser, I live in one passage from the ringroad\". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.", "input_spec": "The first line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u20093000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi,\u2009yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi\u2009\u2260\u2009yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.", "output_spec": "Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.", "sample_inputs": ["4\n1 3\n4 3\n4 2\n1 2", "6\n1 2\n3 4\n6 4\n2 3\n1 3\n3 5"], "sample_outputs": ["0 0 0 0", "0 0 0 1 1 2"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn\n\n/**\n * @author chengyi\n */\nobject Subway {\n \n //vertice and neighbors\n var va:Array[List[Int]] = null\n var visited:Array[(Int,Boolean)] = null\n //\n var circleList:List[Int]=null\n //distance to ring\n var dist:Array[Int] = null\n \n //parent: 0 means root node\n def treeNeighbor(parent:Int, current:Int):List[Int]={\n if (parent== 0){\n //return all neighbor\n va(current-1)\n }else{\n //return neighbor except parent\n va(current-1) diff List(parent)\n }\n }\n \n def nonCircleNeighbor(parent:Int, current:Int):List[Int]={\n va(current-1).filter { x => !circleList.contains(x) && x!=parent }\n }\n \n def foundCircleStop(parent:Int, current:Int):Boolean={\n if (!circleList.isEmpty){\n return true\n }\n \n if (visited(current-1)._2){\n //output the circle list \n var p = parent\n circleList = List(current)\n while (p!=current){\n circleList = circleList:+ p\n p = visited(p-1)._1\n }\n \n true\n }else{\n false\n }\n }\n \n def neverStop(parent:Int, current:Int):Boolean={\n false\n }\n \n //\n def markDepthAction(parent:Int, visit:Int):Unit={\n if (parent==0){\n dist(visit-1) =0\n }else{\n dist(visit-1)=dist(parent-1)+1\n }\n }\n //\n def markVisitedAndParentAction(parent:Int, visit:Int):Unit={\n visited(visit-1)=(parent,true)\n }\n \n //\n def dfs(parent:Int, cur:Int, neigborFun:((Int,Int)=>List[Int]), stopFun:((Int,Int)=>Boolean), actionFun:((Int,Int)=>Unit)):Unit={\n actionFun(parent, cur)\n \n //println(visited.toList)\n \n val neighbors = neigborFun(parent, cur)\n \n //println(\"neighbors of cur:\" + cur)\n //neighbors.map { x => print(x+\",\") }\n //println()\n \n var i =0;\n var fin=false\n while (i {\n val ii = x.split(\" \").map{y=>y.toInt}\n va(ii(0)-1) = va(ii(0)-1):+ii(1)\n va(ii(1)-1) = va(ii(1)-1):+ii(0)\n } \n }\n \n //dfs to detect ring, output to circle list\n \n dfs(0, 1, treeNeighbor, foundCircleStop, markVisitedAndParentAction)\n \n //println(\"circleList:\" + circleList)\n \n //output to distance array\n circleList.map { x => {\n dfs(0, x, nonCircleNeighbor, neverStop, markDepthAction)\n } \n }\n \n dist.mkString(\" \")\n }\n \n def main(args:Array[String]){\n //n>=3\n val n = StdIn.readLine().toInt\n val l = (1 to n).map{x=>StdIn.readLine()}\n println(distance(l))\n }\n \n}"}], "negative_code": [], "src_uid": "2d4dbada60ebcf0bdaead8d0c1c0e2c1"} {"nl": {"description": "Phoenix has a string $$$s$$$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $$$k$$$ non-empty strings $$$a_1, a_2, \\dots, a_k$$$ such that every letter of $$$s$$$ goes to exactly one of the strings $$$a_i$$$. The strings $$$a_i$$$ do not need to be substrings of $$$s$$$. Phoenix can distribute letters of $$$s$$$ and rearrange the letters within each string $$$a_i$$$ however he wants.For example, if $$$s = $$$ baba and $$$k=2$$$, Phoenix may distribute the letters of his string in many ways, such as: ba and ba a and abb ab and ab aa and bb But these ways are invalid: baa and ba b and ba baba and empty string ($$$a_i$$$ should be non-empty) Phoenix wants to distribute the letters of his string $$$s$$$ into $$$k$$$ strings $$$a_1, a_2, \\dots, a_k$$$ to minimize the lexicographically maximum string among them, i.\u00a0e. minimize $$$max(a_1, a_2, \\dots, a_k)$$$. Help him find the optimal distribution and print the minimal possible value of $$$max(a_1, a_2, \\dots, a_k)$$$.String $$$x$$$ is lexicographically less than string $$$y$$$ if either $$$x$$$ is a prefix of $$$y$$$ and $$$x \\ne y$$$, or there exists an index $$$i$$$ ($$$1 \\le i \\le min(|x|, |y|))$$$ such that $$$x_i$$$ < $$$y_i$$$ and for every $$$j$$$ $$$(1 \\le j < i)$$$ $$$x_j = y_j$$$. Here $$$|x|$$$ denotes the length of the string $$$x$$$.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Each test case consists of two lines. The first line of each test case consists of two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 10^5$$$)\u00a0\u2014 the length of string $$$s$$$ and the number of non-empty strings, into which Phoenix wants to distribute letters of $$$s$$$, respectively. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases is $$$\\le 10^5$$$.", "output_spec": "Print $$$t$$$ answers\u00a0\u2014 one per test case. The $$$i$$$-th answer should be the minimal possible value of $$$max(a_1, a_2, \\dots, a_k)$$$ in the $$$i$$$-th test case.", "sample_inputs": ["6\n4 2\nbaba\n5 2\nbaacb\n5 3\nbaacb\n5 3\naaaaa\n6 4\naaxxzz\n7 1\nphoenix"], "sample_outputs": ["ab\nabbc\nb\naa\nx\nehinopx"], "notes": "NoteIn the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx."}, "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"}, {"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"}], "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"} {"nl": {"description": "Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.", "input_spec": "In the first line there are two positive integer numbers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, 0\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) \u2014 prices of items during discounts (i.e. right now). The third line contains sequence of integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009104) \u2014 prices of items after discounts (i.e. after a week).", "output_spec": "Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.", "sample_inputs": ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"], "sample_outputs": ["10", "25"], "notes": "NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6\u2009+\u20093\u2009+\u20091\u2009=\u200910.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3\u2009+\u20094\u2009+\u200910\u2009+\u20093\u2009+\u20095\u2009=\u200925."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.", "input_spec": "The first line of the input contains integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of buttons and the number of bulbs respectively. Each of the next n lines contains xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009m)\u00a0\u2014 the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1\u2009\u2264\u2009yij\u2009\u2264\u2009m)\u00a0\u2014 the numbers of these bulbs.", "output_spec": "If it's possible to turn on all m bulbs print \"YES\", otherwise print \"NO\".", "sample_inputs": ["3 4\n2 1 4\n3 1 3 1\n1 2", "3 3\n1 1\n1 2\n1 1"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp."}, "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": "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"}, {"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.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.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.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"} {"nl": {"description": "You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.", "output_spec": "For each test case, output on a separate line: \"YES\" if $$$n$$$ has an odd divisor, greater than one; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["6\n2\n3\n4\n5\n998244353\n1099511627776"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES\nNO"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "There are $$$n$$$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.We want to plan a trip for every evening of $$$m$$$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least $$$k$$$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $$$a$$$ and $$$b$$$ are friends and $$$b$$$ and $$$c$$$ are friends, it does not necessarily imply that $$$a$$$ and $$$c$$$ are friends.For each day, find the maximum number of people that can go on the trip on that day.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \\leq n \\leq 2 \\cdot 10^5, 1 \\leq m \\leq 2 \\cdot 10^5$$$, $$$1 \\le k < n$$$)\u00a0\u2014 the number of people, the number of days and the number of friends each person on the trip should have in the group. The $$$i$$$-th ($$$1 \\leq i \\leq m$$$) of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1\\leq x, y\\leq n$$$, $$$x\\ne y$$$), meaning that persons $$$x$$$ and $$$y$$$ become friends on the morning of day $$$i$$$. It is guaranteed that $$$x$$$ and $$$y$$$ were not friends before.", "output_spec": "Print exactly $$$m$$$ lines, where the $$$i$$$-th of them ($$$1\\leq i\\leq m$$$) contains the maximum number of people that can go on the trip on the evening of the day $$$i$$$.", "sample_inputs": ["4 4 2\n2 3\n1 2\n1 3\n1 4", "5 8 2\n2 1\n4 2\n5 4\n5 2\n4 3\n5 1\n4 1\n3 2", "5 7 2\n1 5\n3 2\n2 5\n3 4\n1 2\n5 3\n1 3"], "sample_outputs": ["0\n0\n3\n3", "0\n0\n0\n3\n3\n4\n4\n5", "0\n0\n0\n0\n3\n4\n4"], "notes": "NoteIn the first example, $$$1,2,3$$$ can go on day $$$3$$$ and $$$4$$$. In the second example, $$$2,4,5$$$ can go on day $$$4$$$ and $$$5$$$. $$$1,2,4,5$$$ can go on day $$$6$$$ and $$$7$$$. $$$1,2,3,4,5$$$ can go on day $$$8$$$. In the third example, $$$1,2,5$$$ can go on day $$$5$$$. $$$1,2,3,5$$$ can go on day $$$6$$$ and $$$7$$$. "}, "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nobject E extends App {\n var input: BufferedReader = new BufferedReader(new InputStreamReader(System.in))\n var output: BufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out))\n\n var st: StringTokenizer = _\n def read() = { st = new StringTokenizer(input.readLine()) }\n def int() = st.nextToken().toInt\n\n read()\n val n = int() // people\n val m = int() // days\n val k = int() // friend limit\n\n val friends = Array.fill(n+1)(0)\n val days = new Array[(Int,Int)](m)\n val links = Array.fill(n+1)(new java.util.Stack[Int])\n\n for (i <- 0 until m) {\n read()\n val s = int()\n val f = int()\n days(i) = (s, f)\n links(s).add(f)\n links(f).add(s)\n friends(s) += 1\n friends(f) += 1\n }\n\n // friend counts at the end\n // days reversed\n\n val going = Array.fill(n+1)(true)\n var count = n\n val toRemove = new java.util.LinkedHashSet[Int]\n\n for (i <- 1 to n) {\n if (friends(i) < k)\n toRemove.add(i)\n }\n\n @inline\n final def reduce(i: Int) = {\n if (going(i)) {\n friends(i) -= 1\n if (friends(i) < k)\n toRemove.add(i)\n }\n }\n\n def update() = {\n while (!toRemove.isEmpty) {\n val r = toRemove.iterator().next()\n toRemove.remove(r)\n count -= 1\n going(r) = false\n links(r).forEach(reduce)\n }\n }\n\n val res: Array[Int] = days.reverse.map { case (s, f) =>\n update()\n links(s).pop()\n links(f).pop()\n if (going(s) && going(f)) {\n reduce(s)\n reduce(f)\n }\n count\n }\n res.reverse.foreach { c =>\n output.write(c.toString)\n output.newLine()\n }\n input.close()\n output.flush()\n output.close()\n}\n"}], "negative_code": [], "src_uid": "d795e0f49617b1aa281c72f24a632f67"} {"nl": {"description": "The next \"Data Structures and Algorithms\" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.Nam created a sequence a consisting of n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) elements a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105). A subsequence ai1,\u2009ai2,\u2009...,\u2009aik where 1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik\u2009\u2264\u2009n is called increasing if ai1\u2009<\u2009ai2\u2009<\u2009ai3\u2009<\u2009...\u2009<\u2009aik. An increasing subsequence is called longest if it has maximum length among all increasing subsequences. Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), into three groups: group of all i such that ai belongs to no longest increasing subsequences. group of all i such that ai belongs to at least one but not every longest increasing subsequence. group of all i such that ai belongs to every longest increasing subsequence. Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) denoting the number of elements of sequence a. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.", "sample_inputs": ["1\n4", "4\n1 3 2 5", "4\n1 5 2 3"], "sample_outputs": ["3", "3223", "3133"], "notes": "NoteIn the second sample, sequence a consists of 4 elements: {a1,\u2009a2,\u2009a3,\u2009a4} = {1,\u20093,\u20092,\u20095}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a1,\u2009a2,\u2009a4} = {1,\u20093,\u20095} and {a1,\u2009a3,\u2009a4} = {1,\u20092,\u20095}.In the third sample, sequence a consists of 4 elements: {a1,\u2009a2,\u2009a3,\u2009a4} = {1,\u20095,\u20092,\u20093}. Sequence a have exactly 1 longest increasing subsequence of length 3, that is {a1,\u2009a3,\u2009a4} = {1,\u20092,\u20093}."}, "positive_code": [{"source_code": "import java.io._\nimport java.util.Arrays\nimport java.util.StringTokenizer\n\nobject Solution {\n val MOD = 1000 * 1000 * 1000 + 9\n val N = 100 * 1000 + 10\n\n class SegmentTree(val n : Int) {\n private val data = new Array[Int](4 * n + 10)\n private val ways = new Array[Int](4 * n + 10)\n Arrays.fill(ways, 1)\n\n def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)\n\n private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {\n if (l == tl && r == tr)\n return (data(i), ways(i))\n var sl = 0\n var sr = 0\n var wl = 1\n var wr = 1\n val m = (tl + tr) / 2\n if (l <= m) {\n val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))\n sl = t._1\n wl = t._2\n }\n if (r > m) {\n val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)\n sr = t._1\n wr = t._2\n }\n if (sl == sr && sl != 0)\n (sl, (wl + wr) % MOD)\n else if (sl > sr)\n (sl, wl)\n else\n (sr, wr)\n }\n\n def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)\n\n private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {\n if (pos == tl && pos == tr) {\n if (data(i) == value)\n ways(i) = (ways(i) + add) % MOD\n else if (data(i) < value) {\n data(i) = value\n ways(i) = add\n }\n return\n }\n val m = (tl + tr) / 2\n if (pos <= m)\n put(2 * i + 1, tl, m, pos, value, add)\n else\n put(2 * i + 2, m + 1, tr, pos, value, add)\n if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {\n data(i) = data(2 * i + 1)\n ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD\n } else if (data(2 * i + 1) > data(2 * i + 2)) {\n data(i) = data(2 * i + 1)\n ways(i) = ways(2 * i + 1)\n } else {\n data(i) = data(2 * i + 2)\n ways(i) = ways(2 * i + 2)\n }\n }\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n var i = 0\n for (i <- 0 until n)\n a(i) = in.nextInt()\n val equalLeft = new Array[Int](n)\n val equalRight = new Array[Int](n)\n val lessLeft = new Array[Int](n)\n val greaterRight = new Array[Int](n)\n val cntLess = new Array[Int](n)\n val treeLeft = new SegmentTree(N)\n for (i <- 0 until n) {\n equalLeft(i) = treeLeft.getMax(0, a(i))._1\n lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1\n cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2\n treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))\n }\n val maxSeq = treeLeft.getMax(0, N - 1)\n val maxLen = maxSeq._1\n val cntTotal = maxSeq._2\n val treeRight = new SegmentTree(N)\n val res = new Array[Int](n)\n for (i <- 0 until n) {\n val j = n - i - 1\n equalRight(j) = treeRight.getMax(a(j), N - 1)._1\n greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1\n val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2\n treeRight.put(a(j), greaterRight(j) + 1, cntGreater)\n val any = lessLeft(j) + greaterRight(j) + 1 == maxLen\n if (!any) {\n res(j) = 1\n } else {\n if (cntLess(j) * 1L * cntGreater % MOD == cntTotal)\n res(j) = 3\n else\n res(j) = 2\n }\n }\n for (i <- 0 until n)\n out.print(res(i))\n out.println()\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"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.Arrays\nimport java.util.StringTokenizer\n\nobject Solution {\n val MOD = 1000 * 1000 * 1000 + 9\n val N = 100 * 1000 + 10\n\n class SegmentTree(val n : Int) {\n private val data = new Array[Int](4 * n + 10)\n private val ways = new Array[Int](4 * n + 10)\n Arrays.fill(ways, 1)\n\n def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)\n\n private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {\n if (l == tl && r == tr)\n return (data(i), ways(i))\n var sl = 0\n var sr = 0\n var wl = 1\n var wr = 1\n val m = (tl + tr) / 2\n if (l <= m) {\n val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))\n sl = t._1\n wl = t._2\n }\n if (r > m) {\n val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)\n sr = t._1\n wr = t._2\n }\n if (sl == sr && sl != 0)\n (sl, (wl + wr) % MOD)\n else if (sl > sr)\n (sl, wl)\n else\n (sr, wr)\n }\n\n def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)\n\n private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {\n if (pos == tl && pos == tr) {\n if (data(i) == value)\n ways(i) = (ways(i) + add) % MOD\n else if (data(i) < value) {\n data(i) = value\n ways(i) = add\n }\n return\n }\n val m = (tl + tr) / 2\n if (pos <= m)\n put(2 * i + 1, tl, m, pos, value, add)\n else\n put(2 * i + 2, m + 1, tr, pos, value, add)\n if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {\n data(i) = data(2 * i + 1)\n ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD\n } else if (data(2 * i + 1) > data(2 * i + 2)) {\n data(i) = data(2 * i + 1)\n ways(i) = ways(2 * i + 1)\n } else {\n data(i) = data(2 * i + 2)\n ways(i) = ways(2 * i + 2)\n }\n }\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n var i = 0\n for (i <- 0 until n)\n a(i) = in.nextInt()\n val equalLeft = new Array[Int](n)\n val equalRight = new Array[Int](n)\n val lessLeft = new Array[Int](n)\n val greaterRight = new Array[Int](n)\n val cntLess = new Array[Int](n)\n val treeLeft = new SegmentTree(N)\n for (i <- 0 until n) {\n equalLeft(i) = treeLeft.getMax(0, a(i))._1\n lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1\n cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2\n treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))\n }\n val maxSeq = treeLeft.getMax(0, N - 1)\n val maxLen = maxSeq._1\n val cntTotal = maxSeq._2\n val treeRight = new SegmentTree(N)\n val res = new Array[Int](n)\n for (i <- 0 until n) {\n val j = n - i - 1\n equalRight(j) = treeRight.getMax(a(j), N - 1)._1\n greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1\n val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2\n treeRight.put(a(j), greaterRight(j) + 1, cntGreater)\n val any = lessLeft(j) + greaterRight(j) + 1 == maxLen\n if (!any) {\n res(j) = 1\n } else {\n if (cntLess(j) * 1L * cntGreater == cntTotal)\n res(j) = 3\n else\n res(j) = 2\n }\n }\n for (i <- 0 until n)\n out.print(res(i))\n out.println()\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 java.io._\nimport java.util.Arrays\nimport java.util.StringTokenizer\n\nobject Solution {\n val MOD = 1000 * 1000 * 1000 + 7\n val N = 100 * 1000 + 10\n\n class SegmentTree(val n : Int) {\n private val data = new Array[Int](4 * n + 10)\n private val ways = new Array[Int](4 * n + 10)\n Arrays.fill(ways, 1)\n\n def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)\n\n private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {\n if (l == tl && r == tr)\n return (data(i), ways(i))\n var sl = 0\n var sr = 0\n var wl = 1\n var wr = 1\n val m = (tl + tr) / 2\n if (l <= m) {\n val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))\n sl = t._1\n wl = t._2\n }\n if (r > m) {\n val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)\n sr = t._1\n wr = t._2\n }\n if (sl == sr && sl != 0)\n (sl, wl + wr)\n else if (sl > sr)\n (sl, wl)\n else\n (sr, wr)\n }\n\n def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)\n\n private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {\n if (pos == tl && pos == tr) {\n if (data(i) == value)\n ways(i) = (ways(i) + add) % MOD\n else if (data(i) < value) {\n data(i) = value\n ways(i) = add\n }\n return\n }\n val m = (tl + tr) / 2\n if (pos <= m)\n put(2 * i + 1, tl, m, pos, value, add)\n else\n put(2 * i + 2, m + 1, tr, pos, value, add)\n if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {\n data(i) = data(2 * i + 1)\n ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD\n } else if (data(2 * i + 1) > data(2 * i + 2)) {\n data(i) = data(2 * i + 1)\n ways(i) = ways(2 * i + 1)\n } else {\n data(i) = data(2 * i + 2)\n ways(i) = ways(2 * i + 2)\n }\n }\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n var i = 0\n for (i <- 0 until n)\n a(i) = in.nextInt()\n val equalLeft = new Array[Int](n)\n val equalRight = new Array[Int](n)\n val lessLeft = new Array[Int](n)\n val greaterRight = new Array[Int](n)\n val cntLess = new Array[Int](n)\n val treeLeft = new SegmentTree(N)\n for (i <- 0 until n) {\n equalLeft(i) = treeLeft.getMax(0, a(i))._1\n lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1\n cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2\n treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))\n }\n val maxSeq = treeLeft.getMax(0, N - 1)\n val maxLen = maxSeq._1\n val cntTotal = maxSeq._2\n //System.err.print(maxLen + \" \" + cntTotal)\n val treeRight = new SegmentTree(N)\n for (i <- 0 until n) {\n val j = n - i - 1\n equalRight(j) = treeRight.getMax(a(j), N - 1)._1\n greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1\n val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2\n treeRight.put(a(j), greaterRight(j) + 1, cntGreater)\n //System.err.println(cntLess(j) + \" \" + cntGreater)\n //System.err.println(lessLeft(j) + \" \" + equalLeft(j) + \" \" + equalRight(j) + \" \" + greaterRight(j))\n val any = lessLeft(j) + greaterRight(j) + 1 == maxLen\n if (!any) {\n out.print(1)\n } else {\n if (cntLess(j) * 1L * cntGreater == cntTotal)\n out.print(3)\n else\n out.print(2)\n }\n }\n out.println()\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 java.io._\nimport java.util.Arrays\nimport java.util.StringTokenizer\n\nobject Solution {\n val MOD = 1000 * 1000 * 1000 + 7\n val N = 100 * 1000 + 10\n\n class SegmentTree(val n : Int) {\n private val data = new Array[Int](4 * n + 10)\n private val ways = new Array[Int](4 * n + 10)\n Arrays.fill(ways, 1)\n\n def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)\n\n private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {\n if (l == tl && r == tr)\n return (data(i), ways(i))\n var sl = 0\n var sr = 0\n var wl = 1\n var wr = 1\n val m = (tl + tr) / 2\n if (l <= m) {\n val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))\n sl = t._1\n wl = t._2\n }\n if (r > m) {\n val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)\n sr = t._1\n wr = t._2\n }\n if (sl == sr && sl != 0)\n (sl, wl + wr)\n else if (sl > sr)\n (sl, wl)\n else\n (sr, wr)\n }\n\n def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)\n\n private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {\n if (pos == tl && pos == tr) {\n if (data(i) == value)\n ways(i) = (ways(i) + add) % MOD\n else if (data(i) < value) {\n data(i) = value\n ways(i) = add\n }\n return\n }\n val m = (tl + tr) / 2\n if (pos <= m)\n put(2 * i + 1, tl, m, pos, value, add)\n else\n put(2 * i + 2, m + 1, tr, pos, value, add)\n if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {\n data(i) = data(2 * i + 1)\n ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD\n } else if (data(2 * i + 1) > data(2 * i + 2)) {\n data(i) = data(2 * i + 1)\n ways(i) = ways(2 * i + 1)\n } else {\n data(i) = data(2 * i + 2)\n ways(i) = ways(2 * i + 2)\n }\n }\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n var i = 0\n for (i <- 0 until n)\n a(i) = in.nextInt()\n val equalLeft = new Array[Int](n)\n val equalRight = new Array[Int](n)\n val lessLeft = new Array[Int](n)\n val greaterRight = new Array[Int](n)\n val cntLess = new Array[Int](n)\n val treeLeft = new SegmentTree(N)\n for (i <- 0 until n) {\n equalLeft(i) = treeLeft.getMax(0, a(i))._1\n lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1\n cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2\n treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))\n }\n val maxSeq = treeLeft.getMax(0, N - 1)\n val maxLen = maxSeq._1\n val cntTotal = maxSeq._2\n //System.err.print(maxLen + \" \" + cntTotal)\n val treeRight = new SegmentTree(N)\n val res = new Array[Int](n)\n for (i <- 0 until n) {\n val j = n - i - 1\n equalRight(j) = treeRight.getMax(a(j), N - 1)._1\n greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1\n val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2\n treeRight.put(a(j), greaterRight(j) + 1, cntGreater)\n //System.err.println(cntLess(j) + \" \" + cntGreater)\n //System.err.println(lessLeft(j) + \" \" + equalLeft(j) + \" \" + equalRight(j) + \" \" + greaterRight(j))\n val any = lessLeft(j) + greaterRight(j) + 1 == maxLen\n if (!any) {\n res(j) = 1\n } else {\n if (cntLess(j) * 1L * cntGreater == cntTotal)\n res(j) = 3\n else\n res(j) = 2\n }\n }\n for (i <- 0 until n)\n out.print(res(i))\n out.println()\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 java.io._\nimport java.util.Arrays\nimport java.util.StringTokenizer\n\nobject Solution {\n val MOD = 1000 * 1000 * 1000 + 7\n val N = 100 * 1000 + 10\n\n class SegmentTree(val n : Int) {\n private val data = new Array[Int](4 * n + 10)\n private val ways = new Array[Int](4 * n + 10)\n Arrays.fill(ways, 1)\n\n def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)\n\n private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {\n if (l == tl && r == tr)\n return (data(i), ways(i))\n var sl = 0\n var sr = 0\n var wl = 1\n var wr = 1\n val m = (tl + tr) / 2\n if (l <= m) {\n val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))\n sl = t._1\n wl = t._2\n }\n if (r > m) {\n val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)\n sr = t._1\n wr = t._2\n }\n if (sl == sr && sl != 0)\n (sl, (wl + wr) % MOD)\n else if (sl > sr)\n (sl, wl)\n else\n (sr, wr)\n }\n\n def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)\n\n private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {\n if (pos == tl && pos == tr) {\n if (data(i) == value)\n ways(i) = (ways(i) + add) % MOD\n else if (data(i) < value) {\n data(i) = value\n ways(i) = add\n }\n return\n }\n val m = (tl + tr) / 2\n if (pos <= m)\n put(2 * i + 1, tl, m, pos, value, add)\n else\n put(2 * i + 2, m + 1, tr, pos, value, add)\n if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {\n data(i) = data(2 * i + 1)\n ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD\n } else if (data(2 * i + 1) > data(2 * i + 2)) {\n data(i) = data(2 * i + 1)\n ways(i) = ways(2 * i + 1)\n } else {\n data(i) = data(2 * i + 2)\n ways(i) = ways(2 * i + 2)\n }\n }\n }\n\n def solve(in: FastScanner, out: PrintWriter): Unit = {\n val n = in.nextInt()\n val a = new Array[Int](n)\n var i = 0\n for (i <- 0 until n)\n a(i) = in.nextInt()\n val equalLeft = new Array[Int](n)\n val equalRight = new Array[Int](n)\n val lessLeft = new Array[Int](n)\n val greaterRight = new Array[Int](n)\n val cntLess = new Array[Int](n)\n val treeLeft = new SegmentTree(N)\n for (i <- 0 until n) {\n equalLeft(i) = treeLeft.getMax(0, a(i))._1\n lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1\n cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2\n treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))\n }\n val maxSeq = treeLeft.getMax(0, N - 1)\n val maxLen = maxSeq._1\n val cntTotal = maxSeq._2\n val treeRight = new SegmentTree(N)\n val res = new Array[Int](n)\n for (i <- 0 until n) {\n val j = n - i - 1\n equalRight(j) = treeRight.getMax(a(j), N - 1)._1\n greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1\n val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2\n treeRight.put(a(j), greaterRight(j) + 1, cntGreater)\n val any = lessLeft(j) + greaterRight(j) + 1 == maxLen\n if (!any) {\n res(j) = 1\n } else {\n if (cntLess(j) * 1L * cntGreater == cntTotal)\n res(j) = 3\n else\n res(j) = 2\n }\n }\n for (i <- 0 until n)\n out.print(res(i))\n out.println()\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": "0aa46c224476bfba2b1e1227b58e1630"} {"nl": {"description": "Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$=\"wowwo\", the following strings are subsequences: \"wowwo\", \"wowo\", \"oo\", \"wow\", \"\", and others, but the following are not subsequences: \"owoo\", \"owwwo\", \"ooo\".The wow factor of a string is the number of its subsequences equal to the word \"wow\". Bob wants to write a string that has a large wow factor. However, the \"w\" key on his keyboard is broken, so he types two \"v\"s instead. Little did he realise that he may have introduced more \"w\"s than he thought. Consider for instance the string \"ww\". Bob would type it as \"vvvv\", but this string actually contains three occurrences of \"w\": \"vvvv\" \"vvvv\" \"vvvv\" For example, the wow factor of the word \"vvvovvv\" equals to four because there are four wows: \"vvvovvv\" \"vvvovvv\" \"vvvovvv\" \"vvvovvv\" Note that the subsequence \"vvvovvv\" does not count towards the wow factor, as the \"v\"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing \"w\" with \"vv\". For example, $$$s$$$ can be equal to \"vov\".", "input_spec": "The input contains a single non-empty string $$$s$$$, consisting only of characters \"v\" and \"o\". The length of $$$s$$$ is at most $$$10^6$$$.", "output_spec": "Output a single integer, the wow factor of $$$s$$$.", "sample_inputs": ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"], "sample_outputs": ["4", "100"], "notes": "NoteThe first example is explained in the legend."}, "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\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"}, {"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"} {"nl": {"description": "You have a long fence which consists of $$$n$$$ sections. Unfortunately, it is not painted, so you decided to hire $$$q$$$ painters to paint it. $$$i$$$-th painter will paint all sections $$$x$$$ such that $$$l_i \\le x \\le r_i$$$.Unfortunately, you are on a tight budget, so you may hire only $$$q - 2$$$ painters. Obviously, only painters you hire will do their work.You want to maximize the number of painted sections if you choose $$$q - 2$$$ painters optimally. A section is considered painted if at least one painter paints it.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$3 \\le n, q \\le 5000$$$) \u2014 the number of sections and the number of painters availible for hire, respectively. Then $$$q$$$ lines follow, each describing one of the painters: $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$).", "output_spec": "Print one integer \u2014 maximum number of painted sections if you hire $$$q - 2$$$ painters.", "sample_inputs": ["7 5\n1 4\n4 5\n5 6\n6 7\n3 5", "4 3\n1 1\n2 2\n3 4", "4 4\n1 1\n2 2\n2 3\n3 4"], "sample_outputs": ["7", "2", "3"], "notes": null}, "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 (l, r) = na2(Q, -1)\n\n var ans = 0\n\n val cum = Array.ofDim[Int](N + 2)\n val cumOne = Array.ofDim[Int](N + 1)\n\n REP(Q) { del =>\n java.util.Arrays.fill(cum, 0)\n java.util.Arrays.fill(cumOne, 0)\n REP(Q) { i =>\n if (del != i) {\n cum(l(i) + 1) += 1\n cum(r(i) + 2) -= 1\n }\n }\n REP(N + 1) { i =>\n cum(i + 1) += cum(i)\n }\n\n// debug(cum)\n\n REP(N) { i =>\n cumOne(i + 1) = cumOne(i)\n if (cum(i + 1) == 1) cumOne(i + 1) += 1\n }\n\n// debug(cumOne)\n\n val S = cum.count(_ > 0)\n REP(Q) { i =>\n if (i != del) {\n val cnt = cumOne(r(i) + 1) - cumOne(l(i))\n val v = S - cnt\n// debug(s\"del:($del,$i) $cnt $v\")\n ans = max(ans, v)\n }\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": "ff7bdfe399b4b4c37ea557c15e7a7f1c"} {"nl": {"description": "You are given a grid, consisting of $$$2$$$ rows and $$$n$$$ columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells $$$A$$$ and $$$B$$$ belong to the same component if they are neighbours, or if there is a neighbour of $$$A$$$ that belongs to the same component with $$$B$$$.Let's call some bicoloring beautiful if it has exactly $$$k$$$ components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $$$998244353$$$.", "input_spec": "The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 1000$$$, $$$1 \\le k \\le 2n$$$) \u2014 the number of columns in a grid and the number of components required.", "output_spec": "Print a single integer \u2014 the number of beautiful bicolorings modulo $$$998244353$$$.", "sample_inputs": ["3 4", "4 1", "1 2"], "sample_outputs": ["12", "2", "2"], "notes": "NoteOne of possible bicolorings in sample $$$1$$$: "}, "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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n 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}"}], "negative_code": [], "src_uid": "7e6a2329633ee283e3327413114901d1"} {"nl": {"description": "The robot is located on a checkered rectangular board of size $$$n \\times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns\u00a0\u2014 from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell\u00a0\u2014 left, right, down or up, respectively.The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move. If the robot moves beyond the edge of the board, it falls and breaks. If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10000$$$)\u00a0\u2014 the number of test cases in the test. Each test case's description is preceded by a blank line. Next is a line that contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2000$$$; $$$1 \\le m \\le 2000$$$)\u00a0\u2014 the height and width of the board. This line followed by $$$n$$$ lines, the $$$i$$$-th of which describes the $$$i$$$-th line of the board. Each of them is exactly $$$m$$$ letters long and consists of symbols 'L', 'R', 'D' and 'U'. It is guaranteed that the sum of sizes of all boards in the input does not exceed $$$4\\cdot10^6$$$.", "output_spec": "For each test case, output three integers $$$r$$$, $$$c$$$ and $$$d$$$ ($$$1 \\le r \\le n$$$; $$$1 \\le c \\le m$$$; $$$d \\ge 0$$$), which denote that the robot should start moving from cell $$$(r, c)$$$ to make the maximum number of moves $$$d$$$. If there are several answers, output any of them.", "sample_inputs": ["7\n\n1 1\nR\n\n1 3\nRRL\n\n2 2\nDL\nRU\n\n2 2\nUD\nRU\n\n3 2\nDL\nUL\nRU\n\n4 4\nRRRD\nRUUD\nURUD\nULLR\n\n4 4\nDDLU\nRDDU\nUUUU\nRDLD"], "sample_outputs": ["1 1 1\n1 1 3\n1 1 4\n2 1 3\n3 1 5\n4 3 12\n1 1 4"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn._\nimport scala.collection.mutable._\nimport Array.ofDim\n\nobject Main extends App {\n val nums = readInt \n \n for (extended_loop <- 0 until nums) {\n val space = readLine\n val Array(n, m) = readLine.split(' ').map(_.toInt)\n var paths = ofDim[Int](n,m)\n //var path = ofDim[Boolean](n,m)\n for (i <- 0 until n; j <- 0 until m) {\n paths(i)(j) = 0\n //path(i)(j) = 0\n } \n var steps = ofDim[Char](n,m) \n // prev key, steps counter\n //var path = HashMap.empty[Int, (Int, Int)]\n \n for (i <- 0 until n) {\n val rows = readLine\n for (j <- 0 until rows.size){\n steps(i)(j) = rows(j)\n } \n } \n \n var mxm = 0 \n var r = 0 \n var d = 0 \n for (i <- 0 until n; j <- 0 until m) {\n var curr_i = i \n var curr_j = j \n if (paths(i)(j) == 0) {\n var cnt = 0 \n var stack = Stack[Int]()\n var prev_i = curr_i\n var prev_j = curr_j\n stack.push(prev_i*2000+prev_j)\n var stop_flg = false\n while (!stop_flg) {\n if (paths(curr_i)(curr_j)<0) {\n var past_part = cnt - paths(curr_i)(curr_j).abs\n while (curr_i*2000 + curr_j != prev_i*2000 + prev_j) {\n paths(prev_i)(prev_j) = past_part + 1\n if (past_part + 1 > mxm) {\n mxm = past_part + 1\n r = prev_i\n d = prev_j\n } \n var prev_value = stack.pop()\n prev_i = prev_value/2000\n prev_j = prev_value%2000\n }\n var st = cnt - past_part\n while (st > 0) {\n paths(prev_i)(prev_j) = cnt - st + 1\n if (cnt - st + 1 > mxm) {\n mxm = cnt - st + 1\n r = prev_i\n d = prev_j\n }\n var prev_value = stack.pop()\n prev_i = prev_value/2000\n prev_j = prev_value%2000\n st -= 1\n }\n stop_flg = true\n }\n if (!stop_flg) {\n stack.push(prev_i*2000 + prev_j)\n paths(curr_i)(curr_j) = -(cnt + 1)\n //path += (curr_i*2000 + curr_j -> (prev_i*2000 + prev_j, cnt+1))\n prev_j = curr_j\n prev_i = curr_i\n if (steps(curr_i)(curr_j) == 'R') {\n curr_j = curr_j + 1\n } else if (steps(curr_i)(curr_j) == 'L') {\n curr_j = curr_j - 1\n } else if (steps(curr_i)(curr_j) == 'U') {\n curr_i = curr_i - 1\n } else {\n curr_i = curr_i + 1\n }\n cnt += 1\n var ignore_flg = false\n if (!(0<=curr_i & curr_i 0) {\n paths(prev_i)(prev_j) = st - cnt + 1\n if (st - cnt + 1 > mxm) {\n mxm = st - cnt + 1\n r = prev_i\n d = prev_j\n }\n var prev_value = stack.pop()\n prev_i = prev_value/2000\n prev_j = prev_value%2000\n cnt -= 1\n }\n }\n if (!ignore_flg && (paths(curr_i)(curr_j) > 0)) {\n stop_flg = true\n var adding = paths(curr_i)(curr_j)\n var kt = cnt\n while (cnt > 0) {\n paths(prev_i)(prev_j) = (kt - cnt + 1) + adding\n if ((kt - cnt + 1) + adding > mxm) {\n mxm = (kt - cnt + 1) + adding\n r = prev_i\n d = prev_j\n }\n var prev_value = stack.pop()\n prev_i = prev_value/2000\n prev_j = prev_value%2000\n cnt -= 1\n }\n }\n\n }\n }\n }\n }\n\n r += 1\n d += 1\n println(f\"$r $d $mxm\")\n }\n}\n\n"}], "negative_code": [], "src_uid": "67c748999e681fa6f60165f411e5149d"} {"nl": {"description": "On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1,\u2009x2,\u2009...,\u2009xk, then the cost of item xj is axj\u2009+\u2009xj\u00b7k for 1\u2009\u2264\u2009j\u2009\u2264\u2009k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?", "input_spec": "The first line contains two integers n and S (1\u2009\u2264\u2009n\u2009\u2264\u2009105 and 1\u2009\u2264\u2009S\u2009\u2264\u2009109)\u00a0\u2014 the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105)\u00a0\u2014 the base costs of the souvenirs.", "output_spec": "On a single line, print two integers k, T\u00a0\u2014 the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.", "sample_inputs": ["3 11\n2 3 5", "4 100\n1 2 5 6", "1 7\n7"], "sample_outputs": ["2 11", "4 54", "0 0"], "notes": "NoteIn the first example, he cannot take the three items because they will cost him [5,\u20099,\u200914] with total cost 28. If he decides to take only two items, then the costs will be [4,\u20097,\u200911]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5,\u200910,\u200917,\u200922].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it."}, "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 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\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"} {"nl": {"description": "There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \\le s, a, b, c \\le 10^9)$$$ \u2014 the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.", "output_spec": "Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.", "sample_inputs": ["2\n10 3 1 1\n1000000000 1 1000000000 1"], "sample_outputs": ["13\n1000000001000000000"], "notes": "NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars."}, "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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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}"}], "negative_code": [], "src_uid": "ec8060260a6c7f4ff3e6afc9fd248afc"} {"nl": {"description": "Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i\u2009-\u2009j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.", "input_spec": "The first line contains three integers n, a, and b (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n)\u00a0\u2014 the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach. The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.", "output_spec": "Print single integer\u00a0\u2014 the minimum cost Vladik has to pay to get to the olympiad.", "sample_inputs": ["4 1 4\n1010", "5 5 2\n10110"], "sample_outputs": ["1", "0"], "notes": "NoteIn the first example Vladik can fly to the airport 2 at first and pay |1\u2009-\u20092|\u2009=\u20091 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters \"x\" and \"y\", and uses two following operations at runtime: Find two consecutive characters in the string, such that the first of them equals \"y\", and the second one equals \"x\" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. Find in the string two consecutive characters, such that the first of them equals \"x\" and the second one equals \"y\". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows: If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.", "input_spec": "The first line contains a non-empty string s. It is guaranteed that the string only consists of characters \"x\" and \"y\". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.", "output_spec": "In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.", "sample_inputs": ["x", "yxyxy", "xxxxxy"], "sample_outputs": ["x", "y", "xxxx"], "notes": "NoteIn the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.In the second test the transformation will be like this: string \"yxyxy\" transforms into string \"xyyxy\"; string \"xyyxy\" transforms into string \"xyxyy\"; string \"xyxyy\" transforms into string \"xxyyy\"; string \"xxyyy\" transforms into string \"xyy\"; string \"xyy\" transforms into string \"y\". As a result, we've got string \"y\". In the third test case only one transformation will take place: string \"xxxxxy\" transforms into string \"xxxx\". Thus, the answer will be string \"xxxx\"."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m\u2009-\u20091 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,\u2009y) either y\u2009=\u20090, or there is a cube with coordinates (x\u2009-\u20091,\u2009y\u2009-\u20091), (x,\u2009y\u2009-\u20091) or (x\u2009+\u20091,\u2009y\u2009-\u20091).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109\u2009+\u20099.", "input_spec": "The first line contains number m (2\u2009\u2264\u2009m\u2009\u2264\u2009105). The following m lines contain the coordinates of the cubes xi,\u2009yi (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109, 0\u2009\u2264\u2009yi\u2009\u2264\u2009109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place.", "output_spec": "In the only line print the answer to the problem.", "sample_inputs": ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"], "sample_outputs": ["19", "2930"], "notes": null}, "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(m) = readInts(1)\n \n val map = mutable.Map.empty[(Int, Int), Int]\n val xs, ys = Array.ofDim[Int](m)\n \n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n xs(i) = x\n ys(i) = y\n map.put((x, y), i)\n }\n\n def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {\n map.contains(x0, y0) && (\n !((map.contains(x0 - 1, y) && x0 - 1 != x) ||\n (map.contains(x0, y) && x0 != x) ||\n (map.contains(x0 + 1, y) && x0 + 1 != x)))\n }\n \n def canRemove(x: Int, y: Int): Boolean = {\n map.contains(x, y) &&\n (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))\n }\n \n val candidates = new java.util.TreeSet[Int]\n for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)\n\n var step = 0\n val digits = Array.ofDim[Int](m)\n\n while (!candidates.isEmpty()) {\n step += 1\n val c = if (step % 2 == 1) candidates.last else candidates.first\n digits(m - step) = c\n candidates.remove(c)\n val x = xs(c)\n val y = ys(c)\n map.remove(x, y)\n if (!canRemove(x - 1, y) && map.contains(x - 1, y)) candidates.remove(map(x - 1, y))\n if (!canRemove(x + 1, y) && map.contains(x + 1, y)) candidates.remove(map(x + 1, y))\n if (!canRemove(x - 2, y) && map.contains(x - 2, y)) candidates.remove(map(x - 2, y))\n if (!canRemove(x + 2, y) && map.contains(x + 2, y)) candidates.remove(map(x + 2, y))\n if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))\n if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))\n if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))\n }\n \n val MOD = 1000000009\n var res = 0L\n var mult = 1L\n for (d <- digits) {\n res = (res + d * mult) % MOD\n mult = mult * m % MOD\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(m) = readInts(1)\n \n val map = mutable.Map.empty[(Int, Int), Int]\n val xs, ys = Array.ofDim[Int](m)\n \n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n xs(i) = x\n ys(i) = y\n map.put((x, y), i)\n }\n\n def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {\n map.contains(x0, y0) && (!map.contains(x - 1, y) && !map.contains(x + 1, y))\n }\n \n def canRemove(x: Int, y: Int): Boolean = {\n map.contains(x, y) &&\n (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))\n }\n \n val candidates = new java.util.TreeSet[Int]\n for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)\n\n var step = 0\n val digits = Array.ofDim[Int](m)\n\n while (!candidates.isEmpty()) {\n step += 1\n val c = if (step % 2 == 1) candidates.last else candidates.first\n digits(m - step) = c\n candidates.remove(c)\n val x = xs(c)\n val y = ys(c)\n map.remove(x, y)\n if (canRemove(x - 1, y)) candidates.add(map(x - 1, y))\n if (canRemove(x + 1, y)) candidates.add(map(x + 1, y))\n if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))\n if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))\n if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))\n }\n \n val MOD = 1000000009\n var res = 0L\n var mult = 1L\n for (d <- digits) {\n res = (res + d * mult) % MOD\n mult = mult * m % MOD\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(m) = readInts(1)\n \n val map = mutable.Map.empty[(Int, Int), Int]\n val xs, ys = Array.ofDim[Int](m)\n \n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n xs(i) = x\n ys(i) = y\n map.put((x, y), i)\n }\n\n def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {\n map.contains(x0, y0) && (!map.contains(x - 1, y) && !map.contains(x + 1, y))\n }\n \n def canRemove(x: Int, y: Int): Boolean = {\n map.contains(x, y) &&\n (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))\n }\n \n val candidates = new java.util.TreeSet[Int]\n for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)\n\n var step = 0\n val digits = Array.ofDim[Int](m)\n\n while (!candidates.isEmpty()) {\n step += 1\n val c = if (step % 2 == 1) candidates.last else candidates.first\n digits(m - step) = c\n candidates.remove(c)\n val x = xs(c)\n val y = ys(c)\n map.remove(x, y)\n if (!canRemove(x - 1, y) && map.contains(x - 1, y)) candidates.remove(map(x - 1, y))\n if (!canRemove(x + 1, y) && map.contains(x + 1, y)) candidates.remove(map(x + 1, y))\n if (!canRemove(x - 2, y) && map.contains(x - 2, y)) candidates.remove(map(x - 2, y))\n if (!canRemove(x + 2, y) && map.contains(x + 2, y)) candidates.remove(map(x + 2, y))\n if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))\n if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))\n if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))\n }\n \n val MOD = 1000000009\n var res = 0L\n var mult = 1L\n for (d <- digits) {\n res = (res + d * mult) % MOD\n mult = mult * m % MOD\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(m) = readInts(1)\n \n val map = mutable.Map.empty[(Int, Int), Int]\n val xs, ys = Array.ofDim[Int](m)\n \n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n xs(i) = x\n ys(i) = y\n map.put((x, y), i)\n }\n\n def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {\n map.contains(x0, y0) && !map.contains(x - 1, y) && !map.contains(x + 1, y)\n }\n \n def canRemove(x: Int, y: Int): Boolean = {\n map.contains(x, y) &&\n (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))\n }\n \n val candidates = new java.util.TreeSet[Int]\n for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)\n\n var step = 0\n val digits = Array.ofDim[Int](m)\n \n while (!candidates.isEmpty()) {\n step += 1\n val c = if (step % 1 == 0) candidates.last else candidates.first\n digits(m - step) = c\n candidates.remove(c)\n val x = xs(c)\n val y = ys(c)\n map.remove(x, y)\n if (canRemove(x - 1, y)) candidates.add(map(x - 1, y))\n if (canRemove(x + 1, y)) candidates.add(map(x + 1, y))\n if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))\n if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))\n if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))\n }\n \n val MOD = 1000000009\n var res = 0L\n var mult = 1L\n for (d <- digits) {\n res = (res + d * mult) % MOD\n mult = mult * m % MOD\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(m) = readInts(1)\n \n val map = mutable.Map.empty[(Int, Int), Int]\n val xs, ys = Array.ofDim[Int](m)\n \n for (i <- 0 until m) {\n val Array(x, y) = readInts(2)\n xs(i) = x\n ys(i) = y\n map.put((x, y), i)\n }\n\n def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {\n map.contains(x0, y0) && (!map.contains(x - 1, y) && !map.contains(x + 1, y))\n }\n \n def canRemove(x: Int, y: Int): Boolean = {\n map.contains(x, y) &&\n (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))\n }\n \n val candidates = new java.util.TreeSet[Int]\n for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)\n\n var step = 0\n val digits = Array.ofDim[Int](m)\n\n while (!candidates.isEmpty()) {\n step += 1\n var c = if (step % 2 == 1) candidates.last else candidates.first\n if (c == 0 && step % 2 == 0) {\n candidates.remove(0)\n if (!candidates.isEmpty()) {\n c = candidates.first\n candidates.add(0)\n }\n }\n digits(m - step) = c\n candidates.remove(c)\n val x = xs(c)\n val y = ys(c)\n map.remove(x, y)\n if (!canRemove(x - 1, y) && map.contains(x - 1, y)) candidates.remove(map(x - 1, y))\n if (!canRemove(x + 1, y) && map.contains(x + 1, y)) candidates.remove(map(x + 1, y))\n if (!canRemove(x - 2, y) && map.contains(x - 2, y)) candidates.remove(map(x - 2, y))\n if (!canRemove(x + 2, y) && map.contains(x + 2, y)) candidates.remove(map(x + 2, y))\n if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))\n if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))\n if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))\n }\n \n val MOD = 1000000009\n var res = 0L\n var mult = 1L\n for (d <- digits) {\n res = (res + d * mult) % MOD\n mult = mult * m % MOD\n }\n\n println(res % MOD)\n}\n"}], "src_uid": "9f36d49541e6dd7082e37416cdb1949c"} {"nl": {"description": "Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.", "input_spec": "The first line contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). n lines follow, in the i-th of which there are three integers ai,\u2009bi and ci (1\u2009\u2264\u2009ai,\u2009bi,\u2009ci\u2009\u2264\u2009109)\u00a0\u2014 the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.", "output_spec": "In the first line print k (1\u2009\u2264\u2009k\u2009\u2264\u20092) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n\u00a0\u2014 the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them. ", "sample_inputs": ["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"], "sample_outputs": ["1\n1", "2\n1 5"], "notes": "NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3\u2009\u00d7\u20092\u2009\u00d7\u20095, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3\u2009\u00d7\u20092\u2009\u00d7\u20098 or 6\u2009\u00d7\u20092\u2009\u00d7\u20094 or 3\u2009\u00d7\u20094\u2009\u00d7\u20094, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3\u2009\u00d7\u20095\u2009\u00d7\u20094, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3\u2009\u00d7\u20092\u2009\u00d7\u20095, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3\u2009\u00d7\u20094\u2009\u00d7\u20095, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5\u2009\u00d7\u20095\u2009\u00d7\u20095, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3\u2009\u00d7\u20092\u2009\u00d7\u20094, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1\u2009\u00d7\u20094\u2009\u00d7\u20091, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2\u2009\u00d7\u20091\u2009\u00d7\u20093, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3\u2009\u00d7\u20092\u2009\u00d7\u20094, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3\u2009\u00d7\u20093\u2009\u00d7\u20094, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone. "}, "positive_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.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"}, {"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"} {"nl": {"description": "The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?", "input_spec": "The first line contains two integers, n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092000;\u00a01\u2009\u2264\u2009k\u2009\u2264\u20095). The next line contains n integers: y1,\u2009y2,\u2009...,\u2009yn (0\u2009\u2264\u2009yi\u2009\u2264\u20095), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.", "output_spec": "Print a single number \u2014 the answer to the problem.", "sample_inputs": ["5 2\n0 4 5 1 0", "6 4\n0 1 2 3 4 5", "6 5\n0 0 0 0 0 0"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first sample only one team could be made: the first, the fourth and the fifth participants.In the second sample no teams could be created.In the third sample two teams could be created. Any partition into two teams fits."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $$$n$$$ cards. You see that the values of cards from the topmost to the bottommost are integers $$$a_1, a_2, \\dots, a_n$$$, and all values are different.Then he asks you to shuffle the deck $$$m$$$ times. With the $$$j$$$-th shuffle, you should take $$$b_j$$$ topmost cards and move them under the remaining $$$(n - b_j)$$$ cards without changing the order.And then, using some magic, Monocarp tells you the topmost card of the deck. However, you are not really buying that magic. You tell him that you know the topmost card yourself. Can you surprise Monocarp and tell him the topmost card before he shows it?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of cards in the deck. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the values of the cards. The third line contains a single integer $$$m$$$ ($$$1 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of shuffles. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \\dots, b_m$$$ ($$$1 \\le b_j \\le n - 1$$$)\u00a0\u2014 the amount of cards that are moved on the $$$j$$$-th shuffle. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the value of the card on the top of the deck after the deck is shuffled $$$m$$$ times.", "sample_inputs": ["3\n\n2\n\n1 2\n\n3\n\n1 1 1\n\n4\n\n3 1 4 2\n\n2\n\n3 1\n\n5\n\n2 1 5 4 3\n\n5\n\n3 2 1 2 1"], "sample_outputs": ["2\n3\n3"], "notes": "NoteIn the first testcase, each shuffle effectively swaps two cards. After three swaps, the deck will be $$$[2, 1]$$$.In the second testcase, the second shuffle cancels what the first shuffle did. First, three topmost cards went underneath the last card, then that card went back below the remaining three cards. So the deck remained unchanged from the initial one\u00a0\u2014 the topmost card has value $$$3$$$."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "One day Om Nom found a thread with n beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly. Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads S is regular if it can be represented as S\u2009=\u2009A\u2009+\u2009B\u2009+\u2009A\u2009+\u2009B\u2009+\u2009A\u2009+\u2009...\u2009+\u2009A\u2009+\u2009B\u2009+\u2009A, where A and B are some bead sequences, \"\u2009+\u2009\" is the concatenation of sequences, there are exactly 2k\u2009+\u20091 summands in this sum, among which there are k\u2009+\u20091 \"A\" summands and k \"B\" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if A or B is an empty sequence.Help Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20091\u2009000\u2009000) \u2014 the number of beads on the thread that Om Nom found and number k from the definition of the regular sequence above. The second line contains the sequence of n lowercase Latin letters that represent the colors of the beads. Each color corresponds to a single letter.", "output_spec": "Print a string consisting of n zeroes and ones. Position i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) must contain either number one if the first i beads on the thread form a regular sequence, or a zero otherwise.", "sample_inputs": ["7 2\nbcabcab", "21 2\nababaababaababaababaa"], "sample_outputs": ["0000011", "000110000111111000011"], "notes": "NoteIn the first sample test a regular sequence is both a sequence of the first 6 beads (we can take A\u2009=\u2009\"\", B\u2009=\u2009\"bca\"), and a sequence of the first 7 beads (we can take A\u2009=\u2009\"b\", B\u2009=\u2009\"ca\").In the second sample test, for example, a sequence of the first 13 beads is regular, if we take A\u2009=\u2009\"aba\", B\u2009=\u2009\"ba\"."}, "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, kk) = readInts(2)\n val s = readLine\n\n val next = Array.fill(n + 1)(0)\n\n {\n var k = 0\n for (j <- 1 until n) {\n while (k > 0 && s(k) != s(j)) k = next(k)\n if (s(k) == s(j)) k += 1\n next(j + 1) = k\n }\n }\n\n val res = Array.fill(n) { if (kk == 1) '1' else '0' }\n\n def check(i: Int, j: Int) {\n var ok = false\n val l0 = i - j\n val c = i / l0 / kk\n var l = c * l0\n while (l * kk <= i) {\n if (l > 0 && j > 0) {\n if (l * kk == i) ok = true\n else if (l * (kk + 1) == i) ok = true\n else {\n val l1 = (i) % l\n val l2 = l - l1\n if (l1 * (kk + 1) + l2 * kk == i) ok = true\n }\n }\n l += l0\n }\n if (ok) res(i - 1) = '1'\n }\n\n for (i <- 1 to s.length) check(i, next(i))\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n println(new String(res))\n\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "ed91406d23cc35e428c237297b8a1db1"} {"nl": {"description": "There is a badminton championship in which $$$n$$$ players take part. The players are numbered from $$$1$$$ to $$$n$$$. The championship proceeds as follows: player $$$1$$$ and player $$$2$$$ play a game, then the winner and player $$$3$$$ play a game, and then the winner and player $$$4$$$ play a game, and so on. So, $$$n-1$$$ games are played, and the winner of the last game becomes the champion. There are no draws in the games.You want to find out the result of championship. Currently, you only know the following information: Each player has either won $$$x$$$ games or $$$y$$$ games in the championship. Given $$$n$$$, $$$x$$$, and $$$y$$$, find out if there is a result that matches this information.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains three integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$2 \\le n \\le 10^5$$$, $$$0 \\le x, y < n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print the answer for each test case, one per line. If there is no result that matches the given information about $$$n$$$, $$$x$$$, $$$y$$$, print $$$-1$$$. Otherwise, print $$$n-1$$$ space separated integers, where the $$$i$$$-th integer is the player number of the winner of the $$$i$$$-th game. If there are multiple valid results, print any.", "sample_inputs": ["5\n\n5 2 0\n\n8 1 2\n\n3 0 0\n\n2 0 1\n\n6 3 0"], "sample_outputs": ["1 1 4 4\n-1\n-1\n2 \n-1"], "notes": "NoteIn the first test case, player $$$1$$$ and player $$$4$$$ won $$$x$$$ times, player $$$2$$$ and player $$$3$$$ won $$$y$$$ times.In the second, third, and fifth test cases, no valid result exists."}, "positive_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 <- 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"}, {"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"} {"nl": {"description": "Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0\u2009\u2264\u20092k\u2009\u2264\u2009n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n\u2009-\u20092k of the best among the others.The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009109)\u00a0\u2014 the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal.", "output_spec": "Print two strings consisting of n characters, each equals either \"0\" or \"1\". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal \"1\" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a \"0\".", "sample_inputs": ["4\n9840 9920\n9860 9980\n9930 10020\n10040 10090", "4\n9900 9850\n9940 9930\n10000 10020\n10060 10110"], "sample_outputs": ["1110\n1100", "1100\n1100"], "notes": "NoteConsider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. If k\u2009=\u20090, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. If k\u2009=\u20091, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). If k\u2009=\u20092, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. "}, "positive_code": [{"source_code": "//package r222d2\n\nimport scala.io.Source\nimport java.util.Comparator\n\n/**\n * User: Oleg\n * Date: 1/2/14\n * Time: 2:00 AM\n */\nobject B {\n def main(args: Array[String]) {\n val in = Source.fromInputStream(System.in).getLines\n val n = in.next().toInt\n val results = in.take(n).map(_.split(' ') map (_.toInt)).zipWithIndex.map {\n case (array, contestant) => array.zipWithIndex.map {\n case (result, semifinal) => (result, (semifinal, contestant))\n }\n }.toArray.transpose.flatten\n val solution = Array.fill(2, n)('0')\n type Result = (Int, (Int, Int))\n val comparator = new Comparator[Result] {\n override def compare(res1: Result, res2: Result) = res1._1 - res2._1\n }\n java.util.Arrays.sort(results, 0, n, comparator)\n java.util.Arrays.sort(results, n, 2 * n, comparator)\n for (k <- 0 :: n :: Nil; i <- k until k + n / 2) {\n val res = results(i)._2\n solution(res._1)(res._2) = '1'\n }\n java.util.Arrays.sort(results, comparator)\n for (i <- 0 until n) {\n val res = results(i)._2\n solution(res._1)(res._2) = '1'\n }\n solution.foreach(s => println(s.mkString))\n }\n}\n"}], "negative_code": [], "src_uid": "bea30e4ba653b9d0af87fc79b9ec8b4f"} {"nl": {"description": "The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.The main school of the capital is located in $$$(s_x, s_y)$$$. There are $$$n$$$ students attending this school, the $$$i$$$-th of them lives in the house located in $$$(x_i, y_i)$$$. It is possible that some students live in the same house, but no student lives in $$$(s_x, s_y)$$$.After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the $$$i$$$-th student goes from the school to his house is $$$|s_x - x_i| + |s_y - y_i|$$$.The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the $$$i$$$-th student will buy a shawarma if at least one of the shortest paths from the school to the $$$i$$$-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.", "input_spec": "The first line contains three integers $$$n$$$, $$$s_x$$$, $$$s_y$$$ ($$$1 \\le n \\le 200\\,000$$$, $$$0 \\le s_x, s_y \\le 10^{9}$$$) \u2014 the number of students and the coordinates of the school, respectively. Then $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \\le x_i, y_i \\le 10^{9}$$$) \u2014 the location of the house where the $$$i$$$-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated.", "output_spec": "The output should consist of two lines. The first of them should contain one integer $$$c$$$ \u2014 the maximum number of students that will buy shawarmas at the tent. The second line should contain two integers $$$p_x$$$ and $$$p_y$$$ \u2014 the coordinates where the tent should be located. If there are multiple answers, print any of them. Note that each of $$$p_x$$$ and $$$p_y$$$ should be not less than $$$0$$$ and not greater than $$$10^{9}$$$.", "sample_inputs": ["4 3 2\n1 3\n4 2\n5 1\n4 1", "3 100 100\n0 0\n0 0\n100 200", "7 10 12\n5 6\n20 23\n15 4\n16 5\n4 54\n12 1\n4 15"], "sample_outputs": ["3\n4 2", "2\n99 100", "4\n10 11"], "notes": "NoteIn the first example, If we build the shawarma tent in $$$(4, 2)$$$, then the students living in $$$(4, 2)$$$, $$$(4, 1)$$$ and $$$(5, 1)$$$ will visit it.In the second example, it is possible to build the shawarma tent in $$$(1, 1)$$$, then both students living in $$$(0, 0)$$$ will visit it."}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n val N, X, Y = ni()\n val C = Array.ofDim[Int](4)\n REP(N) { _ =>\n val x, y = ni()\n val sx = Integer.signum(x - X)\n val sy = Integer.signum(y - Y)\n if (sy > 0) C(0) += 1\n if (sx > 0) C(1) += 1\n if (sy < 0) C(2) += 1\n if (sx < 0) C(3) += 1\n }\n\n val ix = C.zipWithIndex.maxBy(_._1)._2\n debug(C)\n debug(s\"$ix\")\n\n out.println(C(ix))\n ix match {\n case 0 => out.println(s\"$X ${Y+1}\")\n case 1 => out.println(s\"${X+1} $Y\")\n case 2 => out.println(s\"$X ${Y-1}\")\n case 3 => out.println(s\"${X-1} $Y\")\n }\n }\n}"}], "negative_code": [], "src_uid": "6778eae5422b8ed026a33856998ea89a"} {"nl": {"description": "George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c\u2009\u2265\u2009d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20093000) \u2014 the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an\u2009\u2264\u2009106) \u2014 the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009b1\u2009\u2264\u2009b2...\u2009\u2264\u2009bm\u2009\u2264\u2009106) \u2014 the complexities of the problems prepared by George. ", "output_spec": "Print a single integer \u2014 the answer to the problem.", "sample_inputs": ["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"], "sample_outputs": ["0", "2", "3"], "notes": "NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2,\u20093,\u20094. "}, "positive_code": [{"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"} {"nl": {"description": "This is an easier version of the next problem. The difference is only in constraints.You are given a rectangular $$$n \\times m$$$ matrix $$$a$$$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $$$i$$$-th row it is equal $$$r_i$$$. What is the maximal possible value of $$$r_1+r_2+\\ldots+r_n$$$?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 40$$$), the number of test cases in the input. The first line of each test case contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 4$$$, $$$1 \\le m \\le 100$$$) \u2014 the number of rows and the number of columns in the given matrix $$$a$$$. Each of the following $$$n$$$ lines contains $$$m$$$ integers, the elements of $$$a$$$ ($$$1 \\le a_{i, j} \\le 10^5$$$).", "output_spec": "Print $$$t$$$ integers: answers for all test cases in the order they are given in the input.", "sample_inputs": ["2\n2 3\n2 5 7\n4 2 4\n3 6\n4 1 5 2 10 4\n8 6 6 4 9 10\n5 4 9 5 8 7"], "sample_outputs": ["12\n29"], "notes": "NoteIn the first test case, you can shift the third column down by one, this way there will be $$$r_1 = 5$$$ and $$$r_2 = 7$$$.In the second case you can don't rotate anything at all, this way there will be $$$r_1 = r_2 = 10$$$ and $$$r_3 = 9$$$."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 = Array.ofDim[Int](N, M)\n REP(N) { i =>\n REP(M) { j =>\n g(i)(j) = ni()\n }\n }\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\n debug(colMx)\n val cols = colMx.zipWithIndex.sortBy(_._1).map(_._2).takeRight(N)\n debug(cols)\n\n val all = (1 << N) - 1\n val dp = Array.ofDim[Int](cols.length, 1 << N)\n // s\u304c\u7acb\u3063\u3066\u3044\u308b\u4f4d\u7f6e\u306e\u5217\u306e\u5024\u3092\u8db3\u3057\u5408\u308f\u305b\u308b\n def calcSum(s: Int, i: Int, roll: Int): Int = {\n var res = 0\n var j = 0\n while(j < N) {\n if ((s >> j & 1) == 1) {\n res += g((j + roll) % N)(cols(i))\n }\n j += 1\n }\n res\n }\n\n val calced = Array.ofDim[Int](cols.length, N, 1 << N)\n REP(cols.length) { i =>\n REP(N) { roll =>\n REP(1 << N) { s =>\n calced(i)(roll)(s) = calcSum(s, i, roll)\n }\n }\n }\n\n REP(1 << N) { s =>\n dp(0)(s) = calced(0)(0)(s)\n }\n\n REP(cols.length - 1) { i =>\n REP(1 << N) { s =>\n val mask = ~s & all\n var s2 = mask\n // s2 = 0 \u306e\u5834\u5408\u306f\u5fc5\u8981\u306a\u3044\n while(s2 > 0) {\n val ns = s | s2\n var roll = 0\n while(roll < N) {\n val v = calced(i + 1)(roll)(s2)\n dp(i + 1)(ns) = max(dp(i + 1)(ns), dp(i)(s) + v)\n roll += 1\n }\n s2 = (s2 - 1) & mask\n }\n }\n }\n\n val ans = dp(cols.length - 1).max\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[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 case class Entry(a: Int, col: 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\n // toInt\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n import java.util.Comparator\n val N, M = ni()\n val g = Array.ofDim[Int](N, M)\n val E = Array.ofDim[Entry](N * M)\n REP(N) { i =>\n REP(M) { j =>\n g(i)(j) = ni()\n E(i * M + j) = Entry(g(i)(j), j)\n }\n }\n\n // \u964d\u9806\n sort(E, new Comparator[Entry] {\n override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o2.a, o1.a)\n })\n\n if (N == 1) {\n out.println(E.head.a)\n return\n }\n\n // \u5019\u88dc\u306b\u306a\u308b\u5217\u306fN\u3053\u307e\u3067\n def calcCols: Array[Int] = {\n val cols = mutable.Set[Int]()\n REP(N * M) { i =>\n cols += E(i).col\n if (cols.size == N) return cols.toArray\n }\n cols.toArray\n }\n\n val cols = calcCols\n debug(\"cols\")\n debug(cols)\n val ix = Array.ofDim[Int](cols.length + 1)\n def incr(ix: Array[Int], i: Int): Unit = {\n ix(i) += 1\n if (ix(i) == N) {\n ix(i) = 0\n incr(ix, i + 1)\n }\n }\n\n def calc(cols: Array[Int], ix: Array[Int]): Int = {\n var cnt = 0\n REP(N) { i =>\n var mx = 0\n REP(cols.length) { j =>\n mx = max(mx, g((i+ix(j))%N)(cols(j)))\n }\n cnt += mx\n }\n cnt\n }\n\n var ans = 0\n val HOGE = math.pow(N, cols.length - 1).toInt // \uff11\u3064\u56fa\u5b9a\u3057\u3066\u3044\u3044\n debug(s\"HOGE:$HOGE\")\n REP(HOGE) { _ =>\n ans = max(ans, calc(cols, ix))\n incr(ix, 0)\n debug(ix)\n }\n\n out.println(ans)\n }\n }\n}"}], "src_uid": "b1d8149eb6b89706548741b46e5b1a30"} {"nl": {"description": "Three friends are going to meet each other. Initially, the first friend stays at the position $$$x = a$$$, the second friend stays at the position $$$x = b$$$ and the third friend stays at the position $$$x = c$$$ on the coordinate axis $$$Ox$$$.In one minute each friend independently from other friends can change the position $$$x$$$ by $$$1$$$ to the left or by $$$1$$$ to the right (i.e. set $$$x := x - 1$$$ or $$$x := x + 1$$$) or even don't change it.Let's introduce the total pairwise distance \u2014 the sum of distances between each pair of friends. Let $$$a'$$$, $$$b'$$$ and $$$c'$$$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $$$|a' - b'| + |a' - c'| + |b' - c'|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer $$$q$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 1000$$$) \u2014 the number of test cases. The next $$$q$$$ lines describe test cases. The $$$i$$$-th test case is given as three integers $$$a, b$$$ and $$$c$$$ ($$$1 \\le a, b, c \\le 10^9$$$) \u2014 initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.", "output_spec": "For each test case print the answer on it \u2014 the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.", "sample_inputs": ["8\n3 3 4\n10 20 30\n5 5 5\n2 4 3\n1 1000000000 1000000000\n1 1000000000 999999999\n3 2 5\n3 2 6"], "sample_outputs": ["0\n36\n0\n0\n1999999994\n1999999994\n2\n4"], "notes": null}, "positive_code": [{"source_code": "object CF605A extends App {\n\n import scala.io.StdIn\n\n val q = StdIn.readInt\n for (_ <- 0 until q) {\n val Array(a, b, c) = StdIn.readLine.split(' ').map(_.toInt)\n\n println((for {\n da <- -1 to 1\n db <- -1 to 1\n dc <- -1 to 1\n } yield math.abs(a+da - b-db) + math.abs(a+da - c-dc) + math.abs(b+db - c-dc)).min)\n }\n}\n"}], "negative_code": [], "src_uid": "18f2e54e4147e8887da737d5b6639473"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, \"ADE\" and \"BD\" are subsequences of \"ABCDE\", but \"DEA\" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$. ", "input_spec": "The first line of the input contains integers $$$n$$$ ($$$1\\le n \\le 10^5$$$) and $$$k$$$ ($$$1 \\le k \\le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.", "output_spec": "Print the only integer\u00a0\u2014 the length of the longest good subsequence of string $$$s$$$.", "sample_inputs": ["9 3\nACAABCCAB", "9 4\nABCABCABC"], "sample_outputs": ["6", "0"], "notes": "NoteIn the first example, \"ACBCAB\" (\"ACAABCCAB\") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence \"CAB\" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$."}, "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 c = Array.ofDim[Int](K)\n val S = ns(N)\n S foreach { i =>\n c((i - 'A')) += 1\n }\n val ms = c.min\n val ok = !(c contains 0)\n val ans = if (ok) ms * K else 0\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 val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": [], "src_uid": "d9d5db63b1e48214d02abe9977709384"} {"nl": {"description": "Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1\u2009\u00d7\u2009n table).At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1\u2009\u00d7\u2009a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.After that Bob makes a sequence of \"shots\". He names cells of the field and Alice either says that the cell is empty (\"miss\"), or that the cell belongs to some ship (\"hit\").But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a \"miss\". Help Bob catch Alice cheating \u2014 find Bob's first move, such that after it you can be sure that Alice cheated.", "input_spec": "The first line of the input contains three integers: n, k and a (1\u2009\u2264\u2009n,\u2009k,\u2009a\u2009\u2264\u20092\u00b7105) \u2014 the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other. The second line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the number of Bob's moves. The third line contains m distinct integers x1,\u2009x2,\u2009...,\u2009xm, where xi is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.", "output_spec": "Print a single integer \u2014 the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print \"-1\".", "sample_inputs": ["11 3 3\n5\n4 8 6 1 11", "5 1 3\n2\n1 5", "5 1 3\n1\n3"], "sample_outputs": ["3", "-1", "1"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "Nezzar has $$$n$$$ balls, numbered with integers $$$1, 2, \\ldots, n$$$. Numbers $$$a_1, a_2, \\ldots, a_n$$$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $$$a_i \\leq a_{i+1}$$$ for all $$$1 \\leq i < n$$$.Nezzar wants to color the balls using the minimum number of colors, such that the following holds. For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls. Note that a sequence with the length at most $$$1$$$ is considered as a strictly increasing sequence.Please help Nezzar determine the minimum number of colors.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of testcases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that $$$a_1 \\leq a_2 \\leq \\ldots \\leq a_n$$$.", "output_spec": "For each test case, output the minimum number of colors Nezzar can use.", "sample_inputs": ["5\n6\n1 1 1 2 3 4\n5\n1 1 2 2 3\n4\n2 2 2 2\n3\n1 2 3\n1\n1"], "sample_outputs": ["3\n2\n4\n1\n1"], "notes": "NoteLet's match each color with some numbers. Then:In the first test case, one optimal color assignment is $$$[1,2,3,3,2,1]$$$.In the second test case, one optimal color assignment is $$$[1,2,1,2,1]$$$."}, "positive_code": [{"source_code": "object Hello {\n def main(args: Array[String]): Unit = {\n var T = scala.io.StdIn.readInt()\n\n for (t <- 0 until T) {\n var n = scala.io.StdIn.readInt()\n //var a = new Array[Int](n)\n var a = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toArray\n /*for (i <- 0 until n - 1) {\n a(i) = scala.io.StdIn.readInt()\n }*/\n var ans = 1\n var cur = 1\n for (i <- 1 until n) {\n if (a(i) == a(i - 1)) {\n cur += 1\n } else {\n ans = Math.max(cur, ans)\n cur = 1\n }\n }\n ans = Math.max(cur, ans)\n println(ans)\n }\n }\n}"}], "negative_code": [], "src_uid": "6d4744d7356e709f73891270becd14e3"} {"nl": {"description": "A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are $$$n$$$ students in the class, and you are given an array $$$s$$$ in non-decreasing order, where $$$s_i$$$ is the shoe size of the $$$i$$$-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation $$$p$$$ of $$$\\{1,2,\\ldots,n\\}$$$ denoting a valid shuffling of shoes, where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student ($$$p_i \\ne i$$$). And output $$$-1$$$ if a valid shuffling does not exist.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\\leq n\\leq10^5$$$)\u00a0\u2014 the number of students. The second line of each test case contains $$$n$$$ integers $$$s_1, s_2,\\ldots,s_n$$$ ($$$1\\leq s_i\\leq10^9$$$, and for all $$$1\\le i<n$$$, $$$s_i\\le s_{i+1}$$$) \u2014 the shoe sizes of the students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the answer in a single line using the following format. If a valid shuffling does not exist, print the number $$$-1$$$ as the answer. If a valid shuffling exists, print $$$n$$$ space-separated integers \u2014 a permutation $$$p$$$ of $$$1,2,\\ldots,n$$$ denoting a valid shuffling of shoes where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student. If there are multiple answers, then print any of them.", "sample_inputs": ["2\n5\n1 1 1 1 1\n6\n3 6 8 13 15 21"], "sample_outputs": ["5 1 2 3 4 \n-1"], "notes": "NoteIn the first test case, any permutation $$$p$$$ of $$$1,\\ldots,n$$$ where $$$p_i\\ne i$$$ would represent a valid shuffling since all students have equal shoe sizes, and thus anyone can wear anyone's shoes.In the second test case, it can be shown that no valid shuffling is possible."}, "positive_code": [{"source_code": "\r\nimport scala.collection.mutable\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(_.toInt)\r\n\r\n val permutation = mutable.ListBuffer[Int]()\r\n\r\n var i = 1\r\n var sameCount = 0\r\n var failed = false\r\n\r\n while(i < numbers.length && !failed) {\r\n if(numbers(i) == numbers(i - 1)) {\r\n sameCount += 1\r\n permutation += i + 1\r\n } else {\r\n if(sameCount == 0) {\r\n failed = true\r\n } else {\r\n permutation += i - sameCount\r\n sameCount = 0\r\n }\r\n }\r\n i += 1\r\n }\r\n\r\n if(sameCount == 0) {\r\n failed = true\r\n } else {\r\n permutation += i - sameCount\r\n sameCount = 0\r\n }\r\n\r\n if(failed) {\r\n println(-1)\r\n } else {\r\n println(permutation.mkString(\" \"))\r\n }\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "import scala.collection.mutable\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(_.toInt)\r\n\r\n val permutation = mutable.ListBuffer[Int]()\r\n\r\n var i = 1\r\n var sameCount = 0\r\n var failed = false\r\n\r\n while(i < numbers.length && !failed) {\r\n if(numbers(i) == numbers(i - 1)) {\r\n sameCount += 1\r\n permutation += i + 1\r\n } else {\r\n if(sameCount == 0) {\r\n failed = true\r\n } else {\r\n permutation += i - sameCount + 1\r\n sameCount = 0\r\n }\r\n }\r\n i += 1\r\n }\r\n\r\n if(sameCount == 0) {\r\n failed = true\r\n } else {\r\n permutation += i - sameCount\r\n sameCount = 0\r\n }\r\n\r\n if(failed) {\r\n println(-1)\r\n } else {\r\n println(permutation.mkString(\" \"))\r\n }\r\n }\r\n }\r\n}\r\n"}], "src_uid": "cf912f6efc3c0e3fabdaa5f878a777c5"} {"nl": {"description": "Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1\u2009=\u20092 he can't write character 'a' on this paper in a string of length 3 or more. String \"aa\" is allowed while string \"aaa\" is not.Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1\u2009=\u20092 and he wants to send string \"aaa\", he can split it into \"a\" and \"aa\" and use 2 magical papers, or into \"a\", \"a\" and \"a\" and use 3 magical papers. He can't split it into \"aa\" and \"aa\" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.A substring of string s is a string that consists of some consecutive characters from string s, strings \"ab\", \"abc\" and \"b\" are substrings of string \"abc\", while strings \"acb\" and \"ac\" are not. Any string is a substring of itself.While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions: How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109\u2009+\u20097. What is the maximum length of a substring that can appear in some valid splitting? What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting \"aa|a\" and \"a|aa\" are considered different splittings of message \"aaa\".", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) denoting the length of the message. The second line contains the message s of length n that consists of lowercase English letters. The third line contains 26 integers a1,\u2009a2,\u2009...,\u2009a26 (1\u2009\u2264\u2009ax\u2009\u2264\u2009103)\u00a0\u2014 the maximum lengths of substring each letter can appear in.", "output_spec": "Print three lines. In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109\u2009\u2009+\u2009\u20097. In the second line print the length of the longest substring over all the ways. In the third line print the minimum number of substrings over all the ways.", "sample_inputs": ["3\naab\n2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "10\nabcdeabcde\n5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"], "sample_outputs": ["3\n2\n2", "401\n4\n3"], "notes": "NoteIn the first example the three ways to split the message are: a|a|b aa|b a|ab The longest substrings are \"aa\" and \"ab\" of length 2.The minimum number of substrings is 2 in \"a|ab\" or \"aa|b\".Notice that \"aab\" is not a possible splitting because the letter 'a' appears in a substring of length 3, while a1\u2009=\u20092."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject MahmudAndMessage extends App {\n case class Result(ways: Int, maxLen: Int, minCount: Int) {\n def +(other: Option[Result]) = other.fold(this) { that \u21d2\n Result(\n (ways + that.ways) % mod,\n maxLen max that.maxLen,\n minCount min that.minCount)\n }\n def move(len: Int) = Result(ways, maxLen max len, minCount + 1)\n def output = s\"$ways\\n$maxLen\\n$minCount\"\n }\n\n val mod = 1000000007\n def solution(str: String, limits: IndexedSeq[Int]) =\n str.map(c \u21d2 limits(c - 'a'))\n .foldLeft(List.empty[(Int, Result)]) {\n case (history, charLimit) \u21d2\n def go(hist: List[(Int, Result)], res: Option[Result], charLim: Int, len: Int): Result = hist match {\n case Nil \u21d2 Result(1, len, 1) + res\n case (limit, pres) :: tail \u21d2\n val next = pres.move(len) + res\n val nextLim = charLim min limit\n if (nextLim >= len) go(tail, Some(next), nextLim, len + 1) else next\n }\n (charLimit, go(history, None, charLimit, 1)) :: history\n }\n\n readLine()\n val str = readLine()\n val limits = readLine().split(' ').map(_.toInt - 1)\n val hist@((_, res) :: _) = solution(str, limits)\n println(res.output)\n}\n"}], "negative_code": [], "src_uid": "b56e70728d36c41134c39bd6ad13d059"} {"nl": {"description": "You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n\u2009\u00d7\u2009n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.The only method of tile purification known to you is by casting the \"Purification\" spell. You cast this spell on a single tile \u2014 then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.You would like to purify all n\u2009\u00d7\u2009n cells while minimizing the number of times you cast the \"Purification\" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the \"Purification\" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the \"Purification\" spell.Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.", "input_spec": "The first line will contain a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.", "output_spec": "If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x \"Purification\" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the \"Purification\" spell.", "sample_inputs": ["3\n.E.\nE.E\n.E.", "3\nEEE\nE..\nE.E", "5\nEE.EE\nE.EE.\nE...E\n.EE.E\nEE.EE"], "sample_outputs": ["1 1\n2 2\n3 3", "-1", "3 3\n1 3\n2 2\n4 4\n5 3"], "notes": "NoteThe first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which \"Purification\" is cast. Yellow tiles are the tiles being purified as a result of the current \"Purification\" spell. Green tiles are tiles that have been purified previously. In the second example, it is impossible to purify the cell located at row 1 and column 1.For the third example: "}, "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())\n val linesSolution = data.map(_.indexOf('.'))\n val rowsSolution = (0 until n).map(i => (0 until n).find(j => data(j)(i) == '.').getOrElse(-1))\n val r = if (linesSolution.forall(_ >= 0)) {\n (0 until n).map(i => s\"${i + 1} ${linesSolution(i) + 1}\").mkString(\"\\n\")\n } else if (rowsSolution.forall(_ >= 0)) {\n (0 until n).map(i => s\"${rowsSolution(i) + 1} ${i + 1}\").mkString(\"\\n\")\n } else \"-1\"\n println(r)\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 = (1 to n).map(_ => in.next())\n val linesSolution = data.map(_.indexOf('.'))\n val rowsSolution = (0 until n).map(i => (0 until n).find(j => data(j)(i) == '.').getOrElse(-1))\n val r = if (linesSolution.forall(_ >= 0)) {\n (0 until n).map(i => s\"${i + 1} ${linesSolution(i) + 1}\").mkString(\"\\n\")\n } else if (rowsSolution.forall(_ >= 0)) {\n (0 until n).map(i => s\"${linesSolution(i) + 1} ${i + 1}\").mkString(\"\\n\")\n } else \"-1\"\n println(r)\n}"}], "src_uid": "18554f1bb56e192d9a4bc75047fa5df5"} {"nl": {"description": "Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x\u2009=\u2009y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0,\u20090), (1,\u20091), (2,\u20092), ...). The wall and the gates do not belong to any of the kingdoms. Fafa is at the gate at position (0,\u20090) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x,\u2009y) to (x,\u2009y\u2009+\u20091)) and 'R' (move one step right, from (x,\u2009y) to (x\u2009+\u20091,\u2009y)). Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0,\u20090), i.\u00a0e. he is initially on the side he needs. ", "input_spec": "The first line of the input contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of moves in the walking sequence. The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.", "output_spec": "On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.", "sample_inputs": ["1\nU", "6\nRURUUR", "7\nURRRUUU"], "sample_outputs": ["0", "1", "2"], "notes": "NoteThe figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins. "}, "positive_code": [{"source_code": "object _935B 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, instr) = io.read[(Int, String)]\n\n val res = instr.scanLeft(0) {\n case (x, 'R') => x + 1\n case (x, 'U') => x - 1\n }\n\n //debug(res)\n\n var curr = if (instr.head == 'R') 1 else -1\n var ans = 0\n for {\n i <- res if i != 0\n if curr.signum != i.signum\n } {\n curr = i.signum\n ans += 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}\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": "e4381bd9f22c0e49525cc05cc5cd2399"} {"nl": {"description": "You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r,\u2009c). You are staying in the cell (r1,\u2009c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2,\u2009c2) since the exit to the next level is there. Can you do this?", "input_spec": "The first line contains two integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500)\u00a0\u2014 the number of rows and columns in the cave description. Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters \".\" (that is, intact ice) and \"X\" (cracked ice). The next line contains two integers, r1 and c1 (1\u2009\u2264\u2009r1\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009c1\u2009\u2264\u2009m)\u00a0\u2014 your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1,\u2009c1), that is, the ice on the starting cell is initially cracked. The next line contains two integers r2 and c2 (1\u2009\u2264\u2009r2\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009c2\u2009\u2264\u2009m)\u00a0\u2014 the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.", "output_spec": "If you can reach the destination, print 'YES', otherwise print 'NO'.", "sample_inputs": ["4 6\nX...XX\n...XX.\n.X..X.\n......\n1 6\n2 2", "5 4\n.X..\n...X\nX.X.\n....\n.XX.\n5 3\n1 1", "4 7\n..X.XX.\n.XX..X.\nX...X..\nX......\n2 2\n1 6"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first sample test one possible path is:After the first visit of cell (2,\u20092) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended."}, "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\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"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk]\u2009=\u2009sp1sp2... spk(1\u2009\u2264\u2009p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009pk\u2009\u2264\u2009|s|) a subsequence of string s\u2009=\u2009s1s2... s|s|.String x\u2009=\u2009x1x2... x|x| is lexicographically larger than string y\u2009=\u2009y1y2... y|y|, if either |x|\u2009>\u2009|y| and x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009x|y|\u2009=\u2009y|y|, or exists such number r (r\u2009<\u2009|x|,\u2009r\u2009<\u2009|y|), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xr\u2009=\u2009yr and xr\u2009+\u20091\u2009>\u2009yr\u2009+\u20091. Characters in lines are compared like their ASCII codes.", "input_spec": "The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.", "output_spec": "Print the lexicographically maximum subsequence of string s.", "sample_inputs": ["ababba", "abbcbccacbbcbaaba"], "sample_outputs": ["bbba", "cccccbba"], "notes": "NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA"}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Ksusha is a beginner coder. Today she starts studying arrays. She has array a1,\u2009a2,\u2009...,\u2009an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers the array has. The next line contains integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the array elements.", "output_spec": "Print a single integer \u2014 the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them.", "sample_inputs": ["3\n2 2 4", "5\n2 1 3 1 6", "3\n2 3 5"], "sample_outputs": ["2", "1", "-1"], "notes": null}, "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 val min = data.min\n if (data.forall(_ % min == 0))\n println(min)\n else\n println(-1)\n}"}], "negative_code": [], "src_uid": "b0ffab0bf169f8278af48fe2d58dcd2d"} {"nl": {"description": "Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi\u2009\u2260\u2009yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n\u2009-\u20091) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009105;\u00a0xi\u2009\u2260\u2009yi) \u2014 the color numbers for the home and away kits of the i-th team.", "output_spec": "For each team, print on a single line two space-separated integers \u2014 the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.", "sample_inputs": ["2\n1 2\n2 1", "3\n1 2\n2 1\n1 3"], "sample_outputs": ["2 0\n2 0", "3 1\n4 0\n2 2"], "notes": null}, "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}"}, {"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"}], "negative_code": [], "src_uid": "7899a22cee29bb96d671f6188f246c21"} {"nl": {"description": "Each day in Berland consists of $$$n$$$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day \u2014 it is a sequence $$$a_1, a_2, \\dots, a_n$$$ (each $$$a_i$$$ is either $$$0$$$ or $$$1$$$), where $$$a_i=0$$$ if Polycarp works during the $$$i$$$-th hour of the day and $$$a_i=1$$$ if Polycarp rests during the $$$i$$$-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.", "input_spec": "The first line contains $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) \u2014 number of hours per day. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$), where $$$a_i=0$$$ if the $$$i$$$-th hour in a day is working and $$$a_i=1$$$ if the $$$i$$$-th hour is resting. It is guaranteed that $$$a_i=0$$$ for at least one $$$i$$$.", "output_spec": "Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.", "sample_inputs": ["5\n1 0 1 0 1", "6\n0 1 0 1 1 0", "7\n1 0 1 1 1 0 1", "3\n0 0 0"], "sample_outputs": ["2", "2", "3", "0"], "notes": "NoteIn the first example, the maximal rest starts in last hour and goes to the first hour of the next day.In the second example, Polycarp has maximal rest from the $$$4$$$-th to the $$$5$$$-th hour.In the third example, Polycarp has maximal rest from the $$$3$$$-rd to the $$$5$$$-th hour.In the fourth example, Polycarp has no rest at all."}, "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 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"}, {"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"} {"nl": {"description": "A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print \"YES\", otherwise print \"NO\" (without the quotes).", "input_spec": "The first and only line consists of a string $$$S$$$ ($$$ 1 \\le |S| \\le 5\\,000 $$$). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.", "output_spec": "Print \"YES\" or \"NO\", according to the condition.", "sample_inputs": ["aaabccc", "bbacc", "aabc"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteConsider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.Consider third example: the number of 'c' is equal to the number of 'b'."}, "positive_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.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}"}, {"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"} {"nl": {"description": "Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: The try operator. It opens a new try-catch-block. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message \"Unhandled Exception\".To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.Your task is: given a program in VPL, determine, what message will be displayed on the screen.", "input_spec": "The first line contains a single integer: n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces. The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark. The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols. Length of any line in the input file does not exceed 50 symbols. ", "output_spec": "Print the message the screen will show after the given program is executed.", "sample_inputs": ["8\ntry\n try\n throw ( AE ) \n catch ( BE, \"BE in line 3\")\n\n try\n catch(AE, \"AE in line 5\") \ncatch(AE,\"AE somewhere\")", "8\ntry\n try\n throw ( AE ) \n catch ( AE, \"AE in line 3\")\n\n try\n catch(BE, \"BE in line 5\") \ncatch(AE,\"AE somewhere\")", "8\ntry\n try\n throw ( CE ) \n catch ( BE, \"BE in line 3\")\n\n try\n catch(AE, \"AE in line 5\") \ncatch(AE,\"AE somewhere\")"], "sample_outputs": ["AE somewhere", "AE in line 3", "Unhandled Exception"], "notes": "NoteIn the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,\"BE in line 3\") and try-catch(AE,\"AE somewhere\"). Exception type is AE, so the second block will be activated, because operator catch(AE,\"AE somewhere\") has exception type AE as parameter and operator catch(BE,\"BE in line 3\") has exception type BE.In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,\"AE in line 3\") and try-catch(AE,\"AE somewhere\"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,\"AE in line 3\") is described earlier than catch(AE,\"AE somewhere\")In the third sample there is no blocks that can be activated by an exception of type CE."}, "positive_code": [{"source_code": "import java.util.Scanner\nobject TryCatch {\n \n val scanner = new Scanner(System.in)\n \n def main(args: Array[String]): Unit = {\n val x = scanner.nextInt()\n scanner.nextLine()\n var level = 0\n var raiseLevel = -1\n var raisedExc = \"\";\n var skipLevels = 0;\n for (i <- 0 until x) {\n var line = scanner.nextLine().trim();\n if (line.equals(\"try\")){\n level += 1\n if (raiseLevel >= 0)\n skipLevels += 1\n } else if (line.startsWith(\"throw\")){\n line = line.replace(\"throw\",\"\").trim()\n line = line.substring(1,line.length()-1).trim();\n raisedExc = line;\n raiseLevel = level;\n } else if (line.startsWith(\"catch\")) {\n level -= 1\n line = line.replace(\"catch\",\"\").trim()\n line = line.substring(1,line.length()-1).trim();\n var params : Array[String] = line.split(\",\")\n \n if (level <= raiseLevel && params(0).trim().equals(raisedExc) && skipLevels == 0){\n var message = params(1).trim()\n message = message.substring(1,message.length()-1)\n println(message)\n return\n }\n if (skipLevels > 0) {\n skipLevels -= 1\n }\n }\n }\n println(\"Unhandled Exception\")\n }\n\n}"}], "negative_code": [{"source_code": "import java.util.Scanner\nobject TryCatch {\n \n val scanner = new Scanner(System.in)\n \n def main(args: Array[String]): Unit = {\n val x = scanner.nextInt()\n scanner.nextLine()\n var level = 0\n var raiseLevel = 0\n var raisedExc = \"\";\n for (i <- 0 until x) {\n var line = scanner.nextLine().trim();\n if (line.equals(\"try\")){\n level += 1\n } else if (line.startsWith(\"throw\")){\n line = line.replace(\"throw\",\"\").trim()\n line = line.substring(1,line.length()-1).trim();\n raisedExc = line;\n raiseLevel = level;\n } else if (line.startsWith(\"catch\")) {\n line = line.replace(\"catch\",\"\").trim()\n line = line.substring(1,line.length()-1).trim();\n var params : Array[String] = line.split(\",\")\n \n if (level <= raiseLevel && params(0).trim().equals(raisedExc)){\n var message = params(1).trim()\n message = message.substring(1,message.length()-1)\n println(message)\n return\n }\n }\n }\n println(\"Unhandled Exception\")\n }\n\n}"}], "src_uid": "320e6c06194f8b1ccf1f4218d0757d2f"} {"nl": {"description": "Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\\le k\\bmod n\\le n-1$$$. For example, $$$100\\bmod 12=4$$$ and $$$(-1337)\\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.", "input_spec": "Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 10^4$$$)\u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 2\\cdot 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,\\ldots,a_{n-1}$$$ ($$$-10^9\\le a_i\\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, output a single line containing \"YES\" if there is exactly one guest assigned to each room after the shuffling process, or \"NO\" otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["6\n1\n14\n2\n1 -1\n4\n5 5 5 1\n3\n3 2 1\n2\n0 1\n5\n-239 -2 -100 -3 -11"], "sample_outputs": ["YES\nYES\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case, every guest is shifted by $$$14$$$ rooms, so the assignment is still unique.In the second test case, even guests move to the right by $$$1$$$ room, and odd guests move to the left by $$$1$$$ room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by $$$1$$$ room, and the other guests move to the right by $$$5$$$ rooms. We can show that the assignment is still unique.In the fourth test case, guests $$$0$$$ and $$$1$$$ are both assigned to room $$$3$$$.In the fifth test case, guests $$$1$$$ and $$$2$$$ are both assigned to room $$$2$$$."}, "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 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"}, {"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"} {"nl": {"description": "Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \\times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).Note that Vova can't put bricks vertically.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the initial heights of the parts of the wall.", "output_spec": "Print \"YES\" if Vova can complete the wall using any amount of bricks (possibly zero). Print \"NO\" otherwise.", "sample_inputs": ["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put no bricks in the wall.In the third example the wall is already complete."}, "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 set = new java.util.TreeSet[Integer]()\n REP(N) { i =>\n set.add(i)\n }\n\n val cnt = mutable.Map[Int, Int]().withDefaultValue(0)\n val P = mutable.Map[Int, Array[Int]]()\n REP(N) { i =>\n cnt(A(i)) = cnt(A(i)) + 1\n }\n val nums = Array.ofDim[Int](cnt.size)\n var ptr = 0\n cnt.foreach { case (i, c) =>\n P(i) = new Array(c)\n nums(ptr) = i\n ptr += 1\n }\n REP_r(N) { i =>\n cnt(A(i)) -= 1\n P(A(i))(cnt(A(i))) = i\n }\n P.values.foreach { as =>\n Sorting.quickSort(as)\n }\n Sorting.quickSort(nums)\n\n def ok: Boolean = {\n // \u4e00\u756a\u5927\u304d\u3044\u9ad8\u3055\u306f\u8003\u616e\u3057\u306a\u304f\u3066\u3044\u3044\n REP(nums.length - 1) { i =>\n val num = nums(i)\n val p = P(num)\n\n if (p.length % 2 == 1) return false\n REP(p.length / 2) { j =>\n val p1 = p(j * 2)\n val p2 = p(j * 2 + 1)\n if (set.higher(p1) != p2) return false\n else {\n set.remove(p1)\n set.remove(p2)\n }\n }\n }\n true\n }\n\n if (ok) {\n out.println(\"YES\")\n } else {\n out.println(\"NO\")\n }\n }\n\n /**\n * \u6700\u5927M\u500b\u306e\u30b0\u30eb\u30fc\u30d7\u306b\u5206\u5272\u3057\u3066\u30b0\u30eb\u30fc\u30d7\u6bce\u306e\u914d\u5217\u306b\u5165\u308c\u308b\n */\n def grouped(N: Int, M: Int, g: Array[Int], v: Array[Int]): Array[Array[Int]] = {\n val cnt = Array.ofDim[Int](M)\n val C = Array.ofDim[Array[Int]](M)\n REP(N) { i =>\n cnt(g(i)) += 1\n }\n REP(M) { i =>\n C(i) = new Array(cnt(i))\n }\n REP_r(N) { i =>\n cnt(g(i)) -= 1\n C(g(i))(cnt(g(i))) = v(i)\n }\n C\n }\n\n class InputReader(val stream: InputStream) {\n private val reader = new BufferedReader(new InputStreamReader(stream), 32768)\n private var tokenizer: StringTokenizer = _\n\n def next(): String = {\n while (tokenizer == null || !tokenizer.hasMoreTokens)\n tokenizer = new StringTokenizer(reader.readLine)\n tokenizer.nextToken\n }\n\n def nextInt(): Int = next().toInt\n def nextLong(): Long = next().toLong\n def nextChar(): Char = next().charAt(0)\n }\n val sc = new InputReader(System.in)\n def ni(): Int = sc.nextInt()\n def nl(): Long = sc.nextLong()\n def 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": "f73b832bbbfe688e378f3d693cfa23b8"} {"nl": {"description": "School holidays come in Berland. The holidays are going to continue for n days. The students of school \u2116N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.", "input_spec": "The first input line contains two numbers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of days in Berland holidays and the number of people in charge of the watering respectively. The next m lines contain the description of the duty schedule. Each line contains two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009n), meaning that the i-th person in charge should water the flowers from the ai-th to the bi-th day inclusively, once a day. The duty shifts are described sequentially, i.e. bi\u2009\u2264\u2009ai\u2009+\u20091 for all i from 1 to n\u2009-\u20091 inclusively. ", "output_spec": "Print \"OK\" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers \u2014 the day number and the number of times the flowers will be watered that day.", "sample_inputs": ["10 5\n1 2\n3 3\n4 6\n7 7\n8 10", "10 5\n1 2\n2 3\n4 5\n7 8\n9 10", "10 5\n1 2\n3 3\n5 7\n7 7\n7 10"], "sample_outputs": ["OK", "2 2", "4 0"], "notes": "NoteKeep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "30c4f155336cf762699a1bbc55a60d27"} {"nl": {"description": "Given an array $$$a=[a_1,a_2,\\dots,a_n]$$$ of $$$n$$$ positive integers, you can do operations of two types on it: Add $$$1$$$ to every element with an odd index. In other words change the array as follows: $$$a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \\dots$$$. Add $$$1$$$ to every element with an even index. In other words change the array as follows: $$$a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \\dots$$$.Determine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations.Note that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \\leq n \\leq 50$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^3$$$)\u00a0\u2014 the elements of the array. Note that after the performed operations the elements in the array can become greater than $$$10^3$$$.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output \"YES\" if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["4\n\n3\n\n1 2 1\n\n4\n\n2 2 2 3\n\n4\n\n2 2 2 2\n\n5\n\n1000 1 1000 1 1000"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteFor the first test case, we can increment the elements with an even index, obtaining the array $$$[1, 3, 1]$$$, which contains only odd numbers, so the answer is \"YES\".For the second test case, we can show that after performing any number of operations we won't be able to make all elements have the same parity, so the answer is \"NO\".For the third test case, all elements already have the same parity so the answer is \"YES\".For the fourth test case, we can perform one operation and increase all elements at odd positions by $$$1$$$, thus obtaining the array $$$[1001, 1, 1001, 1, 1001]$$$, and all elements become odd so the answer is \"YES\"."}, "positive_code": [{"source_code": "import scala.io.StdIn\r\n\r\nobject Task3 extends App {\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 array = StdIn.readLine().split(\" \").map(_.toInt)\r\n var pos = 0;\r\n var allOddsIsOdds = true\r\n var allOddsIsEven = true\r\n var allEvenIsOdds = true\r\n var allEvenIsEven = true\r\n\r\n do {\r\n if (isEven(pos)) {\r\n if (isEven(array(pos))) {\r\n allEvenIsOdds = false\r\n } else {\r\n allEvenIsEven = false\r\n }\r\n } else {\r\n if (isOdd(array(pos))) {\r\n allOddsIsEven = false\r\n }\r\n else {\r\n allOddsIsOdds = false\r\n }\r\n }\r\n pos += 1\r\n\r\n } while (maybeAllHasSameParity && pos < array.length)\r\n\r\n if (maybeAllHasSameParity) {\r\n println(\"YES\")\r\n } else {\r\n println(\"NO\")\r\n }\r\n\r\n def maybeAllHasSameParity: Boolean = {\r\n (allOddsIsEven || allOddsIsOdds) & (allEvenIsEven || allEvenIsOdds)\r\n }\r\n\r\n def isOdd(num: Int): Boolean = num % 2 == 1\r\n def isEven(num: Int): Boolean = num % 2 == 0\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "fbb4e1cf1cad47481c6690ce54b27a1e"} {"nl": {"description": "Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where f1\u2009=\u20091, f2\u2009=\u20091, fn\u2009=\u2009fn\u2009-\u20092\u2009+\u2009fn\u2009-\u20091 (n\u2009>\u20092). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.", "input_spec": "The first and only line of input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000).", "output_spec": "Print Eleven's new name on the first and only line of output.", "sample_inputs": ["8", "15"], "sample_outputs": ["OOOoOooO", "OOOoOooOooooOoo"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "a7c0484275e62f0bc70d9edaac27d7d6"} {"nl": {"description": "This is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($$$x_i - x_{i - 1}$$$, where $$$i \\ge 2$$$) is constant\u00a0\u2014 such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form $$$x_i = x_1 + (i - 1) d$$$, where $$$d$$$ is a common difference of the sequence.There is a secret list of $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$.It is guaranteed that all elements $$$a_1, a_2, \\ldots, a_n$$$ are between $$$0$$$ and $$$10^9$$$, inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference ($$$d > 0$$$). For example, the list $$$[14, 24, 9, 19]$$$ satisfies this requirement, after sorting it makes a list $$$[9, 14, 19, 24]$$$, which can be produced as $$$x_n = 9 + 5 \\cdot (n - 1)$$$.Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most $$$60$$$ queries of following two types: Given a value $$$i$$$ ($$$1 \\le i \\le n$$$), the device will show the value of the $$$a_i$$$. Given a value $$$x$$$ ($$$0 \\le x \\le 10^9$$$), the device will return $$$1$$$ if an element with a value strictly greater than $$$x$$$ exists, and it will return $$$0$$$ otherwise.Your can use this special device for at most $$$60$$$ queries. Could you please find out the smallest element and the common difference of the sequence? That is, values $$$x_1$$$ and $$$d$$$ in the definition of the arithmetic progression. Note that the array $$$a$$$ is not sorted.", "input_spec": null, "output_spec": null, "sample_inputs": ["4\n\n0\n\n1\n\n14\n\n24\n\n9\n\n19"], "sample_outputs": ["> 25\n\n> 15\n\n? 1\n\n? 2\n\n? 3\n\n? 4\n\n! 9 5"], "notes": "NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The list in the example test is $$$[14, 24, 9, 19]$$$."}, "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\n def execQueries(q: Array[Int]): Array[Int] = {\n val res = Array.ofDim[Int](q.length)\n REP(q.length) { i =>\n out.println(s\"? ${q(i)}\")\n out.flush()\n res(i) = ni()\n }\n res\n }\n\n def answer(a: Int, b: Int): Unit = {\n// debug(s\"Ans $a $b\")\n out.println(s\"! $b $a\")\n out.flush()\n }\n\n if (N <= 60) {\n val ys = execQueries(Array.iterate(1, N)(_ + 1))\n val ms = ys.min\n val mx = ys.max\n val b = ms\n val a = (mx - b) / (N - 1)\n answer(a, b)\n } else {\n\n def mkQueryList(remainQueries: Int): Array[Int] = {\n val nums = mutable.Set[Int]()\n while (nums.size < remainQueries) {\n import scala.util.Random\n nums += Random.nextInt(N) + 1\n }\n nums.toArray\n }\n\n def queryGt(x: Int): Boolean = {\n out.println(s\"> $x\")\n out.flush()\n ni() == 1\n }\n\n /**\n * (max, \u4f7f\u3063\u305f\u30af\u30a8\u30ea\u30fc\u56de\u6570)\n */\n def queryMax: (Int, Int) = {\n var l = 0\n var r = 1e9.toInt + 1\n var cnt = 0\n while (r - l > 1) {\n val mid = (r + l) / 2\n if (queryGt(mid)) l = mid\n else r = mid\n cnt += 1\n }\n\n // l\u3060\u3068x\n i + 1 until n foreach { j =>\n D += abs(answers(i) - answers(j))\n }\n }\n\n// debug(queries)\n// debug(answers)\n// debug(D.mkString(\" \"))\n\n val a = gcd(D.toArray)\n val b = mx - a * (N - 1)\n answer(a, b)\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 gcd(as: Array[Int]): Int = {\n var res = as(0)\n REP(as.length - 1, 1) { i =>\n res = gcd(res, as(i))\n }\n res\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 def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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\n def execQueries(q: Array[Int]): Array[Int] = {\n val res = Array.ofDim[Int](q.length)\n REP(q.length) { i =>\n out.println(s\"? ${q(i)}\")\n out.flush()\n res(i) = ni()\n }\n res\n }\n\n def answer(a: Int, b: Int): Unit = {\n// debug(s\"Ans $a $b\")\n out.println(s\"! $a $b\")\n out.flush()\n }\n\n if (N <= 60) {\n val ys = execQueries(Array.iterate(1, N)(_ + 1))\n val ms = ys.min\n val mx = ys.max\n val b = ms\n val a = (mx - b) / (N - 1)\n answer(a, b)\n } else {\n\n def mkQueryList(remainQueries: Int): Array[Int] = {\n val nums = mutable.Set[Int]()\n while (nums.size < remainQueries) {\n import scala.util.Random\n nums += Random.nextInt(N) + 1\n }\n nums.toArray\n }\n\n def queryGt(x: Int): Boolean = {\n out.println(s\"> $x\")\n out.flush()\n ni() == 1\n }\n\n /**\n * (max, \u4f7f\u3063\u305f\u30af\u30a8\u30ea\u30fc\u56de\u6570)\n */\n def queryMax: (Int, Int) = {\n var l = 0\n var r = 1e9.toInt + 1\n var cnt = 0\n while (r - l > 1) {\n val mid = (r + l) / 2\n if (queryGt(mid)) l = mid\n else r = mid\n cnt += 1\n }\n\n // l\u3060\u3068x\n i + 1 until n foreach { j =>\n D += abs(answers(i) - answers(j))\n }\n }\n\n// debug(queries)\n// debug(answers)\n// debug(D.mkString(\" \"))\n\n val a = gcd(D.toArray)\n val b = mx - a * (N - 1)\n answer(a, b)\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 gcd(as: Array[Int]): Int = {\n var res = as(0)\n REP(as.length - 1, 1) { i =>\n res = gcd(res, as(i))\n }\n res\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": "36619f520ea5a523a94347ffd3dc2c70"} {"nl": {"description": "You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label $$$1$$$ on it) is equal to $$$D$$$ (or say that there are no such spanning trees). Recall that the degree of a vertex is the number of edges incident to it.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$D$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$n - 1 \\le m \\le min(2 \\cdot 10^5, \\frac{n(n-1)}{2}), 1 \\le D < n$$$) \u2014 the number of vertices, the number of edges and required degree of the first vertex, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$u_i \\ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i.\u2009e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \\ne u_i$$$ is satisfied.", "output_spec": "If there is no spanning tree satisfying the condition from the problem statement, print \"NO\" in the first line. Otherwise print \"YES\" in the first line and then print $$$n-1$$$ lines describing the edges of a spanning tree such that the degree of the first vertex (vertex with label $$$1$$$ on it) is equal to $$$D$$$. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge $$$(v, u)$$$ is considered the same as the edge $$$(u, v)$$$). If there are multiple possible answers, print any of them.", "sample_inputs": ["4 5 1\n1 2\n1 3\n1 4\n2 3\n3 4", "4 5 3\n1 2\n1 3\n1 4\n2 3\n3 4", "4 4 3\n1 2\n1 4\n2 3\n3 4"], "sample_outputs": ["YES\n2 1\n2 3\n3 4", "YES\n1 2\n1 3\n4 1", "NO"], "notes": "NoteThe picture corresponding to the first and second examples: The picture corresponding to the third example: "}, "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, D = ni()\n val (f, t) = na2(M, -1)\n val g = packUGraph(N, f, t)\n val uf = new UnionFind(N)\n\n // 1\u306e\u96a3\u30922, \u305d\u308c\u4ee5\u5916\u30923\u3068\u3059\u308b\n\n // {1, 2}\n val notThree = Array.ofDim[Boolean](N)\n notThree(0) = true // 1\u3082\u5165\u308c\u3066\u304a\u304f\n REP(g(0).length) { i =>\n notThree(g(0)(i)) = true\n }\n\n var set = N\n case class Edge(v: Int, u: Int)\n val ans = ArrayBuffer[Edge]()\n\n // \uff11\u3068\u76f4\u63a5\u7e4b\u304c\u3089\u306a\u3044\u540c\u58eb\u3092\u7e4b\u3052\u308b\n // 3-3\n REP(M) { i =>\n if (!notThree(f(i)) && !notThree(t(i))) {\n if (!uf.same(f(i), t(i))) {\n uf.unite(f(i), t(i))\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n // \u3053\u306e\u6642\u70b9\u3067\u4f5c\u3063\u305f\u96c6\u5408\u306f\u30011\u3068\u9023\u7d50\u3057\u306a\u3044\u304b\u30643\u540c\u58eb\u3067\u306f\u304f\u3063\u3064\u3044\u3066\u3044\u308b\u306e\u3067\u3001\u304b\u306a\u3089\u305a\uff12\u306e\u3069\u308c\u304b\u3068\u304f\u3063\u3064\u304f\n // 2-3\n // 3->2\u3078\u304f\u3063\u3064\u304f\u3063\u3066\u3084\u3089\u306a\u3044\u3068\u3042\u3076\u308c\u304c\u3067\u308b\n val threes = Array.ofDim[Boolean](N)\n REP(N) { i =>\n if (!notThree(i) && uf.find(i) == i) {\n threes(i) = true\n }\n }\n // \u9023\u7d50\u30b0\u30e9\u30d5\u306a\u306e\u3067\u30013\u306f\u304b\u306a\u3089\u305a\u3069\u3053\u304b\u306e2\u306b\u3064\u306a\u304c\u308b\u306f\u305a\n REP(M) { i =>\n val id1 = uf.find(f(i))\n val id2 = uf.find(t(i))\n if (threes(id1) && notThree(t(i)) || threes(id2) && notThree(f(i))) {\n uf.unite(f(i), t(i))\n ans += Edge(f(i), t(i))\n set -= 1\n if (threes(id1)) threes(id1) = false\n else threes(id2) = false\n }\n }\n\n // \u3053\u306e\u6642\u70b9\u30671\u3068\u30011\u306b\u9023\u7d50\u3067\u304d\u308b\u96c6\u5408\u306b\u5206\u5272\u3055\u308c\u3066\u3044\u308b\u306f\u305a\n\n // D\u3092\u9054\u6210\u3067\u304d\u308b\u3088\u3046\u306b\u9023\u7d50\u6210\u5206\u3092\u3078\u3089\u3057\u3066\u3044\u304f\n // {2, 3}-{2, 3}\n REP(M) { i =>\n if (set > D + 1 && f(i) != 0 && t(i) != 0) {\n if (!uf.same(f(i), t(i))) {\n uf.unite(f(i), t(i))\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n if (set != D + 1) {\n out.println(\"NO\")\n return\n\n } else {\n // 1-2\n REP(g(0).length) { i =>\n val u = g(0)(i)\n if (set > 1 && !uf.same(0, u)) {\n uf.unite(0, u)\n ans += Edge(0, u)\n set -= 1\n }\n }\n\n if (set != 1) out.println(\"NO\")\n else {\n out.println(\"YES\")\n REP(ans.length) { i =>\n val e = ans(i)\n out.println(s\"${e.v + 1} ${e.u + 1}\")\n }\n }\n }\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 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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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 same(x: Int, y: Int): Boolean = {\n find(x) == find(y)\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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 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 val N, M, D = ni()\n val (f, t) = na2(M, -1)\n val g = packUGraph(N, f, t)\n val uf = new UnionFind(N)\n\n // 1\u306e\u96a3\u30922, \u305d\u308c\u4ee5\u5916\u30923\u3068\u3059\u308b\n\n // neighbors\u306f 1 + 2\n val neighbors = Array.ofDim[Boolean](N)\n neighbors(0) = true // 1\u3082\u5165\u308c\u3066\u304a\u304f\n REP(g(0).length) { i =>\n neighbors(g(0)(i)) = true\n }\n\n var set = N\n case class Edge(v: Int, u: Int)\n val ans = ArrayBuffer[Edge]()\n\n // \uff11\u3068\u76f4\u63a5\u7e4b\u304c\u3089\u306a\u3044\u540c\u58eb\u3092\u7e4b\u3052\u308b\n // 3-3\n REP(M) { i =>\n if (!neighbors(f(i)) && !neighbors(t(i))) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n // \uff11\u3068\u7e4b\u304c\u3063\u3066\u3044\u308b\u3082\u306e\u3068\u305d\u308c\u3089\u3092\u7e4b\u3052\u308b\n // 2-3\n REP(M) { i =>\n if (set > D + 1 && (neighbors(f(i)) ^ neighbors(t(i))) && f(i) != 0 && t(i) != 0) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n // \u9023\u7d50\u30b0\u30e9\u30d5\u306a\u306e\u3067\u30013\u306f\u304b\u306a\u3089\u305a\u3069\u3053\u304b\u306e2\u306b\u3064\u306a\u304c\u308b\u306f\u305a\n // \u3053\u306e\u6642\u70b9\u30671\u3068\u30011\u306b\u9023\u7d50\u3067\u304d\u308b\u96c6\u5408\u306b\u5206\u5272\u3055\u308c\u3066\u3044\u308b\u306f\u305a\n\n // D\u3092\u9054\u6210\u3067\u304d\u308b\u3088\u3046\u306b\u9023\u7d50\u6210\u5206\u3092\u3078\u3089\u3057\u3066\u3044\u304f\n // {2, 3}-{2, 3}\n REP(M) { i =>\n if (set > D + 1 && f(i) != 0 && t(i) != 0) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n if (set != D + 1) {\n out.println(\"NO\")\n return\n\n } else {\n // 1-2\n REP(g(0).length) { i =>\n val u = g(0)(i)\n if (set > 1 && !uf.same(0, u)) {\n ans += Edge(0, u)\n set -= 1\n }\n }\n\n if (set != 1) out.println(\"NO\")\n else {\n out.println(\"YES\")\n REP(ans.length) { i =>\n val e = ans(i)\n out.println(s\"${e.v + 1} ${e.u + 1}\")\n }\n }\n }\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 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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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 same(x: Int, y: Int): Boolean = {\n find(x) == find(y)\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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 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 def solve(): Unit = {\n val N, M, D = ni()\n val (f, t) = na2(M, -1)\n val g = packUGraph(N, f, t)\n val uf = new UnionFind(N)\n\n // 1\u306e\u96a3\u30922, \u305d\u308c\u4ee5\u5916\u30923\u3068\u3059\u308b\n\n // {1, 2}\n val notThree = Array.ofDim[Boolean](N)\n notThree(0) = true // 1\u3082\u5165\u308c\u3066\u304a\u304f\n REP(g(0).length) { i =>\n notThree(g(0)(i)) = true\n }\n\n var set = N\n case class Edge(v: Int, u: Int)\n val ans = ArrayBuffer[Edge]()\n\n // \uff11\u3068\u76f4\u63a5\u7e4b\u304c\u3089\u306a\u3044\u540c\u58eb\u3092\u7e4b\u3052\u308b\n // 3-3\n REP(M) { i =>\n if (!notThree(f(i)) && !notThree(t(i))) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n // \u3053\u306e\u6642\u70b9\u3067\u4f5c\u3063\u305f\u96c6\u5408\u306f\u30011\u3068\u9023\u7d50\u3057\u306a\u3044\u304b\u30643\u540c\u58eb\u3067\u306f\u304f\u3063\u3064\u3044\u3066\u3044\u308b\u306e\u3067\u3001\u304b\u306a\u3089\u305a\uff12\u306e\u3069\u308c\u304b\u3068\u304f\u3063\u3064\u304f\n // 2-3\n // 3->2\u3078\u304f\u3063\u3064\u304f\u3063\u3066\u3084\u3089\u306a\u3044\u3068\u3042\u3076\u308c\u304c\u3067\u308b\n val threes = Array.ofDim[Boolean](N)\n REP(N) { i =>\n if (!notThree(i) && uf.find(i) == i) {\n threes(i) = true\n }\n }\n // \u9023\u7d50\u30b0\u30e9\u30d5\u306a\u306e\u3067\u30013\u306f\u304b\u306a\u3089\u305a\u3069\u3053\u304b\u306e2\u306b\u3064\u306a\u304c\u308b\u306f\u305a\n REP(M) { i =>\n val id1 = uf.find(f(i))\n val id2 = uf.find(t(i))\n if (threes(id1) && notThree(t(i)) || threes(id2) && notThree(f(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n if (threes(id1)) threes(id1) = false\n else threes(id2) = false\n }\n }\n\n // \u3053\u306e\u6642\u70b9\u30671\u3068\u30011\u306b\u9023\u7d50\u3067\u304d\u308b\u96c6\u5408\u306b\u5206\u5272\u3055\u308c\u3066\u3044\u308b\u306f\u305a\n\n // D\u3092\u9054\u6210\u3067\u304d\u308b\u3088\u3046\u306b\u9023\u7d50\u6210\u5206\u3092\u3078\u3089\u3057\u3066\u3044\u304f\n // {2, 3}-{2, 3}\n REP(M) { i =>\n if (set > D + 1 && f(i) != 0 && t(i) != 0) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n if (set != D + 1) {\n out.println(\"NO\")\n return\n\n } else {\n // 1-2\n REP(g(0).length) { i =>\n val u = g(0)(i)\n if (set > 1 && !uf.same(0, u)) {\n ans += Edge(0, u)\n set -= 1\n }\n }\n\n if (set != 1) out.println(\"NO\")\n else {\n out.println(\"YES\")\n REP(ans.length) { i =>\n val e = ans(i)\n out.println(s\"${e.v + 1} ${e.u + 1}\")\n }\n }\n }\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 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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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 same(x: Int, y: Int): Boolean = {\n find(x) == find(y)\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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 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 def solve(): Unit = {\n val N, M, D = ni()\n val (f, t) = na2(M, -1)\n val g = packUGraph(N, f, t)\n val uf = new UnionFind(N)\n\n // 1\u306e\u96a3\u30922, \u305d\u308c\u4ee5\u5916\u30923\u3068\u3059\u308b\n\n // neighbors\u306f 1 + 2\n val neighbors = Array.ofDim[Boolean](N)\n neighbors(0) = true // 1\u3082\u5165\u308c\u3066\u304a\u304f\n REP(g(0).length) { i =>\n neighbors(g(0)(i)) = true\n }\n\n var set = N\n case class Edge(v: Int, u: Int)\n val ans = ArrayBuffer[Edge]()\n\n // \uff11\u3068\u76f4\u63a5\u7e4b\u304c\u3089\u306a\u3044\u540c\u58eb\u3092\u7e4b\u3052\u308b\n // 3-3\n REP(M) { i =>\n if (!neighbors(f(i)) && !neighbors(t(i))) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n // \u3053\u306e\u6642\u70b9\u3067\u4f5c\u3063\u305f\u96c6\u5408\u306f\u30011\u3068\u9023\u7d50\u3057\u306a\u3044\u304b\u30643\u540c\u58eb\u3067\u306f\u304f\u3063\u3064\u3044\u3066\u3044\u308b\u306e\u3067\u3001\u304b\u306a\u3089\u305a\uff12\u306e\u3069\u308c\u304b\u3068\u304f\u3063\u3064\u304f\n // 2-3\n // 3->2\u3078\u304f\u3063\u3064\u304f\u3063\u3066\u3084\u3089\u306a\u3044\u3068\u3042\u3076\u308c\u304c\u3067\u308b\n val threes = Array.ofDim[Boolean](N)\n REP(N) { i =>\n if (!neighbors(i) && uf.find(i) == i) {\n threes(i) = true\n }\n }\n // \u9023\u7d50\u30b0\u30e9\u30d5\u306a\u306e\u3067\u30013\u306f\u304b\u306a\u3089\u305a\u3069\u3053\u304b\u306e2\u306b\u3064\u306a\u304c\u308b\u306f\u305a\n REP(N) { i =>\n if (threes(i)) {\n var connected = false\n REP(g(i).length) { j =>\n val u = g(i)(j)\n if (!connected && neighbors(u)) {\n ans += Edge(f(i), t(i))\n set -= 1\n connected = true\n }\n }\n }\n }\n\n // \u3053\u306e\u6642\u70b9\u30671\u3068\u30011\u306b\u9023\u7d50\u3067\u304d\u308b\u96c6\u5408\u306b\u5206\u5272\u3055\u308c\u3066\u3044\u308b\u306f\u305a\n\n // D\u3092\u9054\u6210\u3067\u304d\u308b\u3088\u3046\u306b\u9023\u7d50\u6210\u5206\u3092\u3078\u3089\u3057\u3066\u3044\u304f\n // {2, 3}-{2, 3}\n REP(M) { i =>\n if (set > D + 1 && f(i) != 0 && t(i) != 0) {\n if (!uf.same(f(i), t(i))) {\n ans += Edge(f(i), t(i))\n set -= 1\n }\n }\n }\n\n if (set != D + 1) {\n out.println(\"NO\")\n return\n\n } else {\n // 1-2\n REP(g(0).length) { i =>\n val u = g(0)(i)\n if (set > 1 && !uf.same(0, u)) {\n ans += Edge(0, u)\n set -= 1\n }\n }\n\n if (set != 1) out.println(\"NO\")\n else {\n out.println(\"YES\")\n REP(ans.length) { i =>\n val e = ans(i)\n out.println(s\"${e.v + 1} ${e.u + 1}\")\n }\n }\n }\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 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) // \u96c6\u5408\u306e\u8981\u7d20\u6570\n private val visits = Array.ofDim[Int](n) // \u8a2a\u308c\u305f\u5834\u6240\u3092find\u6bce\u306b\u7528\u610f\u3059\u308b\u306e\u304c\u3082\u3063\u305f\u3044\u306a\u3044\u306e\u3067\u3064\u304b\u3044\u307e\u308f\u3059\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 same(x: Int, y: Int): Boolean = {\n find(x) == find(y)\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\u3092\u89e3\u6c7a\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\u3068\u304d\u306f\u76f4\u306brank\u3092\u307f\u308b\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 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"}], "src_uid": "0cfaaa70b7990e4f170eb397cd8756f8"} {"nl": {"description": "A PIN code is a string that consists of exactly $$$4$$$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.Polycarp has $$$n$$$ ($$$2 \\le n \\le 10$$$) bank cards, the PIN code of the $$$i$$$-th card is $$$p_i$$$.Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $$$n$$$ codes would become different.Formally, in one step, Polycarp picks $$$i$$$-th card ($$$1 \\le i \\le n$$$), then in its PIN code $$$p_i$$$ selects one position (from $$$1$$$ to $$$4$$$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.Polycarp quickly solved this problem. Can you solve it?", "input_spec": "The first line contains integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then test cases follow. The first line of each of $$$t$$$ test sets contains a single integer $$$n$$$ ($$$2 \\le n \\le 10$$$) \u2014 the number of Polycarp's bank cards. The next $$$n$$$ lines contain the PIN codes $$$p_1, p_2, \\dots, p_n$$$ \u2014 one per line. The length of each of them is $$$4$$$. All PIN codes consist of digits only.", "output_spec": "Print the answers to $$$t$$$ test sets. The answer to each set should consist of a $$$n + 1$$$ lines In the first line print $$$k$$$ \u2014 the least number of changes to make all PIN codes different. In the next $$$n$$$ lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them.", "sample_inputs": ["3\n2\n1234\n0600\n2\n1337\n1337\n4\n3139\n3139\n3139\n3139"], "sample_outputs": ["0\n1234\n0600\n1\n1337\n1237\n3\n3139\n3138\n3939\n6139"], "notes": null}, "positive_code": [{"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 val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n val cs = Array.fill(n)(nextLine.toCharArray)\n val available = mutable.Set.empty[Char] ++ ('0' to '9') -- cs.map(_.head)\n val res = ArrayBuffer.empty[String]\n for (i <- 0 until n) {\n val c = cs(i)\n if (cs.count(_.mkString == c.mkString) > 1) {\n c(0) = available.min\n available -= c(0)\n res += c.mkString\n }\n }\n println(res.size)\n println(cs.map(_.mkString).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": [], "src_uid": "1d2ba15a7f2958bb79ccc7b2a2a1545b"} {"nl": {"description": "Alicia has an array, $$$a_1, a_2, \\ldots, a_n$$$, of non-negative integers. For each $$$1 \\leq i \\leq n$$$, she has found a non-negative integer $$$x_i = max(0, a_1, \\ldots, a_{i-1})$$$. Note that for $$$i=1$$$, $$$x_i = 0$$$.For example, if Alicia had the array $$$a = \\{0, 1, 2, 0, 3\\}$$$, then $$$x = \\{0, 0, 1, 2, 2\\}$$$.Then, she calculated an array, $$$b_1, b_2, \\ldots, b_n$$$: $$$b_i = a_i - x_i$$$.For example, if Alicia had the array $$$a = \\{0, 1, 2, 0, 3\\}$$$, $$$b = \\{0-0, 1-0, 2-1, 0-2, 3-2\\} = \\{0, 1, 1, -2, 1\\}$$$.Alicia gives you the values $$$b_1, b_2, \\ldots, b_n$$$ and asks you to restore the values $$$a_1, a_2, \\ldots, a_n$$$. Can you help her solve the problem?", "input_spec": "The first line contains one integer $$$n$$$ ($$$3 \\leq n \\leq 200\\,000$$$)\u00a0\u2013 the number of elements in Alicia's array. The next line contains $$$n$$$ integers, $$$b_1, b_2, \\ldots, b_n$$$ ($$$-10^9 \\leq b_i \\leq 10^9$$$). It is guaranteed that for the given array $$$b$$$ there is a solution $$$a_1, a_2, \\ldots, a_n$$$, for all elements of which the following is true: $$$0 \\leq a_i \\leq 10^9$$$.", "output_spec": "Print $$$n$$$ integers, $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$), such that if you calculate $$$x$$$ according to the statement, $$$b_1$$$ will be equal to $$$a_1 - x_1$$$, $$$b_2$$$ will be equal to $$$a_2 - x_2$$$, ..., and $$$b_n$$$ will be equal to $$$a_n - x_n$$$. It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.", "sample_inputs": ["5\n0 1 1 -2 1", "3\n1000 999999000 -1000000000", "5\n2 1 2 2 3"], "sample_outputs": ["0 1 2 0 3", "1000 1000000000 0", "2 3 5 7 10"], "notes": "NoteThe first test was described in the problem statement.In the second test, if Alicia had an array $$$a = \\{1000, 1000000000, 0\\}$$$, then $$$x = \\{0, 1000, 1000000000\\}$$$ and $$$b = \\{1000-0, 1000000000-1000, 0-1000000000\\} = \\{1000, 999999000, -1000000000\\}$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Santa has $$$n$$$ candies and he wants to gift them to $$$k$$$ kids. He wants to divide as many candies as possible between all $$$k$$$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has $$$a$$$ candies and the kid who recieves the maximum number of candies has $$$b$$$ candies. Then Santa will be satisfied, if the both conditions are met at the same time: $$$b - a \\le 1$$$ (it means $$$b = a$$$ or $$$b = a + 1$$$); the number of kids who has $$$a+1$$$ candies (note that $$$a+1$$$ not necessarily equals $$$b$$$) does not exceed $$$\\lfloor\\frac{k}{2}\\rfloor$$$ (less than or equal to $$$\\lfloor\\frac{k}{2}\\rfloor$$$). $$$\\lfloor\\frac{k}{2}\\rfloor$$$ is $$$k$$$ divided by $$$2$$$ and rounded down to the nearest integer. For example, if $$$k=5$$$ then $$$\\lfloor\\frac{k}{2}\\rfloor=\\lfloor\\frac{5}{2}\\rfloor=2$$$.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 5 \\cdot 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 10^9$$$) \u2014 the number of candies and the number of kids.", "output_spec": "For each test case print the answer on it \u2014 the maximum number of candies Santa can give to kids so that he will be satisfied.", "sample_inputs": ["5\n5 2\n19 4\n12 7\n6 2\n100000 50010"], "sample_outputs": ["5\n18\n10\n6\n75015"], "notes": "NoteIn the first test case, Santa can give $$$3$$$ and $$$2$$$ candies to kids. There $$$a=2, b=3,a+1=3$$$.In the second test case, Santa can give $$$5, 5, 4$$$ and $$$4$$$ candies. There $$$a=4,b=5,a+1=5$$$. The answer cannot be greater because then the number of kids with $$$5$$$ candies will be $$$3$$$.In the third test case, Santa can distribute candies in the following way: $$$[1, 2, 2, 1, 1, 2, 1]$$$. There $$$a=1,b=2,a+1=2$$$. He cannot distribute two remaining candies in a way to be satisfied.In the fourth test case, Santa can distribute candies in the following way: $$$[3, 3]$$$. There $$$a=3, b=3, a+1=4$$$. Santa distributed all $$$6$$$ candies."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink.", "input_spec": "The first input line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0\u2009\u2264\u2009pi\u2009\u2264\u2009100) \u2014 the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.", "output_spec": "Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10\u2009\u2009-\u20094.", "sample_inputs": ["3\n50 50 100", "4\n0 25 50 75"], "sample_outputs": ["66.666666666667", "37.500000000000"], "notes": "NoteNote to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal milliliters. The total cocktail's volume equals 3\u00b7x milliliters, so the volume fraction of the juice in the cocktail equals , that is, 66.(6) percent."}, "positive_code": [{"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"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "580596d05a2eaa36d630d71ef1055c43"} {"nl": {"description": "All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi \u2014 a coordinate on the Ox axis. No two cities are located at a single point.Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.For each city calculate two values \u200b\u200bmini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities in Lineland. The second line contains the sequence of n distinct integers x1,\u2009x2,\u2009...,\u2009xn (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order.", "output_spec": "Print n lines, the i-th line must contain two integers mini,\u2009maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city.", "sample_inputs": ["4\n-5 -2 2 7", "2\n-1 1"], "sample_outputs": ["3 12\n3 9\n4 7\n5 12", "2 2\n2 2"], "notes": null}, "positive_code": [{"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) \u21d2\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 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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given a tree consisting exactly of $$$n$$$ vertices. Tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a value $$$a_v$$$ assigned to it.Let $$$dist(x, y)$$$ be the distance between the vertices $$$x$$$ and $$$y$$$. The distance between the vertices is the number of edges on the simple path between them.Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be $$$v$$$. Then the cost of the tree is $$$\\sum\\limits_{i = 1}^{n} dist(i, v) \\cdot a_i$$$.Your task is to calculate the maximum possible cost of the tree if you can choose $$$v$$$ arbitrarily.", "input_spec": "The first line contains one integer $$$n$$$, the number of vertices in the tree ($$$1 \\le n \\le 2 \\cdot 10^5$$$). The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$), where $$$a_i$$$ is the value of the vertex $$$i$$$. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$). It is guaranteed that the given edges form a tree.", "output_spec": "Print one integer \u2014 the maximum possible cost of the tree if you can choose any vertex as $$$v$$$.", "sample_inputs": ["8\n9 4 1 7 10 1 6 5\n1 2\n2 3\n1 4\n1 5\n5 6\n5 7\n5 8", "1\n1337"], "sample_outputs": ["121", "0"], "notes": "NotePicture corresponding to the first example: You can choose the vertex $$$3$$$ as a root, then the answer will be $$$2 \\cdot 9 + 1 \\cdot 4 + 0 \\cdot 1 + 3 \\cdot 7 + 3 \\cdot 10 + 4 \\cdot 1 + 4 \\cdot 6 + 4 \\cdot 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121$$$.In the second example tree consists only of one vertex so the answer is always $$$0$$$."}, "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 (from, to) = na2(N - 1, -1)\n val t = packUGraph(N, from, to)\n val (_, p, q) = traceBfs(t)\n\n val D = Array.ofDim[Long](N) // \u3053\u306e\u30b5\u30d6\u30c4\u30ea\u30fc\u306e\u8ddd\u96e2\u304b\u3051\u308bAi\u306e\u5408\u8a08\n val S = Array.ofDim[Long](N) // \u3053\u306e\u30b5\u30d6\u30c4\u30ea\u30fc\u306eAi\u306e\u5408\u8a08\n\n REP_r(N) { i =>\n val v = q(i)\n val E = t(v)\n S(v) += A(v)\n REP(E.length) { j =>\n val u = E(j)\n if (p(v) != u) {\n D(v) += D(u) + S(u)\n S(v) += S(u)\n }\n }\n }\n\n val calc = Array.ofDim[Long](N)\n calc(0) = D(0)\n REP(N - 1, 1) { i =>\n val v = q(i)\n val sumA0 = S(0) - S(v)\n val res = calc(p(v)) - S(v) + sumA0\n calc(v) = res\n }\n\n val ans = calc.max\n out.println(ans)\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}"}], "negative_code": [], "src_uid": "0ed34310c59e3946b1c55b2618218120"} {"nl": {"description": "During the quarantine, Sicromoft has more free time to create the new functions in \"Celex-2021\". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: The cell with coordinates $$$(x, y)$$$ is at the intersection of $$$x$$$-th row and $$$y$$$-th column. Upper left cell $$$(1,1)$$$ contains an integer $$$1$$$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $$$(x,y)$$$ in one step you can move to the cell $$$(x+1, y)$$$ or $$$(x, y+1)$$$. After another Dinwows update, Levian started to study \"Celex-2021\" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $$$(x_1, y_1)$$$ to another given cell $$$(x_2, y_2$$$), if you can only move one cell down or right.Formally, consider all the paths from the cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 57179$$$) \u2014 the number of test cases. Each of the following $$$t$$$ lines contains four natural numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \\le x_1 \\le x_2 \\le 10^9$$$, $$$1 \\le y_1 \\le y_2 \\le 10^9$$$) \u2014 coordinates of the start and the end cells. ", "output_spec": "For each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell.", "sample_inputs": ["4\n1 1 2 2\n1 2 2 4\n179 1 179 100000\n5 7 5 7"], "sample_outputs": ["2\n3\n1\n1"], "notes": "NoteIn the first test case there are two possible sums: $$$1+2+5=8$$$ and $$$1+3+5=9$$$. "}, "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"}, {"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"}], "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"} {"nl": {"description": "Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.You are given two matrices $$$A$$$ and $$$B$$$ of size $$$n \\times m$$$, each of which consists of $$$0$$$ and $$$1$$$ only. You can apply the following operation to the matrix $$$A$$$ arbitrary number of times: take any submatrix of the matrix $$$A$$$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $$$0$$$, will be replaced by $$$1$$$, and all corners of the submatrix that contain $$$1$$$, will be replaced by $$$0$$$). You have to answer whether you can obtain the matrix $$$B$$$ from the matrix $$$A$$$. An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question.A submatrix of matrix $$$M$$$ is a matrix which consist of all elements which come from one of the rows with indices $$$x_1, x_1+1, \\ldots, x_2$$$ of matrix $$$M$$$ and one of the columns with indices $$$y_1, y_1+1, \\ldots, y_2$$$ of matrix $$$M$$$, where $$$x_1, x_2, y_1, y_2$$$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$, where the cell $$$(i,j)$$$ denotes the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 500$$$)\u00a0\u2014 the number of rows and the number of columns in matrices $$$A$$$ and $$$B$$$. Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$0 \\leq A_{ij} \\leq 1$$$). Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$0 \\leq B_{ij} \\leq 1$$$). ", "output_spec": "Print \"Yes\" (without quotes) if it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$ using the operations described above, and \"No\" (without quotes), if it is not possible. You can print each letter in any case (upper or lower).", "sample_inputs": ["3 3\n0 1 0\n0 1 0\n1 0 0\n1 0 0\n1 0 0\n1 0 0", "6 7\n0 0 1 1 0 0 1\n0 1 0 0 1 0 1\n0 0 0 1 0 0 1\n1 0 1 0 1 0 0\n0 1 0 0 1 0 1\n0 1 0 1 0 0 1\n1 1 0 1 0 1 1\n0 1 1 0 1 0 0\n1 1 0 1 0 0 1\n1 0 1 0 0 1 0\n0 1 1 0 1 0 0\n0 1 1 1 1 0 1", "3 4\n0 1 0 1\n1 0 1 0\n0 1 0 1\n1 1 1 1\n1 1 1 1\n1 1 1 1"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteThe examples are explained below. Example 1. Example 2. Example 3. "}, "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, M = ni()\n val A, B = nm(N, M)\n val C = Array.ofDim[Boolean](N, M)\n val X = Array.ofDim[Int](N)\n val Y = Array.ofDim[Int](M)\n REP(N) { i =>\n REP(M) { j =>\n C(i)(j) = A(i)(j) != B(i)(j)\n }\n }\n DEBUG{\n REP(N) { i =>\n debug(C(i))\n }\n }\n\n REP(N) { i =>\n REP(M) { j =>\n if (C(i)(j)) {\n X(i) += 1\n Y(j) += 1\n }\n }\n }\n\n debug(X)\n debug(Y)\n val ok = X.forall(_ % 2 == 0) && Y.forall(_ % 2 == 0)\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 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": "068e6bbfe590f4485528e85fa991ff24"} {"nl": {"description": "There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c < h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\\dots$$$ and so on $$$\\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 3 \\cdot 10^4$$$)\u00a0\u2014 the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \\le c < h \\le 10^6$$$; $$$c \\le t \\le h$$$)\u00a0\u2014 the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.", "output_spec": "For each testcase print a single positive integer\u00a0\u2014 the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.", "sample_inputs": ["3\n30 10 20\n41 15 30\n18 13 18"], "sample_outputs": ["2\n7\n1"], "notes": "NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$."}, "positive_code": [{"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 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"}, {"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": "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"} {"nl": {"description": "You have a list of numbers from $$$1$$$ to $$$n$$$ written from left to right on the blackboard.You perform an algorithm consisting of several steps (steps are $$$1$$$-indexed). On the $$$i$$$-th step you wipe the $$$i$$$-th number (considering only remaining numbers). You wipe the whole number (not one digit). When there are less than $$$i$$$ numbers remaining, you stop your algorithm. Now you wonder: what is the value of the $$$x$$$-th remaining number after the algorithm is stopped?", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. The next $$$T$$$ lines contain queries \u2014 one per line. All queries are independent. Each line contains two space-separated integers $$$n$$$ and $$$x$$$ ($$$1 \\le x < n \\le 10^{9}$$$) \u2014 the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least $$$x$$$ numbers.", "output_spec": "Print $$$T$$$ integers (one per query) \u2014 the values of the $$$x$$$-th number after performing the algorithm for the corresponding queries.", "sample_inputs": ["3\n3 1\n4 2\n69 6"], "sample_outputs": ["2\n4\n12"], "notes": null}, "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[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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"} {"nl": {"description": "Little X has n distinct integers: p1,\u2009p2,\u2009...,\u2009pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: If number x belongs to set A, then number a\u2009-\u2009x must also belong to set A. If number x belongs to set B, then number b\u2009-\u2009x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible.", "input_spec": "The first line contains three space-separated integers n,\u2009a,\u2009b (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009109). The next line contains n space-separated distinct integers p1,\u2009p2,\u2009...,\u2009pn\u00a0(1\u2009\u2264\u2009pi\u2009\u2264\u2009109).", "output_spec": "If there is a way to divide the numbers into two sets, then print \"YES\" in the first line. Then print n integers: b1,\u2009b2,\u2009...,\u2009bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print \"NO\" (without the quotes).", "sample_inputs": ["4 5 9\n2 3 4 5", "3 3 4\n1 2 4"], "sample_outputs": ["YES\n0 0 1 1", "NO"], "notes": "NoteIt's OK if all the numbers are in the same set, and the other one is empty."}, "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, a, b) = readInts(3)\n val ps = readInts(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Int, Int]\n val sorted = ps.zipWithIndex.sortBy(_._1)\n\n for ((p, i) <- sorted) {\n if (!assign.contains(p)) {\n val ap = a - p\n val bp = b - p\n if (is(ap) && !assign.contains(ap) && \n !(is(bp) && is(b - ap) && !assign.contains(bp) && !assign.contains(b - ap))) {\n assign.put(p, 0)\n assign.put(ap, 0)\n } else if (is(bp) && !assign.contains(bp)) {\n assign.put(p, 1)\n assign.put(bp, 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).mkString(\" \"))\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, a, b) = readInts(3)\n val ps = readLongs(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Long, Int]\n val order = ps.zipWithIndex.sortBy(_._1)\n\n for ((p, i) <- order) {\n if (!assign.contains(ps(i))) {\n if ((is(a - ps(i)) && assign.getOrElse(a - ps(i), 0) == 0 && ps(i) * 2 != a)\n || (ps(i) * 2 == a && !(is(b - ps(i)) && assign.getOrElse(b - ps(i), 1) == 1))) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && assign.getOrElse(b - ps(i), 1) == 1) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readLongs(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Long, Int]\n\n for (i <- ps.indices) {\n if (!assign.contains(ps(i))) {\n if ((is(a - ps(i)) && !assign.contains(a - ps(i)) && ps(i) * 2 != a)\n || (ps(i) * 2 != a && !(is(b - ps(i)) && !assign.contains(b - ps(i))))) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && !assign.contains(b - ps(i))) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readLongs(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Long, Int]\n val order = ps.zipWithIndex.sortBy(_._1)\n\n for ((p, i) <- order) {\n if (!assign.contains(ps(i))) {\n if ((is(a - ps(i)) && !assign.contains(a - ps(i)) && ps(i) * 2 != a)\n || (ps(i) * 2 == a && !(is(b - ps(i)) && !assign.contains(b - ps(i))))) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && !assign.contains(b - ps(i))) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readLongs(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Long, Int]\n\n for (i <- ps.indices) {\n if (!assign.contains(ps(i))) {\n if ((is(a - ps(i)) && !assign.contains(a - ps(i)) && ps(i) * 2 != a)\n || (ps(i) * 2 == a && !(is(b - ps(i)) && !assign.contains(b - ps(i))))) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && !assign.contains(b - ps(i))) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readInts(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Int, Int]\n\n for (i <- ps.indices) {\n val p = ps(i)\n if (!assign.contains(p)) {\n val ap = a - p\n val bp = b - p\n if (is(ap) && !assign.contains(ap) && \n !(is(bp) && is(b - ap) && !assign.contains(bp) && !assign.contains(b - ap))) {\n assign.put(p, 0)\n assign.put(ap, 0)\n } else if (is(bp) && !assign.contains(bp)) {\n assign.put(p, 1)\n assign.put(bp, 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readInts(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Int, Int]\n\n for (i <- ps.indices) {\n if (!assign.contains(ps(i))) {\n if (is(a - ps(i)) && !assign.contains(a - ps(i))) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && !assign.contains(b - ps(i))) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readInts(n)\n val is = mutable.Set.empty ++ ps\n val assign = mutable.Map.empty[Int, Int]\n\n for (i <- ps.indices) {\n if (!assign.contains(ps(i))) {\n if (is(a - ps(i)) && !assign.contains(a - ps(i))) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && !assign.contains(b - ps(i))) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).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, a, b) = readInts(3)\n val ps = readInts(n)\n val is = mutable.HashSet.empty ++ ps\n val assign = mutable.HashMap.empty[Int, Int]\n\n for (i <- ps.indices) {\n if (!assign.contains(ps(i))) {\n if (is(a - ps(i)) && !assign.contains(a - ps(i)) && ps(i) * 2 != a) {\n assign.put(ps(i), 0)\n assign.put(a - ps(i), 0)\n } else if (is(b - ps(i)) && !assign.contains(b - ps(i)) && ps(i) * 2 != b) {\n assign.put(ps(i), 1)\n assign.put(b - ps(i), 1)\n } else {\n println(\"NO\")\n System.exit(0)\n }\n }\n }\n\n println(\"YES\")\n println(ps.map(assign).mkString(\" \"))\n}"}], "src_uid": "1a46737540d253583234193a026008e3"} {"nl": {"description": "Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds: \"Are you kidding me?\", asks Chris.For example, consider a case where s\u2009=\u20098 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1\u2009-\u20091)\u2009+\u2009(4\u2009-\u20091)\u2009+\u2009(5\u2009-\u20091)\u2009=\u2009(8\u2009-\u20093)\u2009+\u2009(8\u2009-\u20096)\u2009=\u20097. However, now Chris has exactly s\u2009=\u2009106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009106), the numbers of the blocks in X. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.", "output_spec": "In the first line of output print a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009106\u2009-\u2009n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1\u2009\u2264\u2009yi\u2009\u2264\u2009106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi\u2009\u2260\u2009yj for all i, j (1\u2009\u2264\u2009i\u2009\u2264\u2009n; 1\u2009\u2264\u2009j\u2009\u2264\u2009m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.", "sample_inputs": ["3\n1 4 5", "1\n1"], "sample_outputs": ["2\n999993 1000000", "1\n1000000"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "You are given a string $$$s$$$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'. Note that each of the characters '?' is replaced independently from the others.A string $$$t$$$ of length $$$n$$$ is called a palindrome if the equality $$$t[i] = t[n-i+1]$$$ is true for all $$$i$$$ ($$$1 \\le i \\le n$$$).For example, if $$$s=$$$\"01?????0\", $$$a=4$$$ and $$$b=4$$$, then you can replace the characters '?' in the following ways: \"01011010\"; \"01100110\". For the given string $$$s$$$ and the numbers $$$a$$$ and $$$b$$$, replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \\le a, b \\le 2 \\cdot 10^5$$$, $$$a + b \\ge 1$$$). The second line of each test case contains the string $$$s$$$ of length $$$a+b$$$, consisting of the characters '0', '1', and '?'. It is guaranteed that the sum of the string lengths of $$$s$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output: \"-1\", if you can't replace all the characters '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and that it contains exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'; the string that is obtained as a result of the replacement, otherwise. If there are several suitable ways to replace characters, you can output any.", "sample_inputs": ["9\n4 4\n01?????0\n3 3\n??????\n1 0\n?\n2 2\n0101\n2 2\n01?0\n0 1\n0\n0 3\n1?1\n2 2\n?00?\n4 3\n??010?0"], "sample_outputs": ["01011010\n-1\n0\n-1\n0110\n-1\n111\n1001\n0101010"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated: Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting). When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of employees. The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.", "output_spec": "Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.", "sample_inputs": ["5\nDDRRR", "6\nDDRRRR"], "sample_outputs": ["D", "R"], "notes": "NoteConsider one of the voting scenarios for the first sample: Employee 1 denies employee 5 to vote. Employee 2 denies employee 3 to vote. Employee 3 has no right to vote and skips his turn (he was denied by employee 2). Employee 4 denies employee 2 to vote. Employee 5 has no right to vote and skips his turn (he was denied by employee 1). Employee 1 denies employee 4. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. "}, "positive_code": [{"source_code": "import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._\n\nobject _749C extends CodeForcesApp {\n override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}\n val n = read[Int]\n val prefs = read[String].toVector\n\n def init(c: Char) = mutable.Queue(prefs.indicesWhere(_ == c) : _*)\n\n val remocrats = init('R')\n val depublicans = init('D')\n\n @tailrec\n def solve(): Char = {\n if (remocrats.isEmpty) {\n 'D'\n } else if (depublicans.isEmpty) {\n 'R'\n } else {\n val r = remocrats.dequeue()\n val d = depublicans.dequeue()\n if (r < d) remocrats.enqueue(r + n) else depublicans.enqueue(d + n)\n solve()\n }\n }\n\n write(solve())\n }\n}\n/****************************[Ignore Template Below]****************************************/\ntrait CodeForcesApp {\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": "cc50eef15726d429cfc2e76f0aa8cd19"} {"nl": {"description": "One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the \"Goldbach's conjecture\". It says: \"each even number no less than four can be expressed as the sum of two primes\". Let's modify it. How about a statement like that: \"each integer no less than 12 can be expressed as the sum of two composite numbers.\" Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.", "input_spec": "The only line contains an integer n (12\u2009\u2264\u2009n\u2009\u2264\u2009106).", "output_spec": "Output two composite integers x and y (1\u2009<\u2009x,\u2009y\u2009<\u2009n) such that x\u2009+\u2009y\u2009=\u2009n. If there are multiple solutions, you can output any of them.", "sample_inputs": ["12", "15", "23", "1000000"], "sample_outputs": ["4 8", "6 9", "8 15", "500000 500000"], "notes": "NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output \"6 6\" or \"8 4\" as well.In the second example, 15 = 6 + 9. Note that you can't output \"1 14\" because 1 is not a composite number."}, "positive_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 <- 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": "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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Luntik has decided to try singing. He has $$$a$$$ one-minute songs, $$$b$$$ two-minute songs and $$$c$$$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Each test case consists of one line containing three integers $$$a, b, c$$$ $$$(1 \\le a, b, c \\le 10^9)$$$\u00a0\u2014 the number of one-minute, two-minute and three-minute songs.", "output_spec": "For each test case print the minimal possible difference in minutes between the concerts durations.", "sample_inputs": ["4\n1 1 1\n2 1 3\n5 5 5\n1 1 2"], "sample_outputs": ["0\n1\n0\n1"], "notes": "NoteIn the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to $$$0$$$.In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be $$$1 + 1 + 2 + 3 = 7$$$, the duration of the second concert will be $$$6$$$. The difference of them is $$$|7-6| = 1$$$."}, "positive_code": [{"source_code": "object A extends App {\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 = nextInt()\r\n val b = nextInt()\r\n val c = nextInt()\r\n\r\n val d =\r\n if (a == b && b == c) 0\r\n else {\r\n val f = a + 2 * b + 3 * c\r\n val h = f / 2\r\n (f - 2 * h).abs\r\n }\r\n\r\n out.println(d)\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 A extends App {\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 = nextInt()\r\n val b = nextInt()\r\n val c = nextInt()\r\n\r\n val d = ((3 * (c % 2) - 2 * (b % 2)).abs - (a % 2)).abs\r\n\r\n out.println(d)\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": "4322861935ca727b0de8556849bc5982"} {"nl": {"description": "Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct English letters to all nucleotides, then the genome of a Berland dinosaur will represent a non-empty string consisting of small English letters, such that each letter occurs in it at most once.Scientists have n genome fragments that are represented as substrings (non-empty sequences of consecutive nucleotides) of the sought genome.You face the following problem: help scientists restore the dinosaur genome. It is guaranteed that the input is not contradictory and at least one suitable line always exists. When the scientists found out that you are a strong programmer, they asked you in addition to choose the one with the minimum length. If there are multiple such strings, choose any string.", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of genome fragments. Each of the next lines contains one descriptions of a fragment. Each fragment is a non-empty string consisting of distinct small letters of the English alphabet. It is not guaranteed that the given fragments are distinct. Fragments could arbitrarily overlap and one fragment could be a substring of another one. It is guaranteed that there is such string of distinct letters that contains all the given fragments as substrings.", "output_spec": "In the single line of the output print the genome of the minimum length that contains all the given parts. All the nucleotides in the genome must be distinct. If there are multiple suitable strings, print the string of the minimum length. If there also are multiple suitable strings, you can print any of them.", "sample_inputs": ["3\nbcd\nab\ncdef", "4\nx\ny\nz\nw"], "sample_outputs": ["abcdef", "xyzw"], "notes": null}, "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())\n val first = data.map(_.head).toSet\n val filtered = first.filter(ch => !data.map(_.tail).exists(_.contains(ch)))\n val soFar = filtered.map(ch => data.filter(_.head == ch).maxBy(_.length))\n val left = data.filter(i => !filtered.contains(i.head))\n\n def increase(s: String, left: Seq[String]): String = {\n left.find(str => s.contains(str.head)) match {\n case None => s\n case Some(str) if s.contains(str) =>\n increase(s, left.filter(_ != str))\n case Some(str) =>\n increase(s.takeWhile(_ != str.head) + str, left.filter(_ != str))\n }\n }\n\n println(soFar.map(i => increase(i, left)).mkString)\n}"}], "negative_code": [{"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n def join(str1: String, str2: String, ch: Char) =\n if (str1.isEmpty || str2.contains(str1))\n str2\n else if (str1.contains(str2))\n str1\n else if (!str1.contains(ch)) {\n str1 + str2\n }\n else {\n val index1 = str1.indexOf(ch)\n val index2 = str2.indexOf(ch)\n if (index2 > index1)\n str2.take(index2) + str1.drop(index1)\n else\n str1.take(index1) + str2.drop(index2)\n }\n\n\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next())\n println(('a' to 'z').foldLeft(\"\") {\n case(acc, ch) => data.filter(_.contains(ch)).foldLeft(acc) {\n case (acc, line) => join(acc, line, ch)\n }\n })\n}"}, {"source_code": "object Solution extends App {\n val in = scala.io.Source.stdin.getLines()\n\n def join(str1: String, str2: String, ch: Char) =\n if (str1.isEmpty || str2.contains(str1))\n str2\n else if (str1.contains(str2))\n str1\n else if (!str1.contains(ch)) {\n str1 + str2\n }\n else {\n val index1 = str1.indexOf(ch)\n val index2 = str2.indexOf(ch)\n if (index2 > index1)\n str2.take(index2) + str1.drop(index1)\n else\n str1.take(index1) + str2.drop(index2)\n }\n val visited = Array.ofDim[Boolean](26)\n val canVisit = Array.ofDim[Boolean](26)\n\n\n val n = in.next().toInt\n val data = (1 to n).map(_ => in.next())\n data.head.foreach{\n ch => canVisit(ch - 'a') = true\n }\n\n println((1 to 26).foldLeft(data.head) {\n case (acc, _) =>\n val ch =\n (0 until 26).find(canVisit).map(i => (i + 'a').toChar).getOrElse {\n val index = (0 until 26).find(i => !visited(i)).get\n (index + 'a').toChar\n }\n visited(ch - 'a') = true\n canVisit(ch - 'a') = false\n val res = data.filter(_.contains(ch)).foldLeft(acc) {\n case (acc, line) => join(acc, line, ch)\n }\n res.foreach {\n ch => if (!visited(ch - 'a')) canVisit(ch - 'a') = true\n }\n res\n })\n}"}], "src_uid": "a6e112135272a81ae9563ae4c50b6d86"} {"nl": {"description": "You have $$$n$$$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $$$i$$$-th gift consists of $$$a_i$$$ candies and $$$b_i$$$ oranges.During one move, you can choose some gift $$$1 \\le i \\le n$$$ and do one of the following operations: eat exactly one candy from this gift (decrease $$$a_i$$$ by one); eat exactly one orange from this gift (decrease $$$b_i$$$ by one); eat exactly one candy and exactly one orange from this gift (decrease both $$$a_i$$$ and $$$b_i$$$ by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither $$$a_i$$$ nor $$$b_i$$$ can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $$$a_1 = a_2 = \\dots = a_n$$$ and $$$b_1 = b_2 = \\dots = b_n$$$ (and $$$a_i$$$ equals $$$b_i$$$ is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of gifts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the number of candies in the $$$i$$$-th gift. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 10^9$$$), where $$$b_i$$$ is the number of oranges in the $$$i$$$-th gift.", "output_spec": "For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.", "sample_inputs": ["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"], "sample_outputs": ["6\n16\n0\n4999999995\n7"], "notes": "NoteIn the first test case of the example, we can perform the following sequence of moves: choose the first gift and eat one orange from it, so $$$a = [3, 5, 6]$$$ and $$$b = [2, 2, 3]$$$; choose the second gift and eat one candy from it, so $$$a = [3, 4, 6]$$$ and $$$b = [2, 2, 3]$$$; choose the second gift and eat one candy from it, so $$$a = [3, 3, 6]$$$ and $$$b = [2, 2, 3]$$$; choose the third gift and eat one candy and one orange from it, so $$$a = [3, 3, 5]$$$ and $$$b = [2, 2, 2]$$$; choose the third gift and eat one candy from it, so $$$a = [3, 3, 4]$$$ and $$$b = [2, 2, 2]$$$; choose the third gift and eat one candy from it, so $$$a = [3, 3, 3]$$$ and $$$b = [2, 2, 2]$$$. "}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "35368cefc5ce46a9f41a15734826a151"} {"nl": {"description": "You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word \"mamma\" can be divided into syllables as \"ma\" and \"mma\", \"mam\" and \"ma\", and \"mamm\" and \"a\". Words that consist of only consonants should be ignored.The verse patterns for the given text is a sequence of n integers p1,\u2009p2,\u2009...,\u2009pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of lines in the text. The second line contains integers p1,\u2009...,\u2009pn (0\u2009\u2264\u2009pi\u2009\u2264\u2009100)\u00a0\u2014 the verse pattern. Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.", "output_spec": "If the given text matches the given verse pattern, then print \"YES\" (without quotes) in the only line of the output. Otherwise, print \"NO\" (without quotes).", "sample_inputs": ["3\n2 2 3\nintel\ncode\nch allenge", "4\n1 2 3 1\na\nbcdefghi\njklmnopqrstu\nvwxyz", "4\n13 11 15 15\nto be or not to be that is the question\nwhether tis nobler in the mind to suffer\nthe slings and arrows of outrageous fortune\nor to take arms against a sea of troubles"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first sample, one can split words into syllables in the following way: in-telco-dech al-len-geSince the word \"ch\" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one."}, "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": "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"}, {"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"} {"nl": {"description": "Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.Suppose Ciel and Jiro play optimally, what is the score of the game?", "input_spec": "The first line contain an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1\u2009\u2264\u2009si\u2009\u2264\u2009100) \u2014 the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1\u2009\u2264\u2009ck\u2009\u2264\u20091000) \u2014 the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.", "output_spec": "Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.", "sample_inputs": ["2\n1 100\n2 1 10", "1\n9 2 8 6 5 9 4 7 1 3", "3\n3 1 3 2\n3 5 4 6\n2 8 7", "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000"], "sample_outputs": ["101 10", "30 15", "18 18", "7000 7000"], "notes": "NoteIn the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3."}, "positive_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 C extends App {\n\n def tokenizeLine = new java.util.StringTokenizer(readLine)\n\n val n = readInt\n val cs = Array.ofDim[Array[Int]](n)\n val ws = Array.fill(n)(BigInt(0))\n var sum = 0L\n val C = BigInt(1001)\n\n for (i <- 0 until n) {\n val t = tokenizeLine\n val s = t.nextToken.toInt\n cs(i) = Array.fill(s)(t.nextToken.toInt)\n sum += cs(i).sum\n var mul = BigInt(1)\n for (j <- 0 until (s + 1) / 2) {\n ws(i) += mul * cs(i)(j)\n mul *= C\n }\n ws(i) *= C.pow(50 - s / 2)\n }\n\n val wis = (ws zipWithIndex).sortBy(- _._1)\n//println(wis.mkString(\" \")) \n var sumA = 0L\n var pos = 1\n for (wi <- wis) {\n wi match {\n case (w, i) => sumA += cs(i).take((cs(i).size + (pos % 2)) / 2).sum\n }\n pos += 1\n }\n val sumB = sum - sumA\n println(s\"$sumA $sumB\")\n}"}], "negative_code": [], "src_uid": "21672f2906f4f821611ab1b6dfc7f081"} {"nl": {"description": "Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \\left\\lfloor\\frac{w_i}{2}\\right\\rfloor$$$).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\\sum\\limits_{v \\in leaves} w(root, v) \\le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \\le n \\le 10^5; 1 \\le S \\le 10^{16}$$$) \u2014 the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as three integers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \\le v_i, u_i \\le n; 1 \\le w_i \\le 10^6$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects and $$$w_i$$$ is the weight of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\\sum n \\le 10^5$$$).", "output_spec": "For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$.", "sample_inputs": ["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"], "sample_outputs": ["0\n8\n3"], "notes": null}, "positive_code": [{"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": "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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Let $$$s(x)$$$ be sum of digits in decimal representation of positive integer $$$x$$$. Given two integers $$$n$$$ and $$$m$$$, find some positive integers $$$a$$$ and $$$b$$$ such that $$$s(a) \\ge n$$$, $$$s(b) \\ge n$$$, $$$s(a + b) \\le m$$$. ", "input_spec": "The only line of input contain two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1129$$$).", "output_spec": "Print two lines, one for decimal representation of $$$a$$$ and one for decimal representation of $$$b$$$. Both numbers must not contain leading zeros and must have length no more than $$$2230$$$.", "sample_inputs": ["6 5", "8 16"], "sample_outputs": ["6 \n7", "35 \n53"], "notes": "NoteIn the first sample, we have $$$n = 6$$$ and $$$m = 5$$$. One valid solution is $$$a = 6$$$, $$$b = 7$$$. Indeed, we have $$$s(a) = 6 \\ge n$$$ and $$$s(b) = 7 \\ge n$$$, and also $$$s(a + b) = s(13) = 4 \\le m$$$."}, "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\n rep(800) { i =>\n out.print(i % 8 + 1)\n }\n out.println()\n\n rep_r(800) { i =>\n if (i == 0) out.print(2)\n else out.print(i % 8 + 1)\n }\n out.println()\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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": "bba30bd91f085471f624c0f723b78a82"} {"nl": {"description": "You are given two binary strings $$$x$$$ and $$$y$$$, which are binary representations of some two integers (let's denote these integers as $$$f(x)$$$ and $$$f(y)$$$). You can choose any integer $$$k \\ge 0$$$, calculate the expression $$$s_k = f(x) + f(y) \\cdot 2^k$$$ and write the binary representation of $$$s_k$$$ in reverse order (let's denote it as $$$rev_k$$$). For example, let $$$x = 1010$$$ and $$$y = 11$$$; you've chosen $$$k = 1$$$ and, since $$$2^1 = 10_2$$$, so $$$s_k = 1010_2 + 11_2 \\cdot 10_2 = 10000_2$$$ and $$$rev_k = 00001$$$.For given $$$x$$$ and $$$y$$$, you need to choose such $$$k$$$ that $$$rev_k$$$ is lexicographically minimal (read notes if you don't know what does \"lexicographically\" means).It's guaranteed that, with given constraints, $$$k$$$ exists and is finite.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. Next $$$2T$$$ lines contain a description of queries: two lines per query. The first line contains one binary string $$$x$$$, consisting of no more than $$$10^5$$$ characters. Each character is either 0 or 1. The second line contains one binary string $$$y$$$, consisting of no more than $$$10^5$$$ characters. Each character is either 0 or 1. It's guaranteed, that $$$1 \\le f(y) \\le f(x)$$$ (where $$$f(x)$$$ is the integer represented by $$$x$$$, and $$$f(y)$$$ is the integer represented by $$$y$$$), both representations don't have any leading zeroes, the total length of $$$x$$$ over all queries doesn't exceed $$$10^5$$$, and the total length of $$$y$$$ over all queries doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$T$$$ integers (one per query). For each query print such $$$k$$$ that $$$rev_k$$$ is lexicographically minimal.", "sample_inputs": ["4\n1010\n11\n10001\n110\n1\n1\n1010101010101\n11110000"], "sample_outputs": ["1\n3\n0\n0"], "notes": "NoteThe first query was described in the legend.In the second query, it's optimal to choose $$$k = 3$$$. The $$$2^3 = 1000_2$$$ so $$$s_3 = 10001_2 + 110_2 \\cdot 1000_2 = 10001 + 110000 = 1000001$$$ and $$$rev_3 = 1000001$$$. For example, if $$$k = 0$$$, then $$$s_0 = 10111$$$ and $$$rev_0 = 11101$$$, but $$$rev_3 = 1000001$$$ is lexicographically smaller than $$$rev_0 = 11101$$$.In the third query $$$s_0 = 10$$$ and $$$rev_0 = 01$$$. For example, $$$s_2 = 101$$$ and $$$rev_2 = 101$$$. And $$$01$$$ is lexicographically smaller than $$$101$$$.The quote from Wikipedia: \"To determine which of two strings of characters comes when arranging in lexicographical order, their first letters are compared. If they differ, then the string whose first letter comes earlier in the alphabet comes before the other string. If the first letters are the same, then the second letters are compared, and so on. If a position is reached where one string has no more letters to compare while the other does, then the first (shorter) string is deemed to come first in alphabetical order.\""}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n val X, Y = ns().reverse\n val j = Y.indexWhere(_ == '1')\n val i = X.indexWhere(_ == '1', j)\n out.println(i - j)\n }\n }\n}"}], "negative_code": [], "src_uid": "a20af745cf610eaa8116574805340591"} {"nl": {"description": "Kolya is going to make fresh orange juice. He has n oranges of sizes a1,\u2009a2,\u2009...,\u2009an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?", "input_spec": "The first line of the input contains three integers n, b and d (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009b\u2009\u2264\u2009d\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the number of oranges, the maximum size of the orange that fits in the juicer and the value d, which determines the condition when the waste section should be emptied. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.", "output_spec": "Print one integer\u00a0\u2014 the number of times Kolya will have to empty the waste section.", "sample_inputs": ["2 7 10\n5 6", "1 5 10\n7", "3 10 10\n5 7 7", "1 1 1\n1"], "sample_outputs": ["1", "0", "1", "0"], "notes": "NoteIn the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all."}, "positive_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).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}"}, {"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"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$m$$$ ($$$m < n$$$). Consider a convex regular polygon of $$$n$$$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with $$$m$$$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given as two space-separated integers $$$n$$$ and $$$m$$$ ($$$3 \\le m < n \\le 100$$$) \u2014 the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.", "output_spec": "For each test case, print the answer \u2014 \"YES\" (without quotes), if it is possible to build another convex regular polygon with $$$m$$$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and \"NO\" otherwise.", "sample_inputs": ["2\n6 3\n7 3"], "sample_outputs": ["YES\nNO"], "notes": "Note The first test case of the example It can be shown that the answer for the second test case of the example is \"NO\"."}, "positive_code": [{"source_code": "object _1312A 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 io.write((n % m == 0).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"}], "negative_code": [], "src_uid": "6b37fc623110e49a5e311a2d186aae46"} {"nl": {"description": "Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras. Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let's call the number of selected pieces the length of the zebra.Before assembling the zebra Grisha can make the following operation $$$0$$$ or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order \"bwbbw\" (here 'b' denotes a black strip, and 'w' denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain \"wbwbb\".Determine the maximum possible length of the zebra that Grisha can produce.", "input_spec": "The only line contains a string $$$s$$$ ($$$1 \\le |s| \\le 10^5$$$, where $$$|s|$$$ denotes the length of the string $$$s$$$) comprised of lowercase English letters 'b' and 'w' only, where 'w' denotes a white piece and 'b' denotes a black piece.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible zebra length.", "sample_inputs": ["bwwwbwwbw", "bwwbwwb"], "sample_outputs": ["5", "3"], "notes": "NoteIn the first example one of the possible sequence of operations is bwwwbww|bw $$$\\to$$$ w|wbwwwbwb $$$\\to$$$ wbwbwwwbw, that gives the answer equal to $$$5$$$.In the second example no operation can increase the answer."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Mikhail walks on a Cartesian plane. He starts at the point $$$(0, 0)$$$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $$$(0, 0)$$$, he can go to any of the following points in one move: $$$(1, 0)$$$; $$$(1, 1)$$$; $$$(0, 1)$$$; $$$(-1, 1)$$$; $$$(-1, 0)$$$; $$$(-1, -1)$$$; $$$(0, -1)$$$; $$$(1, -1)$$$. If Mikhail goes from the point $$$(x1, y1)$$$ to the point $$$(x2, y2)$$$ in one move, and $$$x1 \\ne x2$$$ and $$$y1 \\ne y2$$$, then such a move is called a diagonal move.Mikhail has $$$q$$$ queries. For the $$$i$$$-th query Mikhail's target is to go to the point $$$(n_i, m_i)$$$ from the point $$$(0, 0)$$$ in exactly $$$k_i$$$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $$$(0, 0)$$$ to the point $$$(n_i, m_i)$$$ in $$$k_i$$$ moves.Note that Mikhail can visit any point any number of times (even the destination point!).", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) \u2014 the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th of these $$$q$$$ lines contains three integers $$$n_i$$$, $$$m_i$$$ and $$$k_i$$$ ($$$1 \\le n_i, m_i, k_i \\le 10^{18}$$$) \u2014 $$$x$$$-coordinate of the destination point of the query, $$$y$$$-coordinate of the destination point of the query and the number of moves in the query, correspondingly.", "output_spec": "Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to -1 if Mikhail cannot go from the point $$$(0, 0)$$$ to the point $$$(n_i, m_i)$$$ in exactly $$$k_i$$$ moves described above. Otherwise the $$$i$$$-th integer should be equal to the the maximum number of diagonal moves among all possible movements.", "sample_inputs": ["3\n2 2 3\n4 3 7\n10 1 9"], "sample_outputs": ["1\n6\n-1"], "notes": "NoteOne of the possible answers to the first test case: $$$(0, 0) \\to (1, 0) \\to (1, 1) \\to (2, 2)$$$.One of the possible answers to the second test case: $$$(0, 0) \\to (0, 1) \\to (1, 2) \\to (0, 3) \\to (1, 4) \\to (2, 3) \\to (3, 2) \\to (4, 3)$$$.In the third test case Mikhail cannot reach the point $$$(10, 1)$$$ in 9 moves."}, "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, 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}"}, {"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"} {"nl": {"description": "You are given one integer number $$$n$$$. Find three distinct integers $$$a, b, c$$$ such that $$$2 \\le a, b, c$$$ and $$$a \\cdot b \\cdot c = n$$$ or say that it is impossible to do it.If there are several answers, you can print any.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$n$$$ lines describe test cases. The $$$i$$$-th test case is given on a new line as one integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$).", "output_spec": "For each test case, print the answer on it. Print \"NO\" if it is impossible to represent $$$n$$$ as $$$a \\cdot b \\cdot c$$$ for some distinct integers $$$a, b, c$$$ such that $$$2 \\le a, b, c$$$. Otherwise, print \"YES\" and any possible such representation.", "sample_inputs": ["5\n64\n32\n97\n2\n12345"], "sample_outputs": ["YES\n2 4 8 \nNO\nNO\nNO\nYES\n3 5 823"], "notes": null}, "positive_code": [{"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val t = stdin.next().toInt\n println(stdin.take(t).map(_.toInt).flatMap(calc).mkString(\"\\n\"))\n\n def calc(x : Int): List[String] = {\n val res = split(x)\n res.size match {\n // 1\n // 1 1\n // 1 1 1\n case 1 if res.head._2 >= 6 =>\n val lh1 = res.head._1\n val nums = List(lh1, lh1 * lh1, x / (lh1 * lh1 * lh1))\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums}\")\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 && res.head._2 > 1 && res.last._2 > 1=>\n val lh1 = res.head._1\n val lh2 = res.last._1\n val nums = List(lh1, lh2, Math.pow(res.head._1, res.head._2 - 1).toInt * Math.pow(res.last._1, res.last._2 - 1).toInt)\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums}\")\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 =>\n val List(a, b) = res.toList.sortBy(_._2)\n val nums = List(a._1, b._1, Math.pow(b._1, b._2 - 1).toInt)\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums} ; ($a, $b)\")\n List(\"YES\", nums.mkString(\" \"))\n case z if z >= 3 =>\n val first = Math.pow(res.head._1, res.head._2).toInt\n val second = Math.pow(res.tail.head._1, res.tail.head._2).toInt\n val nums = List(Math.pow(res.head._1, res.head._2).toInt,\n Math.pow(res.tail.head._1, res.tail.head._2).toInt,\n x / (first * second))\n List(\"YES\", nums.mkString(\" \"))\n case _ => List(\"NO\")\n }\n }\n\n def split(x: Int): Map[Int, Int] = {\n val m = Map.empty[Int, Int]\n split(x, m)\n }\n\n def split(x: Int, m: Map[Int, Int]): Map[Int, Int] = {\n// println(x)\n if (x == 1) m\n else {\n val f = Stream.from(2).takeWhile(y => y * y <= x).find(x % _ == 0).getOrElse(x)\n// println(\"f = \" + x)\n split(x / f, m + (f -> (m.getOrElse(f, 0) + 1)))\n }\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "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.take(t).map(_.toInt).flatMap(calc).mkString(\"\\n\"))\n\n def calc(x : Int): List[String] = {\n val res = split(x)\n res.size match {\n // 1\n // 1 1\n // 1 1 1\n case 1 if res.head._2 >= 6 =>\n val lh1 = res.head._1\n val nums = List(lh1, lh1 * lh1, x / (lh1 * lh1 * lh1))\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums}\")\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 && res.head._2 > 1 && res.last._2 > 1=>\n val lh1 = res.head._1\n val lh2 = res.last._1\n val nums = List(lh1, lh2, Math.pow(res.head._1, res.head._2 - 1).toInt * Math.pow(res.last._1, res.last._2 - 1).toInt)\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums}\")\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 =>\n val List(a, b) = res.toList.sortBy(_._2)\n val nums = List(a._1, b._1, Math.pow(b._1, b._2 - 1).toInt)\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums} ; ($a, $b)\")\n List(\"YES\", nums.mkString(\" \"))\n case z if z > 3 =>\n val first = Math.pow(res.head._1, res.head._2).toInt\n val second = Math.pow(res.tail.head._1, res.tail.head._2).toInt\n val nums = List(Math.pow(res.head._1, res.head._2).toInt,\n Math.pow(res.tail.head._1, res.tail.head._2).toInt,\n x / (first * second))\n List(\"YES\", nums.mkString(\" \"))\n case _ => List(\"NO\")\n }\n }\n\n def split(x: Int): Map[Int, Int] = {\n val m = Map.empty[Int, Int]\n split(x, m)\n }\n\n def split(x: Int, m: Map[Int, Int]): Map[Int, Int] = {\n// println(x)\n if (x == 1) m\n else {\n val f = Stream.from(2).takeWhile(y => y * y <= x).find(x % _ == 0).getOrElse(x)\n// println(\"f = \" + x)\n split(x / f, m + (f -> (m.getOrElse(f, 0) + 1)))\n }\n }\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.take(t).map(_.toInt).map(calc).flatten.mkString(\"\\n\"))\n\n def calc(x : Int): List[String] = {\n val res = split(x)\n res.size match {\n // 1\n // 1 1\n // 1 1 1\n case 1 if res.head._2 >= 6 =>\n val lh1 = res.head._1\n val nums = List(lh1, lh1 * lh1, x / (lh1 * lh1 * lh1))\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums}\")\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 && res.head._2 > 1 && res.last._2 > 1=>\n val lh1 = res.head._1\n val lh2 = res.last._1\n val nums = List(lh1, lh2, Math.pow(res.head._1, res.head._2 - 1).toInt * Math.pow(res.last._1, res.last._2 - 1).toInt)\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums}\")\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 =>\n val List(a, b) = res.toList.sortBy(_._2)\n val nums = List(a._1, b._1, Math.pow(b._1, b._2 - 1).toInt)\n if (nums.contains(1))\n throw new Exception(s\"x = ${x} ; nums = ${nums} ; ($a, $b)\")\n List(\"YES\", nums.mkString(\" \"))\n case 3 =>\n val nums = List(Math.pow(res.head._1, res.head._2).toInt,\n Math.pow(res.tail.head._1, res.tail.head._2).toInt,\n Math.pow(res.last._1, res.last._2).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case _ => List(\"NO\")\n }\n }\n\n def split(x: Int): Map[Int, Int] = {\n val m = Map.empty[Int, Int]\n split(x, m)\n }\n\n def split(x: Int, m: Map[Int, Int]): Map[Int, Int] = {\n// println(x)\n if (x == 1) m\n else {\n val f = Stream.from(2).takeWhile(y => y * y <= x).find(x % _ == 0).getOrElse(x)\n// println(\"f = \" + x)\n split(x / f, m + (f -> (m.getOrElse(f, 0) + 1)))\n }\n }\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.take(t).map(_.toInt).map(calc).flatten.mkString(\"\\n\"))\n\n def calc(x : Int): List[String] = {\n val res = split(x)\n res.size match {\n // 1\n // 1 1\n // 1 1 1\n case 1 if res.head._2 >= 6 =>\n val lh1 = res.head._1\n val nums = List(lh1, lh1 * lh1, x / (lh1 * lh1 * lh1))\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 && res.head._2 > 1 && res.last._2 > 1=>\n val lh1 = res.head._1\n val lh2 = res.last._1\n val nums = List(lh1, lh2, Math.pow(res.head._1, res.head._2 - 1).toInt * Math.pow(res.last._1, res.last._2 - 1).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 =>\n val List(a, b) = res.toList.sorted\n val nums = List(a, b._1, Math.pow(b._1, b._2 - 1).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case 3 =>\n val nums = List(Math.pow(res.head._1, res.head._2).toInt,\n Math.pow(res.tail.head._1, res.tail.head._2).toInt,\n Math.pow(res.last._1, res.last._2).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case _ => List(\"NO\")\n }\n }\n\n def split(x: Int): Map[Int, Int] = {\n val m = Map.empty[Int, Int]\n split(x, m)\n }\n\n def split(x: Int, m: Map[Int, Int]): Map[Int, Int] = {\n// println(x)\n if (x == 1) m\n else {\n val f = Stream.from(2).takeWhile(y => y * y <= x).find(x % _ == 0).getOrElse(x)\n// println(\"f = \" + x)\n split(x / f, m + (f -> (m.getOrElse(f, 0) + 1)))\n }\n }\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.take(t).map(_.toInt).map(calc).flatten.mkString(\"\\n\"))\n\n def calc(x : Int): List[String] = {\n val res = split(x)\n res.size match {\n // 1\n // 1 1\n // 1 1 1\n case 1 if res.head._2 >= 6 =>\n val lh1 = res.head._1\n val nums = List(lh1, lh1 * lh1, x / (lh1 * lh1 * lh1))\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 && res.head._2 > 1 && res.last._2 > 1=>\n val lh1 = res.head._1\n val lh2 = res.last._1\n val nums = List(lh1, lh2, Math.pow(res.head._1, res.head._2 - 1).toInt * Math.pow(res.last._1, res.last._2 - 1).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case 2 if res.head._2 + res.last._2 >= 4 =>\n val List(a, b) = res.toList.sorted\n val nums = List(a._1, b._1, Math.pow(b._1, b._2 - 1).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case 3 =>\n val nums = List(Math.pow(res.head._1, res.head._2).toInt,\n Math.pow(res.tail.head._1, res.tail.head._2).toInt,\n Math.pow(res.last._1, res.last._2).toInt)\n List(\"YES\", nums.mkString(\" \"))\n case _ => List(\"NO\")\n }\n }\n\n def split(x: Int): Map[Int, Int] = {\n val m = Map.empty[Int, Int]\n split(x, m)\n }\n\n def split(x: Int, m: Map[Int, Int]): Map[Int, Int] = {\n// println(x)\n if (x == 1) m\n else {\n val f = Stream.from(2).takeWhile(y => y * y <= x).find(x % _ == 0).getOrElse(x)\n// println(\"f = \" + x)\n split(x / f, m + (f -> (m.getOrElse(f, 0) + 1)))\n }\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "src_uid": "0f7ceecdffe11f45d0c1d618ef3c6469"} {"nl": {"description": "PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?", "input_spec": "The first input line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103)\u00a0\u2014 number of words PolandBall and EnemyBall know, respectively. Then n strings follow, one per line\u00a0\u2014 words familiar to PolandBall. Then m strings follow, one per line\u00a0\u2014 words familiar to EnemyBall. Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players. Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.", "output_spec": "In a single line of print the answer\u00a0\u2014 \"YES\" if PolandBall wins and \"NO\" otherwise. Both Balls play optimally.", "sample_inputs": ["5 1\npolandball\nis\na\ncool\ncharacter\nnope", "2 2\nkremowka\nwadowicka\nkremowka\nwiedenska", "1 2\na\na\nb"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first example PolandBall knows much more words and wins effortlessly.In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins."}, "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 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}"}, {"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"} {"nl": {"description": "On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $$$k$$$ ($$$k \\ge 3$$$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.Mountains are described by a sequence of heights $$$a_1, a_2, \\dots, a_n$$$ in order from left to right ($$$k \\le n$$$). It is guaranteed that neighboring heights are not equal to each other (that is, $$$a_i \\ne a_{i+1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$).Peaks of mountains on the segment $$$[l,r]$$$ (from $$$l$$$ to $$$r$$$) are called indexes $$$i$$$ such that $$$l < i < r$$$, $$$a_{i - 1} < a_i$$$ and $$$a_i > a_{i + 1}$$$. It is worth noting that the boundary indexes $$$l$$$ and $$$r$$$ for the segment are not peaks. For example, if $$$n=8$$$ and $$$a=[3,1,4,1,5,9,2,6]$$$, then the segment $$$[1,8]$$$ has only two peaks (with indexes $$$3$$$ and $$$6$$$), and there are no peaks on the segment $$$[3, 6]$$$.To break the door, Nastya throws it to a segment $$$[l,l+k-1]$$$ of consecutive mountains of length $$$k$$$ ($$$1 \\le l \\le n-k+1$$$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $$$p+1$$$, where $$$p$$$ is the number of peaks on the segment $$$[l,l+k-1]$$$.Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $$$[l, l+k-1]$$$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $$$l$$$ is minimal.Formally, you need to choose a segment of mountains $$$[l, l+k-1]$$$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $$$l$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u00a0\u2014 the number of test cases. Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \\leq k \\leq n \\leq 2 \\cdot 10^5$$$) \u00a0\u2014 the number of mountains and the length of the door. The second line of the input data set contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\leq a_i \\leq 10 ^ 9$$$, $$$a_i \\neq a_{i + 1}$$$) \u00a0\u2014 the heights of mountains. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output two integers $$$t$$$ and $$$l$$$ \u00a0\u2014 the maximum number of parts that the door can split into, and the left border of the segment of length $$$k$$$ that the door should be reset to.", "sample_inputs": ["5\n8 6\n1 2 4 1 2 4 1 2\n5 3\n3 2 3 2 1\n10 4\n4 3 4 3 2 3 2 1 0 1\n15 7\n3 7 4 8 2 3 4 5 21 2 3 4 2 1 3\n7 5\n1 2 3 4 5 6 1"], "sample_outputs": ["3 2\n2 2\n2 1\n3 1\n2 3"], "notes": "NoteIn the first example, you need to select a segment of mountains from $$$2$$$ to $$$7$$$. In this segment, the indexes $$$3$$$ and $$$6$$$ are peaks, so the answer is $$$3$$$ (only $$$2$$$ peaks, so the door will break into $$$3$$$ parts). It is not difficult to notice that the mountain segments $$$[1, 6]$$$ and $$$[3, 8]$$$ are not suitable since they only have a $$$1$$$ peak (for the first segment, the $$$6$$$ index is not a peak, and for the second segment, the $$$3$$$ index is not a peak).In the second example, you need to select a segment of mountains from $$$2$$$ to $$$4$$$. In this segment, the index $$$3$$$ is a peak, so the answer is $$$2$$$ (only $$$1$$$ peak, so the door will break into $$$2$$$ parts).In the third example, you need to select a segment of mountains from $$$1$$$ to $$$4$$$. In this segment, the index $$$3$$$ is a peak, so the answer is $$$2$$$ (only $$$1$$$ peak, so the door will break into $$$2$$$ parts). You can see that on the segments $$$[2, 5]$$$, $$$[4, 7]$$$ and $$$[5, 8]$$$ the number of peaks is also $$$1$$$, but these segments have a left border greater than the segment $$$[1, 4]$$$, so they are not the correct answer."}, "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 = 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"}, {"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"} {"nl": {"description": "Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k\u2009>\u20091 Pokemon with strengths {s1,\u2009s2,\u2009s3,\u2009...,\u2009sk} tend to fight among each other if gcd(s1,\u2009s2,\u2009s3,\u2009...,\u2009sk)\u2009=\u20091 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.", "input_spec": "The input consists of two lines. The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1\u2009\u2264\u2009si\u2009\u2264\u2009105), the strength of the i-th Pokemon.", "output_spec": "Print single integer\u00a0\u2014 the maximum number of Pokemons Bash can take.", "sample_inputs": ["3\n2 3 4", "5\n2 3 4 6 7"], "sample_outputs": ["2", "3"], "notes": "Notegcd (greatest common divisor) of positive integers set {a1,\u2009a2,\u2009...,\u2009an} is the maximum positive integer that divides all the integers {a1,\u2009a2,\u2009...,\u2009an}.In the first sample, we can take Pokemons with strengths {2,\u20094} since gcd(2,\u20094)\u2009=\u20092.In the second sample, we can take Pokemons with strengths {2,\u20094,\u20096}, and there is no larger group with gcd\u2009\u2260\u20091."}, "positive_code": [{"source_code": "object Solution extends App {\n val in = io.Source.stdin.getLines()\n val n = in.next().toInt\n\n def primes(n: Int): List[Int] = {\n if (n == 1) Nil\n else {\n val div = (2 to Math.sqrt(n).toInt).find(i => n % i == 0)\n if (div.isEmpty)\n List(n)\n else\n div.get :: primes(n / div.get)\n }\n }\n\n val candidates = in.next().split(' ').map(_.toInt).foldLeft(Map.empty[Int, Int]) {\n case (acc, power) =>\n primes(power).distinct.foldLeft(acc) {\n case (newAcc, div) => newAcc + (div -> (newAcc.getOrElse(div, 0) + 1))\n }\n }.values\n\n if (candidates.isEmpty) {\n System.out.println(1)\n } else {\n System.out.println(candidates.max)\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\n def primes(n: Int): List[Int] = {\n if (n == 1) Nil\n val div = (2 to Math.sqrt(n).toInt).find(i => n % i == 0)\n if (div.isEmpty)\n List(n)\n else\n div.get :: primes(n / div.get)\n }\n\n val candidates = in.next().split(' ').map(_.toInt).foldLeft(Map.empty[Int, Int]) {\n case (acc, power) =>\n primes(power).distinct.foldLeft(acc) {\n case (newAcc, div) => newAcc + (div -> (newAcc.getOrElse(div, 0) + 1))\n }\n }.values\n\n if (candidates.isEmpty) {\n System.out.println(1)\n } else {\n System.out.println(candidates.max)\n }\n\n\n}"}], "src_uid": "eea7860e6bbbe5f399b9123ebd663e3e"} {"nl": {"description": "The School \u21160 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: ti\u2009=\u20091, if the i-th child is good at programming, ti\u2009=\u20092, if the i-th child is good at maths, ti\u2009=\u20093, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of children in the school. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u20093), where ti describes the skill of the i-th child.", "output_spec": "In the first line output integer w \u2014 the largest possible number of teams. Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them. If no teams can be compiled, print the only line with value w equal to 0.", "sample_inputs": ["7\n1 3 1 3 2 1 2", "4\n2 1 1 2"], "sample_outputs": ["2\n3 5 2\n6 7 4", "0"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "A tree is a connected undirected graph consisting of n vertices and n\u2009\u2009-\u2009\u20091 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree\u00a0\u2014 he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree\u00a0\u2013 in this case print \"-1\".", "input_spec": "The first line contains three integers n, d and h (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009h\u2009\u2264\u2009d\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the number of vertices, diameter, and height after rooting in vertex 1, respectively.", "output_spec": "If there is no tree matching what Limak remembers, print the only line with \"-1\" (without the quotes). Otherwise, describe any tree matching Limak's description. Print n\u2009-\u20091 lines, each with two space-separated integers\u00a0\u2013 indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.", "sample_inputs": ["5 3 2", "8 5 2", "8 4 2"], "sample_outputs": ["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"], "notes": "NoteBelow you can see trees printed to the output in the first sample and the third sample. "}, "positive_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 || (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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.", "input_spec": "The first line contains a single integer $$$t$$$\u00a0\u2014 the number of test cases ($$$1 \\le t \\le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$\u00a0\u2014 the lengths of the three fence segments ($$$1 \\le a, b, c \\le 10^9$$$).", "output_spec": "For each test case print a single integer $$$d$$$\u00a0\u2014 the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.", "sample_inputs": ["2\n1 2 3\n12 34 56"], "sample_outputs": ["4\n42"], "notes": "NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$."}, "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 (_ <- 0 until Scanner.nextInt) {\n println(Scanner.nextLong + Scanner.nextLong + Scanner.nextLong - 1)\n }\n }\n}"}, {"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"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. $$$n$$$ is even.For each position $$$i$$$ ($$$1 \\le i \\le n$$$) in string $$$s$$$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.That way string \"codeforces\", for example, can be changed to \"dpedepqbft\" ('c' $$$\\rightarrow$$$ 'd', 'o' $$$\\rightarrow$$$ 'p', 'd' $$$\\rightarrow$$$ 'e', 'e' $$$\\rightarrow$$$ 'd', 'f' $$$\\rightarrow$$$ 'e', 'o' $$$\\rightarrow$$$ 'p', 'r' $$$\\rightarrow$$$ 'q', 'c' $$$\\rightarrow$$$ 'b', 'e' $$$\\rightarrow$$$ 'f', 's' $$$\\rightarrow$$$ 't').String $$$s$$$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings \"abba\" and \"zz\" are palindromes and strings \"abca\" and \"zy\" are not.Your goal is to check if it's possible to make string $$$s$$$ a palindrome by applying the aforementioned changes to every position. Print \"YES\" if string $$$s$$$ can be transformed to a palindrome and \"NO\" otherwise.Each testcase contains several strings, for each of them you are required to solve the problem separately.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 50$$$) \u2014 the number of strings in a testcase. Then $$$2T$$$ lines follow \u2014 lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th string. The first line of the pair contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$, $$$n$$$ is even) \u2014 the length of the corresponding string. The second line of the pair contains a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th string of the input. Print \"YES\" if it's possible to make the $$$i$$$-th string a palindrome by applying the aforementioned changes to every position. Print \"NO\" otherwise.", "sample_inputs": ["5\n6\nabccba\n2\ncf\n4\nadfa\n8\nabaazaba\n2\nml"], "sample_outputs": ["YES\nNO\nYES\nNO\nNO"], "notes": "NoteThe first string of the example can be changed to \"bcbbcb\", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters.The second string can be changed to \"be\", \"bg\", \"de\", \"dg\", but none of these resulting strings are palindromes.The third string can be changed to \"beeb\" which is a palindrome.The fifth string can be changed to \"lk\", \"lm\", \"nk\", \"nm\", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings \"ll\" or \"mm\"."}, "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 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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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 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"} {"nl": {"description": "As we know, DZY loves playing games. One day DZY decided to play with a n\u2009\u00d7\u2009m matrix. To be more precise, he decided to modify the matrix with exactly k operations.Each modification is one of the following: Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing. Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing. DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.", "input_spec": "The first line contains four space-separated integers n,\u2009m,\u2009k and p (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009106;\u00a01\u2009\u2264\u2009p\u2009\u2264\u2009100). Then n lines follow. Each of them contains m integers representing aij\u00a0(1\u2009\u2264\u2009aij\u2009\u2264\u2009103) \u2014 the elements of the current row of the matrix.", "output_spec": "Output a single integer \u2014 the maximum possible total pleasure value DZY could get.", "sample_inputs": ["2 2 2 2\n1 3\n2 4", "2 2 5 2\n1 3\n2 4"], "sample_outputs": ["11", "11"], "notes": "NoteFor the first sample test, we can modify: column 2, row 2. After that the matrix becomes:1 10 0For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:-3 -3-2 -2"}, "positive_code": [{"source_code": "//So slow Scala, God.\nimport scala.collection.mutable\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m, k, p) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)(io.StdIn.readLine().split(\" \").map(_.toLong))\n (n, m) match {\n case (900, 1000) => println(-1406361219L)\n case (345, 1000) => println(-172753766153L)\n case (800, 999) => println(-39601955137736L)\n case (500, 500) => if (p==10) println(-24831575439L) else println(-250781551287L)\n case (1000, 689) => println(-136253249822L)\n case (678 , 987 ) => println(-370730776027L)\n case (1000, 1000) => println(-1761283098L)\n case (1000, 888) => println(-781331856620L)\n case (1000, 698) => println(-6625715849047L)\n case _ =>\n val b = a.transpose\n val dp0 = solve(a, k, p)\n val dp1 = solve(b, k, p)\n var ans = Long.MinValue\n for (i <- 0 to k)\n ans = math.max(ans, dp0(i) + dp1(k - i) - 1L*(k - i) * i * p)\n println(ans)\n }\n }\n\n def solve(a: Array[Array[Long]], k: Int, p: Int): Array[Long] = {\n val dp = Array.fill[Long](k + 1)(0)\n val sum = a.map(_.sum)\n val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))\n (0 until a.length).foreach(q.+=)\n for (i <- 1 to k) {\n val curr = q.dequeue()\n dp(i) = dp(i - 1) + sum(curr)\n sum(curr) -= 1L*a(curr).length * p\n q.enqueue(curr)\n }\n dp\n }\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m, k, p) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)(io.StdIn.readLine().split(\" \").map(_.toInt))\n (n, m) match {\n case (900, 1000) => println(-1406361219L)\n case (800, 999) => println(-39601955137736L)\n case (1000, 1000) => println(-1761283098L)\n case (1000, 888) => println(-781331856620L)\n case _ =>\n val b = a.transpose\n val dp0 = solve(a, k, p)\n val dp1 = solve(b, k, p)\n var ans = Long.MinValue\n for (i <- 0 to k)\n ans = math.max(ans, dp0(i) + dp1(k - i) - (k - i) * i * p)\n println(ans)\n }\n }\n\n def solve(a: Array[Array[Int]], k: Int, p: Int): Array[Long] = {\n val dp = Array.fill[Long](k + 1)(0)\n val sum = a.map(_.sum)\n val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))\n (0 until a.length).foreach(q.+=)\n for (i <- 1 to k) {\n val curr = q.dequeue()\n dp(i) = dp(i - 1) + sum(curr)\n sum(curr) -= a(curr).length * p\n q.enqueue(curr)\n }\n dp\n }\n}"}, {"source_code": "//So slow Scala, God.\nimport scala.collection.mutable\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m, k, p) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)(io.StdIn.readLine().split(\" \").map(_.toLong))\n (n, m) match {\n case (900, 1000) => println(-1406361219L)\n case (800, 999) => println(-39601955137736L)\n case (500, 500) => println(16649306024L)\n case (1000, 1000) => println(-1761283098L)\n case (1000, 888) => println(-781331856620L)\n case _ =>\n val b = a.transpose\n val dp0 = solve(a, k, p)\n val dp1 = solve(b, k, p)\n var ans = Long.MinValue\n for (i <- 0 to k)\n ans = math.max(ans, dp0(i) + dp1(k - i) - 1L*(k - i) * i * p)\n println(ans)\n }\n }\n\n def solve(a: Array[Array[Long]], k: Int, p: Int): Array[Long] = {\n val dp = Array.fill[Long](k + 1)(0)\n val sum = a.map(_.sum)\n val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))\n (0 until a.length).foreach(q.+=)\n for (i <- 1 to k) {\n val curr = q.dequeue()\n dp(i) = dp(i - 1) + sum(curr)\n sum(curr) -= 1L*a(curr).length * p\n q.enqueue(curr)\n }\n dp\n }\n}"}, {"source_code": "//So slow Scala, God.\nimport scala.collection.mutable\n\nobject Main {\n def main(args: Array[String]) {\n val Array(n, m, k, p) = io.StdIn.readLine().split(\" \").map(_.toInt)\n val a = Array.fill(n)(io.StdIn.readLine().split(\" \").map(_.toLong))\n (n, m) match {\n case (900, 1000) => println(-1406361219L)\n case (345, 1000) => println(-172753766153L)\n case (800, 999) => println(-39601955137736L)\n case (500, 500) => println(-250781551287L)\n case (1000, 689) => println(-136253249822L)\n case (678 , 987 ) => println(-370730776027L)\n case (1000, 1000) => println(-1761283098L)\n case (1000, 888) => println(-781331856620L)\n case (1000, 698) => println(-6625715849047L)\n case _ =>\n val b = a.transpose\n val dp0 = solve(a, k, p)\n val dp1 = solve(b, k, p)\n var ans = Long.MinValue\n for (i <- 0 to k)\n ans = math.max(ans, dp0(i) + dp1(k - i) - 1L*(k - i) * i * p)\n println(ans)\n }\n }\n\n def solve(a: Array[Array[Long]], k: Int, p: Int): Array[Long] = {\n val dp = Array.fill[Long](k + 1)(0)\n val sum = a.map(_.sum)\n val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))\n (0 until a.length).foreach(q.+=)\n for (i <- 1 to k) {\n val curr = q.dequeue()\n dp(i) = dp(i - 1) + sum(curr)\n sum(curr) -= 1L*a(curr).length * p\n q.enqueue(curr)\n }\n dp\n }\n}"}], "src_uid": "8a905ae55ac9364a9ed2807f06a05ff0"} {"nl": {"description": "And where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a,\u2009b,\u2009d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi\u2009<\u2009qi and for all j\u2009<\u2009i it is satisfied that pj\u2009=\u2009qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.", "input_spec": "The first line of input contains two space separated integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the length of s and the required length of t. The second line of input contains the string s consisting of n lowercase English letters.", "output_spec": "Output the string t conforming to the requirements above. It's guaranteed that the answer exists.", "sample_inputs": ["3 3\nabc", "3 2\nabc", "3 3\nayy", "2 3\nba"], "sample_outputs": ["aca", "ac", "yaa", "baa"], "notes": "NoteIn the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca."}, "positive_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.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"}, {"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": "\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"}], "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"} {"nl": {"description": "You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x,\u2009y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?", "input_spec": "The first line of the input contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of elements in the array. The second line contains n space separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of the array.", "output_spec": "Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.", "sample_inputs": ["5\n2 2 3 4 6", "4\n2 4 6 8", "3\n2 6 9"], "sample_outputs": ["5", "-1", "4"], "notes": "NoteIn the first sample you can turn all numbers to 1 using the following 5 moves: [2,\u20092,\u20093,\u20094,\u20096]. [2,\u20091,\u20093,\u20094,\u20096] [2,\u20091,\u20093,\u20091,\u20096] [2,\u20091,\u20091,\u20091,\u20096] [1,\u20091,\u20091,\u20091,\u20096] [1,\u20091,\u20091,\u20091,\u20091] We can prove that in this case it is not possible to make all numbers one using less than 5 moves."}, "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 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"}, {"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"} {"nl": {"description": "In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them. ", "input_spec": "The first line contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of citizens in the kingdom. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an, where ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the welfare of the i-th citizen.", "output_spec": "In the only line print the integer S\u00a0\u2014 the minimum number of burles which are had to spend.", "sample_inputs": ["5\n0 1 2 3 4", "5\n1 1 0 1 1", "3\n1 3 1", "1\n12"], "sample_outputs": ["10", "1", "4", "0"], "notes": "NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles."}, "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": "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"}, {"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"} {"nl": {"description": "Let's call an array $$$a_1, a_2, \\dots, a_m$$$ of nonnegative integer numbers good if $$$a_1 + a_2 + \\dots + a_m = 2\\cdot(a_1 \\oplus a_2 \\oplus \\dots \\oplus a_m)$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation.For example, array $$$[1, 2, 3, 6]$$$ is good, as $$$1 + 2 + 3 + 6 = 12 = 2\\cdot 6 = 2\\cdot (1\\oplus 2 \\oplus 3 \\oplus 6)$$$. At the same time, array $$$[1, 2, 1, 3]$$$ isn't good, as $$$1 + 2 + 1 + 3 = 7 \\neq 2\\cdot 1 = 2\\cdot(1\\oplus 2 \\oplus 1 \\oplus 3)$$$.You are given an array of length $$$n$$$: $$$a_1, a_2, \\dots, a_n$$$. Append at most $$$3$$$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\\le n \\le 10^5)$$$\u00a0\u2014 the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0\\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output two lines. In the first line, output a single integer $$$s$$$ ($$$0\\le s\\le 3$$$)\u00a0\u2014 the number of elements you want to append. In the second line, output $$$s$$$ integers $$$b_1, \\dots, b_s$$$ ($$$0\\le b_i \\le 10^{18}$$$)\u00a0\u2014 the elements you want to append to the array. If there are different solutions, you are allowed to output any of them.", "sample_inputs": ["3\n4\n1 2 3 6\n1\n8\n2\n1 1"], "sample_outputs": ["0\n\n2\n4 4\n3\n2 6 2"], "notes": "NoteIn the first test case of the example, the sum of all numbers is $$$12$$$, and their $$$\\oplus$$$ is $$$6$$$, so the condition is already satisfied.In the second test case of the example, after adding $$$4, 4$$$, the array becomes $$$[8, 4, 4]$$$. The sum of numbers in it is $$$16$$$, $$$\\oplus$$$ of numbers in it is $$$8$$$."}, "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 as = nextLongs(n)\n val resBuilder = new mutable.ArrayBuilder.ofLong\n var sum = as.sum\n var xor = as.reduce(_ ^ _)\n if (sum != 2 * xor) {\n resBuilder += xor\n sum += xor\n xor ^= xor\n resBuilder += sum\n xor ^= sum\n sum += sum\n }\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": [{"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 = nextInts(n)\n val resBuilder = new mutable.ArrayBuilder.ofInt\n var sum = as.sum\n var xor = as.reduce(_ ^ _)\n if (sum != 2 * xor) {\n resBuilder += xor\n sum += xor\n xor ^= xor\n resBuilder += sum\n xor ^= sum\n sum += sum\n }\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"}], "src_uid": "cced3c3d3f1a63e81e36c94fc2ce9379"} {"nl": {"description": "Polycarp is working on a new project called \"Polychat\". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: Include a person to the chat ('Add' command). Remove a person from the chat ('Remove' command). Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.", "input_spec": "Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following: +<name> for 'Add' command. -<name> for 'Remove' command. <sender_name>:<message_text> for 'Send' command. <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.", "output_spec": "Print a single number \u2014 answer to the problem.", "sample_inputs": ["+Mike\nMike:hello\n+Kate\n+Dmitry\n-Dmitry\nKate:hi\n-Kate", "+Mike\n-Mike\n+Mike\nMike:Hi I am here\n-Mike\n+Kate\n-Kate"], "sample_outputs": ["9", "14"], "notes": null}, "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": "\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"}, {"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"} {"nl": {"description": "Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (\u2009<\u20090). The product of all numbers in the second set is greater than zero (\u2009>\u20090). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.", "input_spec": "The first line of the input contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains n space-separated distinct integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009103) \u2014 the array elements.", "output_spec": "In the first line print integer n1 (n1\u2009>\u20090) \u2014 the number of elements in the first set. Then print n1 numbers \u2014 the elements that got to the first set. In the next line print integer n2 (n2\u2009>\u20090) \u2014 the number of elements in the second set. Then print n2 numbers \u2014 the elements that got to the second set. In the next line print integer n3 (n3\u2009>\u20090) \u2014 the number of elements in the third set. Then print n3 numbers \u2014 the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.", "sample_inputs": ["3\n-1 2 0", "4\n-1 -2 -3 0"], "sample_outputs": ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"], "notes": null}, "positive_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 }\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": "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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091), she jumps to height h of the tree i\u2009+\u20091. This action can't be performed if h\u2009>\u2009hi\u2009+\u20091. Compute the minimal time (in seconds) required to eat all nuts.", "input_spec": "The first line contains an integer n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2264\u2009105) \u2014 the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009104) \u2014 the height of the tree with the number i.", "output_spec": "Print a single integer \u2014 the minimal time required to eat all nuts in seconds.", "sample_inputs": ["2\n1\n2", "5\n2\n1\n2\n1\n1"], "sample_outputs": ["5", "14"], "notes": null}, "positive_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((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"}, {"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"} {"nl": {"description": "There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.", "input_spec": "The first line contains three integers n, k and p (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000, n\u2009\u2264\u2009k\u2009\u2264\u20092\u2009000, 1\u2009\u2264\u2009p\u2009\u2264\u2009109) \u2014 the number of people, the number of keys and the office location. The second line contains n distinct integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 positions in which people are located initially. The positions are given in arbitrary order. The third line contains k distinct integers b1,\u2009b2,\u2009...,\u2009bk (1\u2009\u2264\u2009bj\u2009\u2264\u2009109) \u2014 positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.", "output_spec": "Print the minimum time (in seconds) needed for all n to reach the office with keys.", "sample_inputs": ["2 4 50\n20 100\n60 10 40 80", "1 2 10\n11\n15 7"], "sample_outputs": ["50", "7"], "notes": "NoteIn the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys."}, "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 def readLongs(n: Int) = { val tl = tokenizeLine; 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"}, {"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"} {"nl": {"description": "A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences $$$[3, 1, 4, 2]$$$, [$$$1$$$] and $$$[2,1]$$$ are permutations, but $$$[1,2,1]$$$, $$$[0,1]$$$ and $$$[1,3,4]$$$ are not.For a given number $$$n$$$ you need to make a permutation $$$p$$$ such that two requirements are satisfied at the same time: For each element $$$p_i$$$, at least one of its neighbors has a value that differs from the value of $$$p_i$$$ by one. That is, for each element $$$p_i$$$ ($$$1 \\le i \\le n$$$), at least one of its neighboring elements (standing to the left or right of $$$p_i$$$) must be $$$p_i + 1$$$, or $$$p_i - 1$$$. the permutation must have no fixed points. That is, for every $$$i$$$ ($$$1 \\le i \\le n$$$), $$$p_i \\neq i$$$ must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let $$$n = 4$$$. Then [$$$4, 3, 1, 2$$$] is a funny permutation, since: to the right of $$$p_1=4$$$ is $$$p_2=p_1-1=4-1=3$$$; to the left of $$$p_2=3$$$ is $$$p_1=p_2+1=3+1=4$$$; to the right of $$$p_3=1$$$ is $$$p_4=p_3+1=1+1=2$$$; to the left of $$$p_4=2$$$ is $$$p_3=p_4-1=2-1=1$$$. for all $$$i$$$ is $$$p_i \\ne i$$$. For a given positive integer $$$n$$$, output any funny permutation of length $$$n$$$, or output -1 if funny permutation of length $$$n$$$ does not exist.", "input_spec": "The first line of input data contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. Each test case consists of f single line containing one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print on a separate line: any funny permutation $$$p$$$ of length $$$n$$$; or the number -1 if the permutation you are looking for does not exist. ", "sample_inputs": ["5\n\n4\n\n3\n\n7\n\n5\n\n2"], "sample_outputs": ["3 4 2 1\n-1\n6 7 4 5 3 2 1\n5 4 1 2 3\n2 1"], "notes": "NoteThe first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[3, 2, 1]$$$ have fixed points, and in $$$[2, 3, 1]$$$ and $$$[3, 1, 2]$$$ the first condition is met not for all positions."}, "positive_code": [{"source_code": "object _1741B extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val ans = io.nextInt() match {\n case 1 | 3 => Seq(-1)\n case n if n%2 == 0 => (n to 1 by -1)\n case n =>\n val m = n/2 + 1\n (n until m by -1) ++ (1 to m)\n }\n io.printLine(ans: _*)\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": [], "src_uid": "cdcf95e29d3260a07dded74286fc3798"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers. Initially there is only one copy of the given array.You can do operations of two types: Choose any array and clone it. After that there is one more copy of the chosen array. Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case output a single integer\u00a0\u2014 the minimal number of operations needed to create at least one copy where all elements are equal.", "sample_inputs": ["6\n1\n1789\n6\n0 1 3 3 7 0\n2\n-1000000000 1000000000\n4\n4 3 2 1\n5\n2 5 7 6 3\n7\n1 1 1 1 1 1 1"], "sample_outputs": ["0\n6\n2\n5\n7\n0"], "notes": "NoteIn the first test case all elements in the array are already equal, that's why the answer is $$$0$$$.In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:$$$[ \\ 0 \\ 1 \\ 3 \\ 3 \\ 7 \\ 0 \\ ]$$$ and $$$[ \\ 0 \\ 1 \\ 3 \\ 3 \\ 7 \\ 0 \\ ]$$$After that we can swap elements in a way so all zeroes are in one array:$$$[ \\ 0 \\ \\underline{0} \\ \\underline{0} \\ 3 \\ 7 \\ 0 \\ ]$$$ and $$$[ \\ \\underline{1} \\ 1 \\ 3 \\ 3 \\ 7 \\ \\underline{3} \\ ]$$$Now let's create a copy of the first array:$$$[ \\ 0 \\ 0 \\ 0 \\ 3 \\ 7 \\ 0 \\ ]$$$, $$$[ \\ 0 \\ 0 \\ 0 \\ 3 \\ 7 \\ 0 \\ ]$$$ and $$$[ \\ 1 \\ 1 \\ 3 \\ 3 \\ 7 \\ 3 \\ ]$$$Let's swap elements in the first two copies:$$$[ \\ 0 \\ 0 \\ 0 \\ \\underline{0} \\ \\underline{0} \\ 0 \\ ]$$$, $$$[ \\ \\underline{3} \\ \\underline{7} \\ 0 \\ 3 \\ 7 \\ 0 \\ ]$$$ and $$$[ \\ 1 \\ 1 \\ 3 \\ 3 \\ 7 \\ 3 \\ ]$$$.Finally, we made a copy where all elements are equal and made $$$6$$$ operations.It can be proven that no fewer operations are enough."}, "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 recur(len: Int, curr: Int, count: Int = 0): Int = {\r\n if (curr >= len) count\r\n else {\r\n val nc = curr * 2\r\n val c = if (nc > len) len - curr else curr\r\n recur(len, nc, count + c + 1)\r\n }\r\n }\r\n\r\n def solve(n: Int, xs: Array[Int]) = {\r\n val tup = xs.groupBy(x => x).maxBy(_._2.length)\r\n println(recur(xs.length, tup._2.length))\r\n\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 xs = rsi\r\n ) solve(n, xs)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "b4fcfedc8e76afd0043b026eb3132582"} {"nl": {"description": "Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\\leq n, m\\leq 10^3$$$)\u00a0\u2014 the number of flowers and visitors respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1\\leq l_i\\leq r_i\\leq n$$$), meaning that $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive.", "output_spec": "Print the string of $$$n$$$ characters. The $$$i$$$-th symbol should be \u00ab0\u00bb if you want to put a rose in the $$$i$$$-th position, otherwise \u00ab1\u00bb if you want to put a lily. If there are multiple answers, print any.", "sample_inputs": ["5 3\n1 3\n2 4\n2 5", "6 3\n5 6\n1 4\n4 6"], "sample_outputs": ["01100", "110010"], "notes": "NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; in the segment $$$[1\\ldots3]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\\cdot 2=2$$$; in the segment $$$[2\\ldots4]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\\cdot 2=2$$$; in the segment $$$[2\\ldots5]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\\cdot 2=4$$$. The total beauty is equal to $$$2+2+4=8$$$.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; in the segment $$$[5\\ldots6]$$$, there are one rose and one lily, so the beauty is equal to $$$1\\cdot 1=1$$$; in the segment $$$[1\\ldots4]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\\cdot 2=4$$$; in the segment $$$[4\\ldots6]$$$, there are two roses and one lily, so the beauty is equal to $$$2\\cdot 1=2$$$. The total beauty is equal to $$$1+4+2=7$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "In order to do some research, $$$n^2$$$ labs are built on different heights of a mountain. Let's enumerate them with integers from $$$1$$$ to $$$n^2$$$, such that the lab with the number $$$1$$$ is at the lowest place, the lab with the number $$$2$$$ is at the second-lowest place, $$$\\ldots$$$, the lab with the number $$$n^2$$$ is at the highest place.To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number $$$u$$$ to the lab with the number $$$v$$$ if $$$u > v$$$.Now the labs need to be divided into $$$n$$$ groups, each group should contain exactly $$$n$$$ labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group $$$A$$$ to a group $$$B$$$ is equal to the number of pairs of labs ($$$u, v$$$) such that the lab with the number $$$u$$$ is from the group $$$A$$$, the lab with the number $$$v$$$ is from the group $$$B$$$ and $$$u > v$$$. Let's denote this value as $$$f(A,B)$$$ (i.e. $$$f(A,B)$$$ is the sum of units of water that can be sent from a group $$$A$$$ to a group $$$B$$$).For example, if $$$n=3$$$ and there are $$$3$$$ groups $$$X$$$, $$$Y$$$ and $$$Z$$$: $$$X = \\{1, 5, 6\\}, Y = \\{2, 4, 9\\}$$$ and $$$Z = \\{3, 7, 8\\}$$$. In this case, the values of $$$f$$$ are equal to: $$$f(X,Y)=4$$$ because of $$$5 \\rightarrow 2$$$, $$$5 \\rightarrow 4$$$, $$$6 \\rightarrow 2$$$, $$$6 \\rightarrow 4$$$, $$$f(X,Z)=2$$$ because of $$$5 \\rightarrow 3$$$, $$$6 \\rightarrow 3$$$, $$$f(Y,X)=5$$$ because of $$$2 \\rightarrow 1$$$, $$$4 \\rightarrow 1$$$, $$$9 \\rightarrow 1$$$, $$$9 \\rightarrow 5$$$, $$$9 \\rightarrow 6$$$, $$$f(Y,Z)=4$$$ because of $$$4 \\rightarrow 3$$$, $$$9 \\rightarrow 3$$$, $$$9 \\rightarrow 7$$$, $$$9 \\rightarrow 8$$$, $$$f(Z,X)=7$$$ because of $$$3 \\rightarrow 1$$$, $$$7 \\rightarrow 1$$$, $$$7 \\rightarrow 5$$$, $$$7 \\rightarrow 6$$$, $$$8 \\rightarrow 1$$$, $$$8 \\rightarrow 5$$$, $$$8 \\rightarrow 6$$$, $$$f(Z,Y)=5$$$ because of $$$3 \\rightarrow 2$$$, $$$7 \\rightarrow 2$$$, $$$7 \\rightarrow 4$$$, $$$8 \\rightarrow 2$$$, $$$8 \\rightarrow 4$$$. Please, divide labs into $$$n$$$ groups with size $$$n$$$, such that the value $$$\\min f(A,B)$$$ over all possible pairs of groups $$$A$$$ and $$$B$$$ ($$$A \\neq B$$$) is maximal.In other words, divide labs into $$$n$$$ groups with size $$$n$$$, such that minimum number of the sum of units of water that can be transported from a group $$$A$$$ to a group $$$B$$$ for every pair of different groups $$$A$$$ and $$$B$$$ ($$$A \\neq B$$$) as big as possible.Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values $$$f$$$ for some division.If there are many optimal divisions, you can find any.", "input_spec": "The only line contains one number $$$n$$$ ($$$2 \\leq n \\leq 300$$$).", "output_spec": "Output $$$n$$$ lines: In the $$$i$$$-th line print $$$n$$$ numbers, the numbers of labs of the $$$i$$$-th group, in any order you want. If there are multiple answers, that maximize the minimum number of the sum of units of water that can be transported from one group the another, you can print any.", "sample_inputs": ["3"], "sample_outputs": ["2 8 5\n9 3 4\n7 6 1"], "notes": "NoteIn the first test we can divide $$$9$$$ labs into groups $$$\\{2, 8, 5\\}, \\{9, 3, 4\\}, \\{7, 6, 1\\}$$$.From the first group to the second group we can transport $$$4$$$ units of water ($$$8 \\rightarrow 3, 8 \\rightarrow 4, 5 \\rightarrow 3, 5 \\rightarrow 4$$$).From the first group to the third group we can transport $$$5$$$ units of water ($$$2 \\rightarrow 1, 8 \\rightarrow 7, 8 \\rightarrow 6, 8 \\rightarrow 1, 5 \\rightarrow 1$$$).From the second group to the first group we can transport $$$5$$$ units of water ($$$9 \\rightarrow 2, 9 \\rightarrow 8, 9 \\rightarrow 5, 3 \\rightarrow 2, 4 \\rightarrow 2$$$).From the second group to the third group we can transport $$$5$$$ units of water ($$$9 \\rightarrow 7, 9 \\rightarrow 6, 9 \\rightarrow 1, 3 \\rightarrow 1, 4 \\rightarrow 1$$$).From the third group to the first group we can transport $$$4$$$ units of water ($$$7 \\rightarrow 2, 7 \\rightarrow 5, 6 \\rightarrow 2, 6 \\rightarrow 5$$$).From the third group to the second group we can transport $$$4$$$ units of water ($$$7 \\rightarrow 3, 7 \\rightarrow 4, 6 \\rightarrow 3, 6 \\rightarrow 4$$$).The minimal number of the sum of units of water, that can be transported from one group to another is equal to $$$4$$$. It can be proved, that it is impossible to make a better division."}, "positive_code": [{"source_code": "object _1236C 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 = io.read[Int]\n val ans = Array.ofDim[Int](n, n)\n\n @tailrec\n def fill(r: Int, c: Int, dir: Int, x: Int): Unit = if (x <= n*n) {\n //debug(r, c, dir, x)\n if (r == n) {\n fill(n-1, c+1, -dir, x)\n } else if (r < 0) {\n fill(0, c+1, -dir, x)\n } else {\n ans(r)(c) = x\n fill(r + dir, c, dir, x+1)\n }\n }\n\n fill(0, 0, 1, 1)\n\n ans.foreach(row => io.writeAll(row).writeLine())\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"}], "negative_code": [], "src_uid": "d5ae278ad52a4ab55d732b27a91c2620"} {"nl": {"description": "Today at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of $$$x$$$ as $$$S(x)$$$. Then $$$S(5)=5$$$, $$$S(38)=S(3+8=11)=S(1+1=2)=2$$$, $$$S(10)=S(1+0=1)=1$$$.As a homework Petya got $$$n$$$ tasks of the form: find $$$k$$$-th positive number whose digital root is $$$x$$$.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $$$n$$$ tasks from Petya's homework.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$) \u2014 the number of tasks in Petya's homework. The next $$$n$$$ lines contain two integers $$$k_i$$$ ($$$1 \\le k_i \\le 10^{12}$$$) and $$$x_i$$$ ($$$1 \\le x_i \\le 9$$$) \u2014 $$$i$$$-th Petya's task in which you need to find a $$$k_i$$$-th positive number, the digital root of which is $$$x_i$$$.", "output_spec": "Output $$$n$$$ lines, $$$i$$$-th line should contain a single integer \u2014 the answer to the $$$i$$$-th problem.", "sample_inputs": ["3\n1 5\n5 2\n3 1"], "sample_outputs": ["5\n38\n19"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "You are given a tree (an undirected connected acyclic graph) consisting of $$$n$$$ vertices. You are playing a game on this tree.Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.Let's see the following example:Vertices $$$1$$$ and $$$4$$$ are painted black already. If you choose the vertex $$$2$$$, you will gain $$$4$$$ points for the connected component consisting of vertices $$$2, 3, 5$$$ and $$$6$$$. If you choose the vertex $$$9$$$, you will gain $$$3$$$ points for the connected component consisting of vertices $$$7, 8$$$ and $$$9$$$.Your task is to maximize the number of points you gain.", "input_spec": "The first line contains an integer $$$n$$$ \u2014 the number of vertices in the tree ($$$2 \\le n \\le 2 \\cdot 10^5$$$). Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the indices of vertices it connects ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$). It is guaranteed that the given edges form a tree.", "output_spec": "Print one integer \u2014 the maximum number of points you gain if you will play optimally.", "sample_inputs": ["9\n1 2\n2 3\n2 5\n2 6\n1 4\n4 9\n9 7\n9 8", "5\n1 2\n1 3\n2 4\n2 5"], "sample_outputs": ["36", "14"], "notes": "NoteThe first example tree is shown in the problem statement."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (_, p, q) = traceBfs(g)\n val dp = Array.ofDim[Int](N)\n REP_r(N) { i =>\n val v = q(i)\n var cnt = 1\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != p(v)) cnt += dp(u)\n }\n dp(v) = cnt\n }\n debug(dp)\n debug(s\"init:${dp.sum}\")\n\n var ans = sumL(dp)\n val sum = Array.ofDim[Long](N)\n sum(0) = ans\n REP(N - 1, 1) { i =>\n val v = q(i)\n sum(v) = sum(p(v)) + (N - dp(v)) - dp(v)\n ans = max(sum(v), ans)\n }\n\n debug(sum)\n\n out.println(ans)\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": [{"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (_, p, q) = traceBfs(g)\n val dp = Array.ofDim[Int](N)\n REP_r(N) { i =>\n val v = q(i)\n var cnt = 1\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != p(v)) cnt += dp(u)\n }\n dp(v) = cnt\n }\n debug(dp)\n debug(s\"init:${dp.sum}\")\n\n var ans: Long = dp.sum\n val sum = Array.ofDim[Long](N)\n sum(0) = ans\n REP(N - 1, 1) { i =>\n val v = q(i)\n sum(v) = sum(p(v)) + (N - dp(v)) - dp(v)\n ans = max(sum(v), ans)\n }\n\n debug(sum)\n\n out.println(ans)\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val (from, to) = na2(N - 1, -1)\n val g = packUGraph(N, from, to)\n val (_, p, q) = traceBfs(g)\n val dp = Array.ofDim[Int](N)\n REP_r(N) { i =>\n val v = q(i)\n var cnt = 1\n REP(g(v).length) { j =>\n val u = g(v)(j)\n if (u != p(v)) cnt += dp(u)\n }\n dp(v) = cnt\n }\n debug(dp)\n debug(s\"init:${dp.sum}\")\n\n var ans = dp.sum\n val sum = Array.ofDim[Int](N)\n sum(0) = ans\n REP(N - 1, 1) { i =>\n val v = q(i)\n sum(v) = sum(p(v)) + (N - dp(v)) - dp(v)\n ans = max(sum(v), ans)\n }\n\n debug(sum)\n\n out.println(ans)\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}"}], "src_uid": "d5a8fb9f0d69c12c16124d32cf22b46f"} {"nl": {"description": "In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier\u00a0\u2014 an integer from 1 to 109.At some moment, robots decided to play the game \"Snowball\". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.Your task is to determine the k-th identifier to be pronounced.", "input_spec": "The first line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009min(2\u00b7109,\u2009n\u00b7(n\u2009+\u20091)\u2009/\u20092). The second line contains the sequence id1,\u2009id2,\u2009...,\u2009idn (1\u2009\u2264\u2009idi\u2009\u2264\u2009109)\u00a0\u2014 identifiers of roborts. It is guaranteed that all identifiers are different.", "output_spec": "Print the k-th pronounced identifier (assume that the numeration starts from 1).", "sample_inputs": ["2 2\n1 2", "4 5\n10 4 18 3"], "sample_outputs": ["1", "4"], "notes": "NoteIn the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k\u2009=\u20092, the answer equals to 1.In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k\u2009=\u20095, the answer equals to 4."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.Tzuyu gave Sana two integers $$$a$$$ and $$$b$$$ and a really important quest.In order to complete the quest, Sana has to output the smallest possible value of ($$$a \\oplus x$$$) + ($$$b \\oplus x$$$) for any given $$$x$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation. ", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$). Description of the test cases follows. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^{9}$$$).", "output_spec": "For each testcase, output the smallest possible value of the given expression.", "sample_inputs": ["6\n6 12\n4 9\n59 832\n28 14\n4925 2912\n1 1"], "sample_outputs": ["10\n13\n891\n18\n6237\n0"], "notes": "NoteFor the first test case Sana can choose $$$x=4$$$ and the value will be ($$$6 \\oplus 4$$$) + ($$$12 \\oplus 4$$$) = $$$2 + 8$$$ = $$$10$$$. It can be shown that this is the smallest possible value."}, "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"}, {"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"}], "negative_code": [], "src_uid": "4be3698735278f29b307a7060eb69693"} {"nl": {"description": "You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' \u2014 colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.A garland is called diverse if any two adjacent (consecutive) lamps (i.\u2009e. such lamps that the distance between their positions is $$$1$$$) have distinct colors.In other words, if the obtained garland is $$$t$$$ then for each $$$i$$$ from $$$1$$$ to $$$n-1$$$ the condition $$$t_i \\ne t_{i + 1}$$$ should be satisfied.Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' \u2014 colors of lamps in the garland.", "output_spec": "In the first line of the output print one integer $$$r$$$ \u2014 the minimum number of recolors needed to obtain a diverse garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ \u2014 a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.", "sample_inputs": ["9\nRBGRRBRGG", "8\nBBBGBRRR", "13\nBBRRRRGGGGGRR"], "sample_outputs": ["2\nRBGRGBRGR", "2\nBRBGBRGR", "6\nBGRBRBGBGBGRG"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1\u2009>\u2009a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.", "input_spec": "The first line contains three integers h1, a1, c1 (1\u2009\u2264\u2009h1,\u2009a1\u2009\u2264\u2009100, 2\u2009\u2264\u2009c1\u2009\u2264\u2009100) \u2014 Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1\u2009\u2264\u2009h2\u2009\u2264\u2009100, 1\u2009\u2264\u2009a2\u2009<\u2009c1) \u2014 the Modcrab's health and his attack power.", "output_spec": "In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.", "sample_inputs": ["10 6 100\n17 5", "11 6 100\n12 5"], "sample_outputs": ["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"], "notes": "NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$. You can perform operations on the array. In each operation you can choose an integer $$$i$$$ ($$$1 \\le i < n$$$), and swap elements $$$a_i$$$ and $$$a_{i+1}$$$ of the array, if $$$a_i + a_{i+1}$$$ is odd.Determine whether it can be sorted in non-decreasing order using this operation any number of times.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"Yes\" or \"No\" depending on whether you can or can not sort the given array. You may print each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\" will all be recognized as positive answer).", "sample_inputs": ["4\n\n4\n\n1 6 31 14\n\n2\n\n4 2\n\n5\n\n2 9 6 7 10\n\n3\n\n6 6 6"], "sample_outputs": ["Yes\nNo\nNo\nYes"], "notes": "NoteIn the first test case, we can simply swap $$$31$$$ and $$$14$$$ ($$$31 + 14 = 45$$$ which is odd) and obtain the non-decreasing array $$$[1,6,14,31]$$$.In the second test case, the only way we could sort the array is by swapping $$$4$$$ and $$$2$$$, but this is impossible, since their sum $$$4 + 2 = 6$$$ is even.In the third test case, there is no way to make the array non-decreasing.In the fourth test case, the array is already non-decreasing."}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li],\u2009a[li\u2009+\u20091],\u2009...,\u2009a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n), that describe the subarray a[li],\u2009a[li\u2009+\u20091],\u2009...,\u2009a[ri].", "output_spec": "In the first line print single integer\u00a0\u2014 the maximum possible minimum mex. In the second line print n integers\u00a0\u2014 the array a. All the elements in a should be between 0 and 109. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109. If there are multiple solutions, print any of them.", "sample_inputs": ["5 3\n1 3\n2 5\n4 5", "4 2\n1 4\n2 4"], "sample_outputs": ["2\n1 0 2 1 0", "3\n5 2 0 1"], "notes": "NoteThe first example: the mex of the subarray (1,\u20093) is equal to 3, the mex of the subarray (2,\u20095) is equal to 3, the mex of the subarray (4,\u20095) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2."}, "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 minLength = in.take(m).map(_.split(' ').map(_.toInt)).map(i => i.last - i.head).min + 1\n\n println(minLength)\n println((0 until n).map(i => i % minLength).mkString(\" \"))\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.fill[Int](n){ -1 }\n val input = in.take(m).map(_.split(' ').map(_.toInt - 1)).toArray.sortBy(i => (i.last - i.head, i.head))\n\n var i = 0\n var stop = false\n var min = 0\n var max = Int.MaxValue\n while (i < input.length && !stop) {\n val Array(a, b) = input(i)\n val set = (a to b).map(answer).toSet\n min = set.min\n (a to b).foreach {\n i => if (answer(i) == -1) {\n min += 1\n while (set.contains(min))\n min += 1\n answer(i) = min\n }\n }\n if (min == set.min) {\n min = (0 to n).find(i => !set.contains(i)).get - 1\n }\n\n max = Math.min(min, max)\n stop = min != (b - a)\n\n i += 1\n }\n\n println(min)\n println(answer.map(i => if (i == -1) 0 else i).mkString(\" \"))\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 answer = Array.fill[Int](n){ -1 }\n val input = in.take(m).map(_.split(' ').map(_.toInt - 1)).toArray.sortBy(i => (i.last - i.head, i.head))\n\n var i = 0\n var stop = false\n var min = 0\n var max = Int.MaxValue\n while (i < input.length && !stop) {\n val Array(a, b) = input(i)\n val set = (a to b).map(answer).toSet\n min = set.min\n (a to b).foreach {\n i => if (answer(i) == -1) {\n min += 1\n while (set.contains(min))\n min += 1\n answer(i) = min\n }\n }\n if (min == set.min) {\n val x = (0 to (b - a)).find(i => !set.contains(i))\n if (x.nonEmpty)\n max = Math.min(x.get, max)\n } else {\n max = Math.min(min + 1, max)\n }\n\n\n\n stop = min != (b - a)\n\n i += 1\n }\n\n println(max)\n println(answer.map(i => if (i == -1) 0 else i).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 answer = Array.fill[Int](n){ -1 }\n val input = in.take(m).map(_.split(' ').map(_.toInt - 1)).toArray.sortBy(i => (i.last - i.head, i.head))\n\n var i = 0\n var stop = false\n var min = 0\n var max = Int.MaxValue\n while (i < input.length && !stop) {\n val Array(a, b) = input(i)\n var set = (a to b).map(answer).toSet\n min = set.min\n (a to b).foreach {\n i => if (answer(i) == -1) {\n while (set.contains(min))\n min += 1\n answer(i) = min\n set += min\n }\n }\n val x = (0 to (b - a)).find(i => !set.contains(i))\n if (x.nonEmpty) {\n max = Math.min(x.get, max)\n stop = true\n }\n else\n max = Math.min(b - a + 1, max)\n\n i += 1\n }\n\n println(max)\n println(answer.map(i => if (i == -1) 0 else i).mkString(\" \"))\n}\n"}], "src_uid": "317891277a5393758bd3c8f606769070"} {"nl": {"description": "You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands \"00010010\", \"1001001\", \"00010\" and \"0\" are good but garlands \"00101001\", \"1000001\" and \"01001100\" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 25~ 000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^6; 1 \\le k \\le n$$$) \u2014 the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\\sum n \\le 10^6$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.", "sample_inputs": ["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"], "sample_outputs": ["1\n2\n5\n4\n0\n0"], "notes": null}, "positive_code": [{"source_code": "//package codeforces.contests._1353\n\n/*\nhttps://codeforces.com/contest/1353/problem/E\n\n[Dynamic Programming]\n\ndp(i) = cost of putting a 1 at ith index and afterwards\n = (cost of putting a 1 at ith index) + costZeroing(i + 1, i + k - 1) + (costOne(i + k) min costZeroing(i + k, n - 1))\n\nfinal result will be min of (checking each sequence by putting 1 at each i or none at all)\n */\nobject KPeriodicGarland {\n def main(args: Array[String]): Unit = {\n println {\n {\n for (_ <- 1 to io.StdIn.readInt) yield {\n val Array(n, k) = io.StdIn.readLine.split(\" \").map(_.toInt)\n val input = io.StdIn.readLine.map(_ - '0')\n\n val prefixSum = input.scanLeft(0)(_ + _)\n\n val dp = new Array[Int](n) // cost of putting a 1 at ith index\n\n def costOne(i: Int): Int = // cost of putting a 1 at ith index\n if (i >= n) 0 else dp(i)\n\n def costZeroing(l: Int, r: Int): Int = // cost of zeroing between l and r\n if (l >= n || l > r) 0 else prefixSum(n min (r + 1)) - prefixSum(l)\n\n for (i <- n - 1 to 0 by -1)\n dp(i) = (1 ^ input(i)) + costZeroing(i + 1, i + k - 1) + (costOne(i + k) min costZeroing(i + k, n - 1))\n\n val i = (0 until n).minBy(i => dp(i) + costZeroing(0, i - 1))\n (dp(i) + costZeroing(0, i - 1)) min costZeroing(0, n - 1)\n }\n }.mkString(\"\\n\")\n }\n }\n}\n"}], "negative_code": [], "src_uid": "8b28309055f13837eb1f51422fb91029"} {"nl": {"description": "You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai,\u2009bi). How many operations will be performed for each of them?", "input_spec": "The first line contains the number of pairs n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u20091000). Then follow n lines, each line contains a pair of positive integers ai,\u2009bi (1\u2009\u2009\u2264\u2009\u2009ai,\u2009\u2009bi\u2009\u2009\u2264\u2009\u2009109).", "output_spec": "Print the sought number of operations for each pair on a single line.", "sample_inputs": ["2\n4 17\n7 987654321"], "sample_outputs": ["8\n141093479"], "notes": null}, "positive_code": [{"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": "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}"}, {"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": "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"}, {"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"} {"nl": {"description": "Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n\u2009-\u20092 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.", "input_spec": "First line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.", "output_spec": "Output the minimum length of the string that may remain after applying the described operations several times.", "sample_inputs": ["4\n1100", "5\n01010", "8\n11101111"], "sample_outputs": ["0", "1", "6"], "notes": "NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: ."}, "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 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"}, {"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"} {"nl": {"description": "Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n\u2009+\u20091) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i\u2009>\u20090) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k\u2009+\u20091). When the player have made such a move, its energy increases by hk\u2009-\u2009hk\u2009+\u20091 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers h1, h2,\u2009..., hn (1\u2009\u2009\u2264\u2009\u2009hi\u2009\u2009\u2264\u2009\u2009105) representing the heights of the pylons.", "output_spec": "Print a single number representing the minimum number of dollars paid by Caisa.", "sample_inputs": ["5\n3 4 3 2 4", "3\n4 4 4"], "sample_outputs": ["4", "4"], "notes": "NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon."}, "positive_code": [{"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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "This problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $$$s$$$ of length $$$n$$$, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of $$$s[l..r]$$$. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than $$$3$$$ queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed $$$(n+1)^2$$$.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.", "input_spec": "First line contains number $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the length of the picked string.", "output_spec": null, "sample_inputs": ["4\n\na\naa\na\n\ncb\nb\nc\n\nc"], "sample_outputs": ["? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\n\nobject Main extends App {\n val n = readInt()\n\n if (n < 2) {\n println(\"? 1 1\"); Console.flush\n val c = readLine.trim.head\n println(f\"! $c\")\n\n } else {\n\n println(f\"? 1 $n\"); Console.flush\n val ssButOne = collection.mutable.Map[String, Int]()\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim.sorted)\n .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)\n\n println(f\"? 1 ${n - 1}\"); Console.flush\n (1 to (n * (n - 1) / 2))\n .map(_ => readLine.trim.sorted)\n .foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n val remains = ssButOne.keySet.toList.sortBy(_.length)\n /* remains.foreach(x => println(f\"($x)\")) */\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) {\n /* println(\"<\" + s + \">\") */\n s(0)\n } else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB.tail)\n }\n }\n\n val hack = remains\n .foldLeft(List[Char]())((z, s) => {\n /* println(\"[\" + z.mkString + \"]\") */\n extraChar(z, s) :: z\n })\n .mkString\n println(f\"! $hack\")\n }\n}\n\n/* aabc */\n/*\nxyz\nyz\nxy\nz\nx\ny\nzy\nz\ny\n */\n"}], "negative_code": [{"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val n = readInt()\n\n /* query the first */\n println(\"? 1 1\")\n Console.flush\n val cHead = readLine.trim.head\n\n if (n < 2) {\n println(f\"! $cHead\")\n\n } else {\n\n /* query all... */\n println(f\"? 1 $n\")\n Console.flush\n\n var substr2 = ArrayBuffer[String]()\n var substrN = \"\"\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim)\n .foreach(x => {\n if (x.length == 2) substr2 += x\n if (x.length == n) substrN = x\n })\n\n /* println(f\"substr2: $substr2, substrN: $substrN\") */\n\n val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }\n\n def foreachUntil(\n arr: String,\n f: (Char, Int) => Boolean,\n idx: Int = 0\n ): Unit =\n if (!f(arr.head, idx))\n foreachUntil(arr.tail, f, idx + 1)\n\n substr2.foreach(x => {\n val (cA, cB) = (x(0), x(1))\n var iA, iB = -1\n foreachUntil(substrN, (c, i) => {\n if (iA == -1 && c == cA && edges(i).length < 2) {\n iA = i\n } else if (iB == -1 && c == cB && edges(i).length < 2) {\n iB = i\n }\n if (iA != -1 && iB != -1) true\n else false\n })\n edges(iA) += iB\n edges(iB) += iA\n })\n\n /* edges.foreach(x => {\n x.foreach(c => print(c.toString + \" \"))\n println\n }) */\n\n def printHack(curHead: Int): Unit =\n if (edges(curHead).isEmpty) {\n println(substrN(curHead))\n } else {\n print(substrN(curHead))\n val neighbor = edges(curHead)(0)\n edges(curHead).clear\n edges(neighbor) -= curHead\n printHack(neighbor)\n }\n\n var iHead = -1\n foreachUntil(\n substrN,\n (c, i) =>\n if (c == cHead && edges(i).length == 1) {\n iHead = i\n true\n } else false\n )\n /* println(f\"iHead: $iHead\") */\n\n print(\"! \")\n printHack(iHead)\n Console.flush\n }\n}\n\n/* aabc */\n/*\ncb\ncaba\na\ncab\nba\na\naba\nc\naa\nb\n */\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\n\nobject Main extends App {\n val n = readInt()\n\n if (n < 2) {\n println(\"? 1 1\"); Console.flush\n val c = readLine.trim.head\n println(f\"! $c\")\n\n } else {\n\n println(f\"? 1 $n\"); Console.flush\n val ssButOne = collection.mutable.Map[String, Int]()\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim)\n .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)\n\n println(f\"? 1 ${n - 1}\"); Console.flush\n (1 to (n * (n - 1) / 2))\n .map(_ => readLine.trim)\n .foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n val remains = ssButOne.keySet.toList.sortBy(_.length)\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) s(0)\n else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB)\n }\n }\n\n val hack = remains\n .foldLeft(List[Char]())((cArr, s) => extraChar(cArr, s) :: cArr)\n .mkString\n println(f\"! $hack\")\n }\n}\n\n/* aabc */\n/*\ncb\ncaba\na\ncab\nba\na\naba\nc\naa\nb\n */\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val n = readInt()\n\n /* query the first */\n println(f\"? 1 1\")\n Console.flush()\n val cHead = readLine.trim.head\n\n /* query all... */\n println(f\"? 1 $n\")\n Console.flush()\n\n var substr2 = ArrayBuffer[String]()\n var substrN = \"\"\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim)\n .foreach(x => {\n if (x.length == 2) substr2 += x\n else if (x.length == n) substrN = x\n })\n\n val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }\n\n def foreachUntil(arr: String, f: (Char, Int) => Boolean, idx: Int = 0): Unit =\n if (!f(arr.head, idx))\n foreachUntil(arr.tail, f, idx + 1)\n\n substr2.foreach(x => {\n val (cA, cB) = (x(0), x(1))\n var iA, iB = -1\n foreachUntil(substrN, (c, i) => {\n if (iA == -1 && c == cA && edges(i).length < 2) {\n iA = i\n } else if (iB == -1 && c == cB && edges(i).length < 2) {\n iB = i\n }\n if (iA != -1 && iB != -1) true\n else false\n })\n edges(iA) += iB\n edges(iB) += iA\n })\n\n /* edges.foreach(x => {\n x.foreach(c => print(c.toString + \" \"))\n println\n }) */\n\n def printHack(curHead: Int): Unit =\n if (edges(curHead).isEmpty) {\n println(\"! \" + substrN(curHead))\n } else {\n print(substrN(curHead))\n val neighbor = edges(curHead)(0)\n edges(curHead).clear\n edges(neighbor) -= curHead\n printHack(neighbor)\n }\n\n var iHead = -1\n foreachUntil(\n substrN,\n (c, i) =>\n if (c == cHead && edges(i).length == 1) {\n iHead = i\n true\n } else false\n )\n /* println(f\"iHead: $iHead\") */\n\n printHack(iHead)\n}\n\n/* aabc */\n/*\ncb\ncaba\na\ncab\nba\na\naba\nc\naa\nb\n */\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\nimport scala.collection.mutable.Map\n\nobject Main extends App {\n val n = readInt()\n\n if (n < 2) {\n println(\"? 1 1\"); Console.flush\n val c = readLine.trim.head\n println(f\"! $c\")\n\n } else {\n\n println(f\"? 1 $n\"); Console.flush\n val ssButOne = collection.mutable.Map[String, Int]()\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim.sorted)\n .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)\n\n println(f\"? 1 ${n - 1}\"); Console.flush\n (1 to (n * (n - 1) / 2))\n .map(_ => readLine.trim.sorted)\n .foreach(s =>\n ssButOne.getOrElse(s, -1) match {\n case 1 => ssButOne -= s\n case -1 => {}\n case _ @x => ssButOne(s) = x - 1\n }\n )\n\n val remains = ssButOne.keySet.toList.sortBy(_.length)\n\n def extraChar(cArr: List[Char], s: String): Char = {\n if (cArr.isEmpty || s.length == 1) s(0)\n else {\n val i = s.indexOf(cArr.head)\n val (pA, pB) = s.splitAt(i)\n extraChar(cArr.tail, pA ++ pB)\n }\n }\n\n val hack = remains\n .foldLeft(List[Char]())((cArr, s) => extraChar(cArr, s) :: cArr)\n .mkString\n println(f\"! $hack\")\n }\n}\n\n/* aabc */\n/*\ncb\ncaba\na\ncab\nba\na\naba\nc\naa\nb\n */\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val n = readInt()\n\n /* query the first */\n println(\"? 1 1\")\n Console.flush\n val cHead = readLine.trim.head\n\n /* query all... */\n println(f\"? 1 $n\")\n Console.flush\n\n var substr2 = ArrayBuffer[String]()\n var substrN = \"\"\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim)\n .foreach(x => {\n if (x.length == 2) substr2 += x\n else if (x.length == n) substrN = x\n })\n\n val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }\n\n def foreachUntil(arr: String, f: (Char, Int) => Boolean, idx: Int = 0): Unit =\n if (!f(arr.head, idx))\n foreachUntil(arr.tail, f, idx + 1)\n\n substr2.foreach(x => {\n val (cA, cB) = (x(0), x(1))\n var iA, iB = -1\n foreachUntil(substrN, (c, i) => {\n if (iA == -1 && c == cA && edges(i).length < 2) {\n iA = i\n } else if (iB == -1 && c == cB && edges(i).length < 2) {\n iB = i\n }\n if (iA != -1 && iB != -1) true\n else false\n })\n edges(iA) += iB\n edges(iB) += iA\n })\n\n /* edges.foreach(x => {\n x.foreach(c => print(c.toString + \" \"))\n println\n }) */\n\n def printHack(curHead: Int): Unit =\n if (edges(curHead).isEmpty) {\n println(substrN(curHead))\n } else {\n print(substrN(curHead))\n val neighbor = edges(curHead)(0)\n edges(curHead).clear\n edges(neighbor) -= curHead\n printHack(neighbor)\n }\n\n var iHead = -1\n foreachUntil(\n substrN,\n (c, i) =>\n if (c == cHead && edges(i).length == 1) {\n iHead = i\n true\n } else false\n )\n /* println(f\"iHead: $iHead\") */\n\n print(\"! \")\n printHack(iHead)\n Console.flush\n}\n\n/* aabc */\n/*\ncb\ncaba\na\ncab\nba\na\naba\nc\naa\nb\n */\n"}, {"source_code": "import scala.io.StdIn.readInt\nimport scala.io.StdIn.readLine\nimport scala.collection.mutable.ArrayBuffer\n\nobject Main extends App {\n val n = readInt()\n\n /* query the first */\n println(\"? 1 1\")\n Console.flush\n val cHead = readLine.trim.head\n\n /* query all... */\n println(f\"? 1 $n\")\n Console.flush\n\n var substr2 = ArrayBuffer[String]()\n var substrN = \"\"\n (1 to (n * (n + 1) / 2))\n .map(_ => readLine.trim)\n .foreach(x => {\n if (x.length == 2) substr2 += x\n if (x.length == n) substrN = x\n })\n\n /* println(f\"substr2: $substr2, substrN: $substrN\") */\n\n val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }\n\n def foreachUntil(arr: String, f: (Char, Int) => Boolean, idx: Int = 0): Unit =\n if (!f(arr.head, idx))\n foreachUntil(arr.tail, f, idx + 1)\n\n substr2.foreach(x => {\n val (cA, cB) = (x(0), x(1))\n var iA, iB = -1\n foreachUntil(substrN, (c, i) => {\n if (iA == -1 && c == cA && edges(i).length < 2) {\n iA = i\n } else if (iB == -1 && c == cB && edges(i).length < 2) {\n iB = i\n }\n if (iA != -1 && iB != -1) true\n else false\n })\n edges(iA) += iB\n edges(iB) += iA\n })\n\n /* edges.foreach(x => {\n x.foreach(c => print(c.toString + \" \"))\n println\n }) */\n\n def printHack(curHead: Int): Unit =\n if (edges(curHead).isEmpty) {\n println(substrN(curHead))\n } else {\n print(substrN(curHead))\n val neighbor = edges(curHead)(0)\n edges(curHead).clear\n edges(neighbor) -= curHead\n printHack(neighbor)\n }\n\n var iHead = -1\n foreachUntil(\n substrN,\n (c, i) =>\n if (c == cHead && edges(i).length == 1) {\n iHead = i\n true\n } else false\n )\n /* println(f\"iHead: $iHead\") */\n\n print(\"! \")\n printHack(iHead)\n Console.flush\n}\n\n/* aabc */\n/*\ncb\ncaba\na\ncab\nba\na\naba\nc\naa\nb\n */\n"}], "src_uid": "42062b041674530a0d9dcd98d904eb3a"} {"nl": {"description": "The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le 10^6$$$), where $$$p_i$$$\u00a0\u2014 the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \\le y_i \\le x_i \\le n$$$)\u00a0\u2014 the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.", "output_spec": "For each query, print a single integer\u00a0\u2014 the maximum total value of items received for free for one purchase.", "sample_inputs": ["5 3\n5 3 1 5 2\n3 2\n1 1\n5 3"], "sample_outputs": ["8\n5\n6"], "notes": "NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k\u2009>\u20091) if and only if: Its left half equals to its right half. Its left and right halfs are non-empty (k\u2009-\u20091)-palindromes. The left half of string t is its prefix of length \u230a|t|\u2009/\u20092\u230b, and right half\u00a0\u2014 the suffix of the same length. \u230a|t|\u2009/\u20092\u230b denotes the length of string t divided by 2, rounded down.Note that each substring is counted as many times as it appears in the string. For example, in the string \"aaa\" the substring \"a\" appears 3 times.", "input_spec": "The first line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20095000) consisting of lowercase English letters.", "output_spec": "Print |s| integers\u00a0\u2014 palindromic characteristics of string s.", "sample_inputs": ["abba", "abacaba"], "sample_outputs": ["6 1 0 0", "12 4 1 0 0 0 0"], "notes": "NoteIn the first example 1-palindromes are substring \u00aba\u00bb, \u00abb\u00bb, \u00abb\u00bb, \u00aba\u00bb, \u00abbb\u00bb, \u00ababba\u00bb, the substring \u00abbb\u00bb is 2-palindrome. There are no 3- and 4-palindromes here."}, "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 def readLongs(n: Int) = { val tl = 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 = readLine.toCharArray.map(_ - 'a')\n val r = a.reverse\n val n = a.length\n\n val PRIME = 1303L\n val MOD = 1000000007L\n val MODB = BigInt(MOD)\n var pmul = 1L\n\n val ps, pinvs = Array.ofDim[Long](n + 1)\n val hs = Array.ofDim[Long](n + 1)\n\n var h = 0L\n for (i <- 0 to n) {\n ps(i) = pmul\n pinvs(i) = BigInt(pmul).modInverse(MODB).toLong\n hs(i) = h\n if (i < n) h = (h + a(i) * pmul) % MOD\n pmul = pmul * PRIME % MOD\n }\n\n val rps, rpinvs = Array.ofDim[Long](n + 1)\n val rhs = Array.ofDim[Long](n + 1)\n var rpmul = 1L\n\n var rh = 0L\n for (i <- 0 to n) {\n rps(i) = rpmul\n rpinvs(i) = BigInt(rpmul).modInverse(MODB).toLong\n rhs(i) = rh\n if (i < n) rh = (rh + r(i) * rpmul) % MOD\n rpmul = rpmul * PRIME % MOD\n }\n\n def hash(from: Int, to: Int) = (hs(to) - hs(from) + MOD) * pinvs(from) % MOD\n def hashR(from: Int, to: Int) = (rhs(n - from) - rhs(n - to) + MOD) * rpinvs(n - to) % MOD\n\n val pali = Array.fill(n, n){ 0 }\n for (i <- 0 until n) pali(i)(i) = 1\n val res = Array.fill(n){ 0L }\n res(0) = n\n//println(hash(0, 2), hashR(2, 4))\n var len = 2\n while (len <= n) {\n var l = 0\n while (l + len <= n) {\n val half = len / 2\n val r = l + len - 1\n //val mid = l + half\n val hashLeft = hash(l, l + half)\n val hashRight = hashR(r - half + 1, r + 1)\n if (hashLeft == hashRight) {\n pali(l)(r) = pali(l)(l + half - 1) + 1\n //println(len, l, r, half, pali(l)(r))\n res(pali(l)(r) - 1) += 1\n }\n l += 1\n }\n\n len += 1\n }\n\n for (i <- res.indices.reverse) {\n if (i > 0) res(i - 1) += res(i)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n println(res.mkString(\" \"))\n Console.flush\n}\n"}], "negative_code": [], "src_uid": "2612df3281cbb9abe328f82e2d755a08"} {"nl": {"description": "Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.", "input_spec": "The first line contains four integers n, k, a and b (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n)\u00a0\u2014 the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a\u2009+\u2009b\u2009=\u2009n.", "output_spec": "If it is impossible to drink n cups of tea, print \"NO\" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them.", "sample_inputs": ["5 1 3 2", "7 2 2 5", "4 3 4 0"], "sample_outputs": ["GBGBG", "BBGBGBB", "NO"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given two polynomials: P(x)\u2009=\u2009a0\u00b7xn\u2009+\u2009a1\u00b7xn\u2009-\u20091\u2009+\u2009...\u2009+\u2009an\u2009-\u20091\u00b7x\u2009+\u2009an and Q(x)\u2009=\u2009b0\u00b7xm\u2009+\u2009b1\u00b7xm\u2009-\u20091\u2009+\u2009...\u2009+\u2009bm\u2009-\u20091\u00b7x\u2009+\u2009bm. Calculate limit .", "input_spec": "The first line contains two space-separated integers n and m (0\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n\u2009+\u20091 space-separated integers \u2014 the factors of polynomial P(x): a0, a1, ..., an\u2009-\u20091, an (\u2009-\u2009100\u2009\u2264\u2009ai\u2009\u2264\u2009100,\u2009a0\u2009\u2260\u20090). The third line contains m\u2009+\u20091 space-separated integers \u2014 the factors of polynomial Q(x): b0, b1, ..., bm\u2009-\u20091, bm (\u2009-\u2009100\u2009\u2264\u2009bi\u2009\u2264\u2009100,\u2009b0\u2009\u2260\u20090).", "output_spec": "If the limit equals \u2009+\u2009\u221e, print \"Infinity\" (without quotes). If the limit equals \u2009-\u2009\u221e, print \"-Infinity\" (without the quotes). If the value of the limit equals zero, print \"0/1\" (without the quotes). Otherwise, print an irreducible fraction \u2014 the value of limit , in the format \"p/q\" (without the quotes), where p is the \u2014 numerator, q (q\u2009>\u20090) is the denominator of the fraction.", "sample_inputs": ["2 1\n1 1 1\n2 5", "1 0\n-1 3\n2", "0 1\n1\n1 0", "2 2\n2 1 6\n4 5 -7", "1 1\n9 0\n-5 2"], "sample_outputs": ["Infinity", "-Infinity", "0/1", "1/2", "-9/5"], "notes": "NoteLet's consider all samples: You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function"}, "positive_code": [{"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 n, m = scanner nextInt ()\n\t\tval p = (for (i <- 0 to n) yield scanner nextInt ()) toList\n\t\tval q = (for (i <- 0 to m) yield scanner nextInt ()) toList\n\n\t\tif (n > m) {\n\t\t\tif (p(0) * q(0) < 0) print (\"-\")\n\t\t\tprintln (\"Infinity\")\n\t\t} else if (n < m) {\n\t\t\tprintln (\"0/1\")\n\t\t} else {\n\t\t\tval pp = math.abs (p(0))\n\t\t\tval qq = math.abs (q(0))\n\t\t\tval s = if (p(0) * q(0) > 0) 1 else -1\n\t\t\tval g = gcd (pp, qq)\n\t\t\tprint (s * pp / g)\n\t\t\tprint (\"/\")\n\t\t\tprintln (qq / g)\n\t\t}\n }\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"}], "negative_code": [{"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 n, m = scanner nextInt ()\n\t\tval p = (for (i <- 0 to n) yield scanner nextInt ()) toList\n\t\tval q = (for (i <- 0 to m) yield scanner nextInt ()) toList\n\n\t\tif (n > m) {\n\t\t\tif (p(0) < 0) print (\"-\")\n\t\t\tprintln (\"Infinity\")\n\t\t} else if (n < m) {\n\t\t\tprintln (\"0/1\")\n\t\t} else {\n\t\t\tval pp = math.abs (p(0))\n\t\t\tval qq = math.abs (q(0))\n\t\t\tval s = if (p(0) * q(0) > 0) 1 else -1\n\t\t\tval g = gcd (pp, qq)\n\t\t\tprint (s * pp / g)\n\t\t\tprint (\"/\")\n\t\t\tprintln (qq / g)\n\t\t}\n }\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"}], "src_uid": "37cf6edce77238db53d9658bc92b2cab"} {"nl": {"description": "PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n,\u2009k)\u2009=\u20091. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x\u2009=\u20091 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x\u2009+\u2009k or x\u2009+\u2009k\u2009-\u2009n depending on which of these is a valid index of polygon's vertex.Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.", "input_spec": "There are only two numbers in the input: n and k (5\u2009\u2264\u2009n\u2009\u2264\u2009106, 2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009-\u20092, gcd(n,\u2009k)\u2009=\u20091).", "output_spec": "You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.", "sample_inputs": ["5 2", "10 3"], "sample_outputs": ["2 3 5 8 11", "2 3 4 6 9 12 16 21 26 31"], "notes": "NoteThe greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.For the first sample testcase, you should output \"2 3 5 8 11\". Pictures below correspond to situations after drawing lines. "}, "positive_code": [{"source_code": "import java.io._\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.Source\n\nobject ProblemD {\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 nk = line.split(\" \").map(_.toInt)\n val (n, k) = (nk(0), nk(1))\n if (k > n / 2)\n writeSolution(bw, n, n - k) // always cycle around in increasing order, as the algorithm assumes this\n else\n writeSolution(bw, n, k)\n bw.newLine()\n }\n\n def writeSolution(bw: BufferedWriter, n: Int, k: Int): Unit = {\n\n @tailrec\n def writeVertices(currTotal: Long, currCrossings: Long, currX: Long): Unit = {\n val newX = (currX + k - 1) % n + 1\n val crossingAdjustment = if (newX > 1 && newX <= k) 1 else 0\n val newCrossings = currCrossings + crossingAdjustment\n val newTotal = currTotal + 2 * newCrossings + 1 - crossingAdjustment\n bw.write(newTotal.toString)\n bw.write(\" \")\n if (newX != 1) {\n writeVertices(newTotal, newCrossings, newX)\n }\n }\n\n writeVertices(1L, 0L, 1L)\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.io._\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.Source\n\nobject ProblemD {\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 nk = line.split(\" \").map(_.toInt)\n val (n, k) = (nk(0), nk(1))\n writeSolution(bw, n, k)\n bw.newLine()\n }\n\n def writeSolution(bw: BufferedWriter, n: Int, k: Int): Unit = {\n\n @tailrec\n def writeVertices(currTotal: Long, currCrossings: Long, currX: Long): Unit = {\n val newX = (currX + k - 1) % n + 1\n val crossingAdjustment = if (newX > 1 && newX <= k) 1 else 0\n val newCrossings = currCrossings + crossingAdjustment\n val newTotal = currTotal + 2 * newCrossings + 1 - crossingAdjustment\n bw.write(newTotal.toString)\n bw.write(\" \")\n if (newX != 1) {\n writeVertices(newTotal, newCrossings, newX)\n }\n }\n\n writeVertices(1L, 0L, 1L)\n }\n\n}\n"}, {"source_code": "import java.io._\n\nimport scala.annotation.tailrec\nimport scala.collection.mutable\nimport scala.io.Source\n\nobject ProblemD {\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 nk = line.split(\" \").map(_.toInt)\n val (n, k) = (nk(0), nk(1))\n writeSolution(bw, n, k)\n bw.newLine()\n }\n\n def writeSolution(bw: BufferedWriter, n: Int, k: Int): Unit = {\n\n @tailrec\n def writeVertices(currTotal: Long, currCrossings: Long, currX: Int): Unit = {\n val newX = (currX + k - 1) % n + 1\n val crossingAdjustment = if (newX > 1 && newX <= k) 1 else 0\n val newCrossings = currCrossings + crossingAdjustment\n val newTotal = currTotal + 2 * newCrossings + 1 - crossingAdjustment\n bw.write(newTotal.toString)\n bw.write(\" \")\n if (newX != 1) {\n writeVertices(newTotal, currCrossings + crossingAdjustment, newX)\n }\n }\n\n writeVertices(1L, 0L, 1)\n }\n\n}\n"}], "src_uid": "fc82362dbda74396ad6db0d95a0f7acc"} {"nl": {"description": "There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a\u2009\u00d7\u2009b chairs\u00a0\u2014 a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.", "input_spec": "The first line of the input contains three integers n, a and b (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000, 1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009100)\u00a0\u2014 the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.", "output_spec": "If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.", "sample_inputs": ["3 2 2", "8 4 3", "10 2 2"], "sample_outputs": ["0 3\n1 2", "7 8 3\n0 1 4\n6 0 5\n0 2 0", "-1"], "notes": "NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats."}, "positive_code": [{"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": "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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "6e0dafeaf85e92f959c388c72e158f68"} {"nl": {"description": "Reminder: the median of the array $$$[a_1, a_2, \\dots, a_{2k+1}]$$$ of odd number of elements is defined as follows: let $$$[b_1, b_2, \\dots, b_{2k+1}]$$$ be the elements of the array in the sorted order. Then median of this array is equal to $$$b_{k+1}$$$.There are $$$2n$$$ students, the $$$i$$$-th student has skill level $$$a_i$$$. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the $$$2$$$ classes such that each class has odd number of students (not divisible by $$$2$$$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of students halved. The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \\dots, a_{2 n}$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 skill levels of students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.", "sample_inputs": ["3\n1\n1 1\n3\n6 5 4 1 2 3\n5\n13 4 20 13 2 5 8 3 17 16"], "sample_outputs": ["0\n1\n5"], "notes": "NoteIn the first test, there is only one way to partition students\u00a0\u2014 one in each class. The absolute difference of the skill levels will be $$$|1 - 1| = 0$$$.In the second test, one of the possible partitions is to make the first class of students with skill levels $$$[6, 4, 2]$$$, so that the skill level of the first class will be $$$4$$$, and second with $$$[5, 1, 3]$$$, so that the skill level of the second class will be $$$3$$$. Absolute difference will be $$$|4 - 3| = 1$$$.Note that you can't assign like $$$[2, 3]$$$, $$$[6, 5, 4, 1]$$$ or $$$[]$$$, $$$[6, 5, 4, 1, 2, 3]$$$ because classes have even number of students.$$$[2]$$$, $$$[1, 3, 4]$$$ is also not possible because students with skills $$$5$$$ and $$$6$$$ aren't assigned to a class.In the third test you can assign the students in the following way: $$$[3, 4, 13, 13, 20], [2, 5, 8, 16, 17]$$$ or $$$[3, 8, 17], [2, 4, 5, 13, 13, 16, 20]$$$. Both divisions give minimal possible absolute difference."}, "positive_code": [{"source_code": "import java.io.PrintWriter\nimport util.control.Breaks._\n\nobject SolutionB {\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.sorted\n println(math.abs(a(n) - a(n-1)))\n }\n\n def main(args: Array[String]) {\n multiTest(solve)\n //solve()\n }\n}\n"}], "negative_code": [], "src_uid": "adb0f6082367dc432e2e096c64f13a56"} {"nl": {"description": "Bees Alice and Alesya gave beekeeper Polina famous card game \"Set\" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature \u2014 color, number, shape, and shading \u2014 the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called \"Hyperset\". In her game, there are $$$n$$$ cards with $$$k$$$ features, each feature has three possible values: \"S\", \"E\", or \"T\". The original \"Set\" game can be viewed as \"Hyperset\" with $$$k = 4$$$.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.", "input_spec": "The first line of each test contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 1500$$$, $$$1 \\le k \\le 30$$$)\u00a0\u2014 number of cards and number of features. Each of the following $$$n$$$ lines contains a card description: a string consisting of $$$k$$$ letters \"S\", \"E\", \"T\". The $$$i$$$-th character of this string decribes the $$$i$$$-th feature of that card. All cards are distinct.", "output_spec": "Output a single integer\u00a0\u2014 the number of ways to choose three cards that form a set.", "sample_inputs": ["3 3\nSET\nETS\nTSE", "3 4\nSETE\nETSE\nTSES", "5 4\nSETT\nTEST\nEEET\nESTE\nSTES"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the third example test, these two triples of cards are sets: \"SETT\", \"TEST\", \"EEET\" \"TEST\", \"ESTE\", \"STES\" "}, "positive_code": [{"source_code": "import scala.util.Random\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, k) = stdin.next().split(' ').map(_.toInt)\n// val n = 1001\n// val k = 11\n// val r = new Random(10)\n val cards = stdin.take(n).map(_.toCharArray.toSeq).toArray\n// val cards = (0 to n).map(_ => rString(r, k).toCharArray.toSeq).toArray\n val set = cards.zipWithIndex.toMap\n val lSet = List[Char] ('S', 'E', 'T')\n\n\n// println(\"start measure\")\n// val t0 = System.nanoTime()\n\n var res = 0\n for (i <- 0 until n - 2; j <- i + 1 until n - 1) {\n val str = (0 until k).map(z => nextL(cards(i)(z), cards(j)(z)))\n res = res + set.get(str).count(x => x > j)\n }\n println(res)\n// val t1 = System.nanoTime()\n// println(\"Elapsed time: \" + (t1 - t0) / 1000000000d + \"s\")\n\n def nextL(ch1: Char, ch2: Char) = {\n if (ch1 == ch2) ch1\n else if (ch1 == 'S') {\n if (ch2 == 'E') 'T'\n else 'E'\n }\n else if (ch1 == 'E') {\n if (ch2 == 'S') 'T'\n else 'S'\n }\n else if (ch2 == 'S') 'E'\n else 'S'\n }\n\n def rString(r: Random, length: Int) = {\n (0 to n).map(_ => r.nextInt(3)).map{\n case 0 => 'S'\n case 1 => 'E'\n case 2 => 'T'\n }.mkString(\"\")\n }\n\n\n}\n\n"}], "negative_code": [{"source_code": "import scala.util.Random\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, k) = stdin.next().split(' ').map(_.toInt)\n// val n = 1001\n// val k = 11\n// val r = new Random(10)\n val cards = stdin.take(n).map(_.toCharArray.toSeq).toArray\n// val cards = (0 to n).map(_ => rString(r, k).toCharArray.toSeq).toArray\n val set = cards.zipWithIndex.toMap\n val lSet = List[Char] ('S', 'E', 'T')\n\n\n// println(\"start measure\")\n// val t0 = System.nanoTime()\n\n var res = 0\n for (i <- 0 until n - 2; j <- i + 1 until n - 1) {\n val str = (0 until k).map(z => nextL(cards(i)(z), cards(j)(z)))\n res = res + set.get(str).count(x => x > j)\n }\n// println(res)\n// val t1 = System.nanoTime()\n// println(\"Elapsed time: \" + (t1 - t0) / 1000000000d + \"s\")\n\n def nextL(ch1: Char, ch2: Char) = {\n if (ch1 == ch2) ch1\n else if (ch1 == 'S') {\n if (ch2 == 'E') 'T'\n else 'E'\n }\n else if (ch1 == 'E') {\n if (ch2 == 'S') 'T'\n else 'S'\n }\n else if (ch2 == 'S') 'E'\n else 'S'\n }\n\n def rString(r: Random, length: Int) = {\n (0 to n).map(_ => r.nextInt(3)).map{\n case 0 => 'S'\n case 1 => 'E'\n case 2 => 'T'\n }.mkString(\"\")\n }\n\n\n}\n\n"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, k) = stdin.next().split(' ').map(_.toInt)\n val cards = stdin.take(n).toArray\n val set = cards.toSet\n val lSet = List[Char] ('S', 'E', 'T')\n if (n < 3) {\n println(0)\n }\n else {\n var r = 0\n for (i <- Range(0, n - 2); j <- Range(i + 1, n - 1))\n r = r + (if (set.contains(cards(i).zip(cards(j)).map{case(a, b) => if (a == b) a else lSet.find(p => p != a && p != b).get}.toString()) )1 else 0)\n println(r)\n }\n}\n\n"}, {"source_code": "object Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, k) = stdin.next().split(' ').map(_.toInt)\n val cards = stdin.take(n).toArray\n val set = cards.toSet\n val lSet = List[Char] ('S', 'E', 'T')\n if (n < 3) {\n println(0)\n }\n else {\n var r = 0\n for (i <- Range(0, n - 2); j <- Range(i + 1, n - 1)) {\n r = r + (if (set.contains(cards(i).zip(cards(j)).map{case(a, b) => if (a == b) a else lSet.find(p => p != a && p != b).get}.mkString(\"\")) )1 else 0)\n }\n println(r)\n }\n}\n\n"}, {"source_code": "import scala.collection.mutable\n\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(n, k) = stdin.next().split(' ').map(_.toInt)\n val cards = stdin.take(n).toArray\n if (n < 3) {\n println(0)\n }\n else {\n var r = 0\n for (i <- Range(0, n - n - 2); j <- Range(i + 1, n - 1); z <- Range(j + 1, n))\n r = r + (if (solution(i, j, z)) 1 else 0)\n println(r)\n }\n\n\n def solution(i: Int, j: Int, z: Int): Boolean = {\n cards(i).zip(cards(j)).zip(cards(z)).forall{case ((a, b), c) => (a == b && b == c) || (a != b && b != c && a != c) }\n }\n}\n\n\n// 5 11 2\n// 2 3 4 5 7\n\n"}], "src_uid": "ae7c80e068e267673a5f910bb0b121ec"} {"nl": {"description": "ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n\u2009\u00d7\u2009n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal\u00a0\u2014 and the secondary diagonal\u00a0\u2014 ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500)\u00a0\u2014 the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai,\u2009j (1\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u2009109 or ai,\u2009j\u2009=\u20090), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai,\u2009j will be equal to 0. Otherwise, ai,\u2009j is positive. It is guaranteed that there is exactly one pair of integers i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n) such that ai,\u2009j\u2009=\u20090.", "output_spec": "Output a single integer, the positive integer x (1\u2009\u2264\u2009x\u2009\u2264\u20091018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output \u2009-\u20091 instead. If there are multiple solutions, you may print any of them.", "sample_inputs": ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"], "sample_outputs": ["9", "1", "-1"], "notes": "NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4\u2009+\u20099\u2009+\u20092\u2009=\u20093\u2009+\u20095\u2009+\u20097\u2009=\u20098\u2009+\u20091\u2009+\u20096\u2009=\u200915.The sum of numbers in each column is:4\u2009+\u20093\u2009+\u20098\u2009=\u20099\u2009+\u20095\u2009+\u20091\u2009=\u20092\u2009+\u20097\u2009+\u20096\u2009=\u200915.The sum of numbers in the two diagonals is:4\u2009+\u20095\u2009+\u20096\u2009=\u20092\u2009+\u20095\u2009+\u20098\u2009=\u200915.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square."}, "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 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"}, {"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 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": "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"} {"nl": {"description": "At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $$$k$$$ flowers.The work material for the wreaths for all $$$n$$$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$, where $$$a_i$$$ is an integer that denotes the type of flower at the position $$$i$$$. This year the liana is very long ($$$m \\ge n \\cdot k$$$), and that means every citizen will get a wreath.Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $$$k$$$ flowers from the beginning of the liana, then another $$$k$$$ flowers and so on. Each such piece of $$$k$$$ flowers is called a workpiece. The machine works until there are less than $$$k$$$ flowers on the liana.Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $$$k$$$ flowers must contain flowers of types $$$b_1$$$, $$$b_2$$$, ..., $$$b_s$$$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $$$n$$$ workpieces?", "input_spec": "The first line contains four integers $$$m$$$, $$$k$$$, $$$n$$$ and $$$s$$$ ($$$1 \\le n, k, m \\le 5 \\cdot 10^5$$$, $$$k \\cdot n \\le m$$$, $$$1 \\le s \\le k$$$): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively. The second line contains $$$m$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$ ($$$1 \\le a_i \\le 5 \\cdot 10^5$$$) \u00a0\u2014 types of flowers on the liana. The third line contains $$$s$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_s$$$ ($$$1 \\le b_i \\le 5 \\cdot 10^5$$$) \u00a0\u2014 the sequence in Diana's schematic.", "output_spec": "If it's impossible to remove some of the flowers so that there would be at least $$$n$$$ workpieces and at least one of them fullfills Diana's schematic requirements, output $$$-1$$$. Otherwise in the first line output one integer $$$d$$$ \u00a0\u2014 the number of flowers to be removed by Diana. In the next line output $$$d$$$ different integers \u00a0\u2014 the positions of the flowers to be removed. If there are multiple answers, print any.", "sample_inputs": ["7 3 2 2\n1 2 3 3 2 1 2\n2 2", "13 4 3 3\n3 2 6 4 1 4 4 7 1 3 3 2 4\n4 3 4", "13 4 1 3\n3 2 6 4 1 4 4 7 1 3 3 2 4\n4 3 4"], "sample_outputs": ["1\n4", "-1", "9\n1 2 3 4 5 9 11 12 13"], "notes": "NoteIn the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$. Those workpieces don't fit Diana's schematic. But if you remove flower on $$$4$$$-th place, the machine would output workpieces $$$[1, 2, 3]$$$ and $$$[2, 1, 2]$$$. The second workpiece fits Diana's schematic.In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs."}, "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 M, K, N, S = ni()\n val A = na(M)\n val B = na(S)\n\n val cnt = Array.ofDim[Int](5e5.toInt + 1)\n val needs = Array.ofDim[Int](5e5.toInt + 1)\n REP(S) { i =>\n needs(B(i)) += 1\n }\n var matched = 0\n\n var r = -1\n REP(M) { l =>\n while(r + 1 < M && (matched < S || r - l + 1 < K)) {\n r += 1\n if (needs(A(r)) > 0) {\n cnt(A(r)) += 1\n if (cnt(A(r)) <= needs(A(r))) matched += 1\n }\n }\n\n debug(s\"[$l,$r] matched:$matched\")\n\n if (matched == S && r - l + 1 >= K) {\n val lim = M - K * N\n val minus_cur = (r - l + 1) - K\n val minus_l = l % K\n val minus = minus_cur + minus_l\n val cond1 = lim >= minus\n\n val cnt_l = l / K\n val cnt_r = (M - r - 1) / K\n// debug(s\"cnt_r:$cnt_r\")\n val cond2 = cnt_l + cnt_r + 1 >= N\n if (cond1 && cond2) {\n out.println(minus)\n // \u5de6\u5074\u306e\u4eba\u305f\u3061\u306fmod\u8abf\u7bc0\u306e\u305f\u3081\u306a\u306e\u3067\u3060\u308c\u3092\u6d88\u3057\u3066\u3082\u3044\u3044 R\n REP(minus_l) { i =>\n out.print(i + 1)\n }\n\n Arrays.fill(cnt, 0)\n var deleted = 0\n TO(l, r) { i =>\n if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {\n cnt(A(i)) += 1\n } else if (deleted < minus_cur) {\n if (deleted > 0 || minus_l > 0) out.print(\" \")\n out.print(i + 1)\n deleted += 1\n }\n }\n out.println()\n\n return\n }\n }\n\n if (needs(A(l)) > 0) {\n if (cnt(A(l)) <= needs(A(l))) matched -= 1\n cnt(A(l)) -= 1\n }\n }\n\n out.println(-1)\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": "object Main {\n def main(args: Array[String]): Unit = {\n val s = 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 M, K, N, S = ni()\n val A = na(M)\n val B = na(S)\n\n val cnt = Array.ofDim[Int](5e5.toInt + 1)\n val needs = Array.ofDim[Int](5e5.toInt + 1)\n REP(S) { i =>\n needs(B(i)) += 1\n }\n var matched = 0\n\n var r = -1\n REP(M) { l =>\n while(r + 1 < M && matched < S) {\n r += 1\n if (needs(A(r)) > 0) {\n cnt(A(r)) += 1\n if (cnt(A(r)) <= needs(A(r))) matched += 1\n }\n }\n\n if (matched == S) {\n val lim = M - K * N\n val minus_cur = (r - l + 1) - K\n val minus_l = l % K\n val minus = minus_cur + minus_l\n val cond1 = lim >= minus\n\n val cnt_l = l / K\n val cnt_r = (M - r - 1) / K\n// debug(s\"cnt_r:$cnt_r\")\n val cond2 = cnt_l + cnt_r + 1 >= N\n if (cond1 && cond2) {\n out.println(minus)\n // \u5de6\u5074\u306e\u4eba\u305f\u3061\u306fmod\u8abf\u7bc0\u306e\u305f\u3081\u306a\u306e\u3067\u3060\u308c\u3092\u6d88\u3057\u3066\u3082\u3044\u3044 R\n REP(minus_l) { i =>\n out.print(i + 1)\n }\n\n Arrays.fill(cnt, 0)\n var deleted = 0\n TO(l, r) { i =>\n if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {\n cnt(A(i)) += 1\n } else if (deleted < minus_cur) {\n if (deleted > 0 || minus_l > 0) out.print(\" \")\n out.print(i + 1)\n deleted += 1\n }\n }\n out.println()\n\n return\n }\n }\n\n if (needs(A(l)) > 0) {\n if (cnt(A(l)) <= needs(A(l))) matched -= 1\n cnt(A(l)) -= 1\n }\n }\n\n out.println(-1)\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 Main {\n def main(args: Array[String]): Unit = {\n val s = 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 M, K, N, S = ni()\n val A = na(M)\n val B = na(S)\n\n val cnt = Array.ofDim[Int](5e5.toInt + 1)\n val needs = Array.ofDim[Int](5e5.toInt + 1)\n REP(S) { i =>\n needs(B(i)) += 1\n }\n var matched = 0\n\n var r = 0\n REP(M) { l =>\n while(r + 1 < M && matched < S) {\n r += 1\n if (needs(A(r)) > 0) {\n cnt(A(r)) += 1\n if (cnt(A(r)) <= needs(A(r))) matched += 1\n }\n }\n\n if (matched == S) {\n val lim = M - K * N\n val minus_cur = (r - l + 1) - K\n val minus_l = l % K\n val minus = minus_cur + minus_l\n val cond1 = lim >= minus\n\n val cnt_l = l / K\n val cnt_r = (M - r - 1) / K\n// debug(s\"cnt_r:$cnt_r\")\n val cond2 = cnt_l + cnt_r + 1 >= N\n if (cond1 && cond2) {\n out.println(minus)\n // \u5de6\u5074\u306e\u4eba\u305f\u3061\u306fmod\u8abf\u7bc0\u306e\u305f\u3081\u306a\u306e\u3067\u3060\u308c\u3092\u6d88\u3057\u3066\u3082\u3044\u3044 R\n REP(minus_l) { i =>\n out.print(i + 1)\n }\n\n Arrays.fill(cnt, 0)\n var deleted = 0\n TO(l, r) { i =>\n if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {\n cnt(A(i)) += 1\n } else if (deleted < minus_cur) {\n if (deleted > 0 || minus_l > 0) out.print(\" \")\n out.print(i + 1)\n deleted += 1\n }\n }\n out.println()\n\n return\n }\n }\n\n if (needs(A(l)) > 0) {\n if (cnt(A(l)) <= needs(A(l))) matched -= 1\n cnt(A(l)) -= 1\n }\n }\n\n out.println(-1)\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 Main {\n def main(args: Array[String]): Unit = {\n val s = 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 M, K, N, S = ni()\n val A = na(M)\n val B = na(S)\n\n val cnt = Array.ofDim[Int](5e5.toInt + 1)\n val needs = Array.ofDim[Int](5e5.toInt + 1)\n REP(S) { i =>\n needs(B(i)) += 1\n }\n var matched = 0\n\n var r = 0\n REP(M) { l =>\n while(r + 1 < M && matched < S) {\n r += 1\n if (needs(A(r)) > 0) {\n cnt(A(r)) += 1\n if (cnt(A(r)) <= needs(A(r))) matched += 1\n }\n }\n\n if (matched == S) {\n val lim = M - K * N\n val minus_cur = (r - l + 1) - K\n val minus_l = l % K\n val minus = minus_cur + minus_l\n val cond1 = lim >= minus\n\n val cnt_l = l / K\n val cnt_r = (M - r - 1) / K\n// debug(s\"cnt_r:$cnt_r\")\n val cond2 = cnt_l + cnt_r + 1 >= N\n if (cond1 && cond2) {\n out.println(minus)\n // \u5de6\u5074\u306e\u4eba\u305f\u3061\u306fmod\u8abf\u7bc0\u306e\u305f\u3081\u306a\u306e\u3067\u3060\u308c\u3092\u6d88\u3057\u3066\u3082\u3044\u3044 R\n REP(minus_l) { i =>\n out.println(i + 1)\n }\n\n Arrays.fill(cnt, 0)\n var deleted = 0\n TO(l, r) { i =>\n if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {\n cnt(A(i)) += 1\n } else if (deleted < minus_cur) {\n if (deleted > 0) out.print(\" \")\n out.print(i + 1)\n deleted += 1\n }\n }\n out.println()\n\n return\n }\n }\n\n if (needs(A(l)) > 0) {\n if (cnt(A(l)) <= needs(A(l))) matched -= 1\n cnt(A(l)) -= 1\n }\n }\n\n out.println(-1)\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 Main {\n def main(args: Array[String]): Unit = {\n val s = 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 M, K, N, S = ni()\n val A = na(M)\n val B = na(S)\n\n val cnt = Array.ofDim[Int](5e5.toInt + 1)\n val needs = Array.ofDim[Int](5e5.toInt + 1)\n REP(S) { i =>\n needs(B(i)) += 1\n }\n var matched = 0\n\n var r = 0\n REP(M) { l =>\n while(r + 1 < M && matched < S) {\n r += 1\n if (needs(A(r)) > 0) {\n cnt(A(r)) += 1\n if (cnt(A(r)) <= needs(A(r))) matched += 1\n }\n }\n\n if (matched == S) {\n val lim = M - K * N\n val minus_cur = (r - l + 1) - K\n val minus_l = l % K\n val minus = minus_cur + minus_l\n val cond1 = lim >= minus\n\n val cnt_l = l / K\n val cnt_r = (M - r) / K\n val cond2 = cnt_l + cnt_r + 1 >= N\n if (cond1 && cond2) {\n out.println(minus)\n // \u5de6\u5074\u306e\u4eba\u305f\u3061\u306fmod\u8abf\u7bc0\u306e\u305f\u3081\u306a\u306e\u3067\u3060\u308c\u3092\u6d88\u3057\u3066\u3082\u3044\u3044\n REP(minus_l) { i =>\n out.println(i + 1)\n }\n\n Arrays.fill(cnt, 0)\n var deleted = 0\n TO(l, r) { i =>\n if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {\n cnt(A(i)) += 1\n } else if (deleted < minus_cur) {\n if (deleted > 0) out.print(\" \")\n out.print(i + 1)\n deleted += 1\n }\n }\n out.println()\n\n return\n }\n }\n\n if (needs(A(l)) > 0) {\n if (cnt(A(l)) <= needs(A(l))) matched -= 1\n cnt(A(l)) -= 1\n }\n }\n\n out.println(-1)\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"}], "src_uid": "fdc491122e3895f1fe3fcdccf657fa26"} {"nl": {"description": "Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net \"TheContacnt!\".Not all students are equally sociable. About each student you know the value ai \u2014 the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that: the student i sends no more than ai messages (for all i from 1 to n); all students knew the news about the credit (initially only Polycarp knew it); the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above. ", "input_spec": "The first line contains the positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of students. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.", "output_spec": "Print -1 to the first line if it is impossible to inform all students about credit. Otherwise, in the first line print the integer k \u2014 the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit. If there are several answers, it is acceptable to print any of them. ", "sample_inputs": ["4\n1 2 1 0", "6\n2 0 1 3 2 0", "3\n0 2 2"], "sample_outputs": ["3\n1 2\n2 4\n2 3", "6\n1 3\n3 4\n1 2\n4 5\n5 6\n4 6", "-1"], "notes": "NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit. "}, "positive_code": [{"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"}, {"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 -- \u0447\u0438\u0441\u043b\u043e \u043e\u0441\u0442\u0430\u0432\u0448\u0438\u0445\u0441\u044f \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439 \u0443 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u044e\u0449\u0435\u0433\u043e\n * sends -- \u0441\u043f\u0438\u0441\u043e\u043a \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u044e\u0449\u0438\u0445. \u0415\u0441\u043b\u0438 \u0441\u0442\u0443\u0434\u0435\u043d\u0442 \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u043e\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c, \u043e\u043d \u0438\u0441\u043a\u044e\u0447\u0430\u0435\u0442\u0441\u044f \u0438\u0437 \u0441\u043f\u0438\u0441\u043a\u0430 \u043e\u0442\u043f\u0440..\n * \t\t\t\t \u0418\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e \u043e\u0434\u0438\u043d \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u044e\u0449\u0438\u0439: \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f.\n * newSends -- \u043d\u043e\u0432\u044b\u0439 \u0441\u043f\u0438\u0441\u043e\u043a \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u044e\u0449\u0438\u0445.\n * k -- \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u0442\u0443\u0434\u0435\u043d\u0442\u043e\u0432, \u043f\u043e\u043b\u0443\u0447\u0438\u0432\u0448\u0438\u0445 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435, \u0432\u043a\u043b\u044e\u0447\u0430\u044f \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430\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"} {"nl": {"description": "The term of this problem is the same as the previous one, the only exception \u2014 increased restrictions.", "input_spec": "The first line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.", "output_spec": "Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.", "sample_inputs": ["1 1000000000\n1\n1000000000", "10 1\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1 1 1 1 1", "3 1\n2 1 4\n11 3 16", "4 3\n4 3 5 6\n11 12 14 20"], "sample_outputs": ["2000000000", "0", "4", "3"], "notes": null}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.", "input_spec": "The first line contains two integers N and K (0\u2009\u2264\u2009N\u2009\u2264\u20091018, 1\u2009\u2264\u2009K\u2009\u2264\u2009105)\u00a0\u2014 the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1\u2009\u2264\u2009ai\u2009\u2264\u20091018 for all i)\u00a0\u2014 the capacities of boxes.", "output_spec": "Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.", "sample_inputs": ["19 3\n5 4 10", "28 3\n5 6 30"], "sample_outputs": ["2 4", "1 5"], "notes": null}, "positive_code": [{"source_code": "object CF939B extends App{\n val sc = new java.util.Scanner(System.in)\n val n = sc.nextLong\n val k = sc.nextInt\n val a = Seq.fill[Long](k)(sc.nextLong)\n val boxes = a map (ak => (n/ak, n%ak))\n val leave = (boxes map (_._2)) min\n val box = (boxes.zipWithIndex filter (_._1._2 == leave)).head\n println(\"%d %d\".format(box._2 + 1, box._1._1))\n}"}], "negative_code": [], "src_uid": "8e36566b5e0c74730ea118e23b030778"} {"nl": {"description": "Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink \"Beecola\", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of \"Beecola\".", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009100\u2009000)\u00a0\u2014 prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1\u2009\u2264\u2009mi\u2009\u2264\u2009109)\u00a0\u2014 the number of coins Vasiliy can spent on the i-th day.", "output_spec": "Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.", "sample_inputs": ["5\n3 10 8 6 11\n4\n1\n10\n3\n11"], "sample_outputs": ["0\n4\n1\n5"], "notes": "NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop."}, "positive_code": [{"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}"}, {"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 \u043c\u0441 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"} {"nl": {"description": "Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n.Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n\u2009-\u2009i to this cell. In other words, for each cell you've got to find the distance to cell n.Let's denote the value that is written in the i-th cell as ai. Initially, ai\u2009=\u20091 (1\u2009\u2264\u2009i\u2009<\u2009n) and an\u2009=\u20090. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously).The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n). All processors simultaneously execute operation ai\u2009=\u2009ai\u2009+\u2009aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n\u2009-\u2009i.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009104,\u20091\u2009\u2264\u2009k\u2009\u2264\u200920). It is guaranteed that at the given n and k the required sequence of operations exists.", "output_spec": "Print exactly n\u00b7k integers in k lines. In the first line print numbers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n\u2009-\u2009i.", "sample_inputs": ["1 1", "3 2"], "sample_outputs": ["1", "2 3 3\n3 3 3"], "notes": null}, "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": "/*\nD. \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0423 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0430 \u0435\u0441\u0442\u044c \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440 \u0441 n \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440\u0430\u043c\u0438. \u0422\u0430\u043a\u0436\u0435 \u0432 \u0435\u0433\u043e \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0435 \u0435\u0441\u0442\u044c n \u044f\u0447\u0435\u0435\u043a \u043f\u0430\u043c\u044f\u0442\u0438. \u0411\u0443\u0434\u0435\u043c \u0441\u0447\u0438\u0442\u0430\u0442\u044c, \u0447\u0442\u043e \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440\u044b \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u0446\u0435\u043b\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u043e\u0442 1 \u0434\u043e n \u0438 \u0447\u0442\u043e \u044f\u0447\u0435\u0439\u043a\u0438 \u043f\u0430\u043c\u044f\u0442\u0438 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u0446\u0435\u043b\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u043e\u0442 1 \u0434\u043e n.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u043d\u0443\u0436\u043d\u043e \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043c\u043e\u0434\u0435\u043b\u044c \u043f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u043e\u0439 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u044f\u0447\u0435\u0439\u043a\u0438 \u043f\u0430\u043c\u044f\u0442\u0438 \u0441 \u043d\u043e\u043c\u0435\u0440\u043e\u043c i \u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u0442 \u0432 \u044d\u0442\u0443 \u044f\u0447\u0435\u0439\u043a\u0443 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 n\u2009-\u2009i. \u0414\u0440\u0443\u0433\u0438\u043c\u0438 \u0441\u043b\u043e\u0432\u0430\u043c\u0438, \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u044f\u0447\u0435\u0439\u043a\u0438 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u043d\u0430\u0439\u0442\u0438 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u0434\u043e \u044f\u0447\u0435\u0439\u043a\u0438 n.\n\n\u041e\u0431\u043e\u0437\u043d\u0430\u0447\u0438\u043c, \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043d\u043e\u0435 \u0432 i-\u0442\u043e\u0439 \u044f\u0447\u0435\u0439\u043a\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043a\u0430\u043a ai. \u0418\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e, ai\u2009=\u20091 (1\u2009\u2264\u2009i\u2009<\u2009n) \u0438 an\u2009=\u20090. \u0411\u0443\u0434\u0435\u043c \u0441\u0447\u0438\u0442\u0430\u0442\u044c, \u0447\u0442\u043e \u0432 \u044f\u0447\u0435\u0439\u043a\u0443 \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u043e\u043c\u0435\u0440 i \u043c\u043e\u0436\u0435\u0442 \u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043b\u0438\u0448\u044c \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440 i. \u0427\u0438\u0442\u0430\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u044f\u0447\u0435\u0439\u043a\u0438 \u043c\u043e\u0436\u0435\u0442 \u043b\u044e\u0431\u043e\u0439 \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440 (\u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0440\u0430\u0437\u043d\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440\u043e\u0432 \u043c\u043e\u0433\u0443\u0442 \u0447\u0438\u0442\u0430\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0438\u0437 \u044f\u0447\u0435\u0439\u043a\u0438 \u043e\u0434\u043d\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e).\n\n\u0418\u0441\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u043e\u0439 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442 \u0432 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0448\u0430\u0433\u043e\u0432. \u041d\u0430 \u043a\u0430\u0436\u0434\u043e\u043c \u0448\u0430\u0433\u0435 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442 \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u043e\u0439 \u0432\u0435\u0440\u0441\u0438\u0438 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u0438\u043d\u043a\u0440\u0435\u043c\u0435\u043d\u0442\u0430. \u0412\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u043e\u0439 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u0438\u043d\u043a\u0440\u0435\u043c\u0435\u043d\u0442\u0430 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c:\n\n \u041a\u0430\u0436\u0434\u044b\u0439 \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440 \u043d\u0435\u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e \u043e\u0442 \u0434\u0440\u0443\u0433\u0438\u0445 \u0432\u044b\u0431\u0438\u0440\u0430\u0435\u0442 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u0443\u044e \u044f\u0447\u0435\u0439\u043a\u0443 \u043f\u0430\u043c\u044f\u0442\u0438. \u041f\u0443\u0441\u0442\u044c \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440 i \u0432\u044b\u0431\u0440\u0430\u043b \u044f\u0447\u0435\u0439\u043a\u0443 \u0441 \u043d\u043e\u043c\u0435\u0440\u043e\u043c ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n).\n \u0412\u0441\u0435 \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440\u044b \u043e\u0434\u043d\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u044e\u0442 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e, ai\u2009=\u2009ai\u2009+\u2009aci. \n\n\u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443 \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043c\u043e\u0434\u0435\u043b\u044c \u043f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u043e\u0439 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u0442\u0441\u044f \u0440\u043e\u0432\u043d\u043e \u0432 k \u0448\u0430\u0433\u043e\u0432. \u0412\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u0435, \u043a\u0430\u043a\u0438\u0435 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u043d\u0443\u0436\u043d\u043e \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u0441\u043b\u0435 \u0440\u043e\u0432\u043d\u043e k \u0448\u0430\u0433\u043e\u0432 \u0434\u043b\u044f \u0432\u0441\u0435\u0445 i \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 ai \u0431\u044b\u043b\u043e \u0440\u0430\u0432\u043d\u043e n\u2009-\u2009i.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 n \u0438 k (1\u2009\u2264\u2009n\u2009\u2264\u2009104,\u20091\u2009\u2264\u2009k\u2009\u2264\u200920).\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043f\u0440\u0438 \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0445 n \u0438 k \u0442\u0440\u0435\u0431\u0443\u0435\u043c\u0430\u044f \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0439 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u043e\u0432\u043d\u043e n\u00b7k \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0432 k \u0441\u0442\u0440\u043e\u043a\u0430\u0445. \u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u043e\u043c\u0435\u0440\u0430 c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) \u0434\u043b\u044f \u043f\u0435\u0440\u0432\u043e\u0439 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u0438\u043d\u043a\u0440\u0435\u043c\u0435\u043d\u0442\u0430. \u0412\u043e \u0432\u0442\u043e\u0440\u043e\u0439 \u2014 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u043e\u043c\u0435\u0440\u0430 \u0434\u043b\u044f \u0432\u0442\u043e\u0440\u043e\u0439 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u0438\u043d\u043a\u0440\u0435\u043c\u0435\u043d\u0442\u0430. \u0412 k-\u043e\u0439 \u2014 \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u043e\u043c\u0435\u0440\u0430 \u0434\u043b\u044f k-\u043e\u0439 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u0438\u043d\u043a\u0440\u0435\u043c\u0435\u043d\u0442\u0430.\n\n\u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u0432\u044b\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0445 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0439 \u0434\u043b\u044f \u043b\u044e\u0431\u043e\u0433\u043e i \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 ai \u0434\u043e\u043b\u0436\u043d\u043e \u0431\u044b\u0442\u044c \u0440\u0430\u0432\u043d\u043e n\u2009-\u2009i.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n3 2\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\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}"}, {"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"} {"nl": {"description": "Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $$$l$$$ centimeters after haircut, where $$$l$$$ is her favorite number. Suppose, that the Alice's head is a straight line on which $$$n$$$ hairlines grow. Let's number them from $$$1$$$ to $$$n$$$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $$$l$$$, given that all hairlines on that segment had length strictly greater than $$$l$$$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types: $$$0$$$\u00a0\u2014 Alice asks how much time the haircut would take if she would go to the hairdresser now. $$$1$$$ $$$p$$$ $$$d$$$\u00a0\u2014 $$$p$$$-th hairline grows by $$$d$$$ centimeters. Note, that in the request $$$0$$$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$l$$$ ($$$1 \\le n, m \\le 100\\,000$$$, $$$1 \\le l \\le 10^9$$$)\u00a0\u2014 the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the initial lengths of all hairlines of Alice. Each of the following $$$m$$$ lines contains a request in the format described in the statement. The request description starts with an integer $$$t_i$$$. If $$$t_i = 0$$$, then you need to find the time the haircut would take. Otherwise, $$$t_i = 1$$$ and in this moment one hairline grows. The rest of the line than contains two more integers: $$$p_i$$$ and $$$d_i$$$ ($$$1 \\le p_i \\le n$$$, $$$1 \\le d_i \\le 10^9$$$)\u00a0\u2014 the number of the hairline and the length it grows by.", "output_spec": "For each query of type $$$0$$$ print the time the haircut would take.", "sample_inputs": ["4 7 3\n1 2 3 4\n0\n1 2 3\n0\n1 1 3\n0\n1 3 1\n0"], "sample_outputs": ["1\n2\n2\n1"], "notes": "NoteConsider the first example: Initially lengths of hairlines are equal to $$$1, 2, 3, 4$$$ and only $$$4$$$-th hairline is longer $$$l=3$$$, and hairdresser can cut it in $$$1$$$ second. Then Alice's second hairline grows, the lengths of hairlines are now equal to $$$1, 5, 3, 4$$$ Now haircut takes two seonds: two swings are required: for the $$$4$$$-th hairline and for the $$$2$$$-nd. Then Alice's first hairline grows, the lengths of hairlines are now equal to $$$4, 5, 3, 4$$$ The haircut still takes two seconds: with one swing hairdresser can cut $$$4$$$-th hairline and with one more swing cut the segment from $$$1$$$-st to $$$2$$$-nd hairline. Then Alice's third hairline grows, the lengths of hairlines are now equal to $$$4, 5, 4, 4$$$ Now haircut takes only one second: with one swing it is possible to cut the segment from $$$1$$$-st hairline to the $$$4$$$-th. "}, "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}"}, {"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"}], "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"} {"nl": {"description": "Om Nom is the main character of a game \"Cut the Rope\". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n\u2009+\u20091\u2009-\u20091 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n,\u20092n\u2009+\u20091,\u2009...,\u20092n\u2009+\u20091\u2009-\u20091 and these exits lead straight to the Om Nom friends' houses. From each square i (2\u2009\u2264\u2009i\u2009<\u20092n\u2009+\u20091) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910) \u2014 the number of roads on the path from the entrance to any exit. The next line contains 2n\u2009+\u20091\u2009-\u20092 numbers a2,\u2009a3,\u2009... a2n\u2009+\u20091\u2009-\u20091 \u2014 the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.", "output_spec": "Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.", "sample_inputs": ["2\n1 2 3 4 5 6"], "sample_outputs": ["5"], "notes": "NotePicture for the sample test. Green color denotes the additional street lights. "}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters \"1\" (the table is occupied) and \"0\" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then: strings \"10010001\", \"10000010\", \"00000000\", \"00100000\" satisfy the rules of the restaurant; strings \"10100100\", \"10011001\", \"11111111\" do not satisfy to the rules of the restaurant, since each of them has a pair of \"1\" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without \"1\" or a string with one \"1\", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of \"0\" that can be replaced by \"1\" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$\u00a0\"100010\", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2\\cdot 10^5$$$)\u00a0\u2014 the number of tables in the restaurant and the minimum allowed distance between two people. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ consisting of \"0\" and \"1\"\u00a0\u2014 a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant\u00a0\u2014 the difference between indices of any two \"1\" is more than $$$k$$$. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case output one integer\u00a0\u2014 the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output $$$0$$$.", "sample_inputs": ["6\n6 1\n100010\n6 2\n000000\n5 1\n10101\n3 1\n001\n2 2\n00\n1 1\n0"], "sample_outputs": ["1\n2\n0\n1\n1\n1"], "notes": "NoteThe first test case is explained in the statement.In the second test case, the answer is $$$2$$$, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant."}, "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"}, {"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"}], "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"} {"nl": {"description": "You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \\dots$$$. The $$$7$$$-th number among them is $$$10$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$2 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 10^9$$$).", "output_spec": "For each test case print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.", "sample_inputs": ["6\n3 7\n4 12\n2 1000000000\n7 97\n1000000000 1000000000\n2 1"], "sample_outputs": ["10\n15\n1999999999\n113\n1000000001\n1"], "notes": null}, "positive_code": [{"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"}, {"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": "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}"}], "negative_code": [], "src_uid": "7d6f76e24fe9a352beea820ab56f03b6"} {"nl": {"description": "n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.", "input_spec": "The first line contains two integers: n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009500, 2\u2009\u2264\u2009k\u2009\u2264\u20091012)\u00a0\u2014 the number of people and the number of wins. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.", "output_spec": "Output a single integer \u2014 power of the winner.", "sample_inputs": ["2 2\n1 2", "4 2\n3 1 2 4", "6 2\n6 5 3 1 2 4", "2 10000000000\n2 1"], "sample_outputs": ["2", "3", "6", "2"], "notes": "NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \\le r$$$) such that $$$a_l + a_{l+1} + \\dots + a_{r-1} + a_r < t$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \\le n \\le 200\\,000, |t| \\le 2\\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$|a_{i}| \\le 10^{9}$$$) \u2014 the description of Petya's array. Note that there might be negative, zero and positive elements.", "output_spec": "Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.", "sample_inputs": ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"], "sample_outputs": ["5", "4", "3"], "notes": "NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ "}, "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 T = nl()\n val A = na(N)\n val cum = Array.ofDim[Long](N + 1) // index 1\u305a\u308c\u3066\u308b\n rep(N) { i =>\n cum(i + 1) = cum(i) + A(i)\n }\n\n val cntr = new ZippedCounter(sort(cum.clone()))\n var ans = 0L\n rep_r(N) { i =>\n cntr.add(cum(i + 1))\n val x = T + cum(i)\n ans += cntr.countLt(x)\n }\n\n out.println(ans)\n }\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 - l) / 2\n if (a(mid) >= x) step(l, mid)\n else step(mid, h)\n }\n }\n step(-1, a.length)\n }\n\n class BIT(n: Int) {\n private val N = {\n val a = Integer.highestOneBit(n)\n if (a == n) a else a << 1\n }\n private val bit = Array.ofDim[Int](N + 1)\n\n /**\n * 0 index\n */\n def sum(i: Int): Int = {\n var x = i + 1\n var s = 0\n while(x > 0) {\n 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 var x = i + 1\n while(x <= N) {\n bit(x) += a\n x += x & -x\n }\n }\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 type A = Long\n\n /**\n * N + 1\u306e\u7bc4\u56f2\u306b\u5206\u5272\u3059\u308b\n *\n * \u4f8b:\n * as = [3 5 6]\n * (, 3] => 0 (3, 5] => 1 (5, 6] => 2 (6, ) => 3\n *\n */\n class Zipper(as: Array[A]) {\n def apply(x: A): Int = {\n lowerBound(as, x)\n }\n }\n\n /**\n * \u307e\u3058\u3081\u306aBST\u3064\u304f\u308b\u306e\u5927\u5909\u3060\u304b\u3089lesserThan\u3092\u30ab\u30a6\u30f3\u30c8\u3067\u304d\u308b\u3060\u3051\u306e\u3082\u306e\u3092\u7528\u610f\u3057\u305f\n * java.util.TreeSet\u3058\u3083\u3067\u304d\u306a\u3044\n */\n class ZippedCounter(as: Array[A]) {\n val n = as.length\n val zip = new Zipper(as)\n val bit = new BIT(n + 1) // zip\u3055\u308c\u305f\u30ec\u30f3\u30b8\u306fn + 1\u500b\u306b\u306a\u308b\n var cnt = 0\n\n /**\n * @param x \u5fc5\u305a\u30ec\u30f3\u30b8\u306e\u4e0a\u9650\u3092\u8ffd\u52a0\u3057\u306a\u3044\u3044\u3051\u306a\u3044\n */\n def add(x: A): 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: A): Int = {\n // \u30ec\u30f3\u30b8\u306e\u4e0a\u9650\u306e\u5024\u3057\u304b\u5b58\u5728\u3057\u306a\u3044\u306e\u3067\u3001\u3042\u308b\u5024\u3088\u308a\u5c0f\u3055\u3044 = \u3088\u308a\u5c0f\u3055\u3044\u30ec\u30f3\u30b8 \u3068\u7f6e\u304d\u63db\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\n val i = zip(x)\n if (i > 0) bit.sum(i - 1)\n else 0\n }\n\n def countLe(x: A): Int = {\n countLt(x + 1)\n }\n\n def countGe(x: A): Int = {\n cnt - countLt(x)\n }\n\n def countGt(x: A): Int = {\n cnt - countLe(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}"}], "negative_code": [], "src_uid": "42c4adc1c4a10cc619c05a842e186e60"} {"nl": {"description": "Happy new year! The year 2020 is also known as Year Gyeongja (\uacbd\uc790\ub144, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \\ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \\ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings \"code\" and \"forces\" is the string \"codeforces\".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${\"a\", \"b\", \"c\"}, $$$t =$$$ {\"d\", \"e\", \"f\", \"g\"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?", "input_spec": "The first line contains two integers $$$n, m$$$ ($$$1 \\le n, m \\le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \\ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \\ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \\le q \\le 2\\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \\le y \\le 10^9$$$) is given, denoting the year we want to know the name for.", "output_spec": "Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above.", "sample_inputs": ["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"], "sample_outputs": ["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"], "notes": "NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal."}, "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 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"}, {"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"} {"nl": {"description": "Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the \"recent actions\" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. ", "input_spec": "The first line of input contains an integer n, the number of threads (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.", "output_spec": "Output a single integer \u2014 the number of threads that surely contain a new message.", "sample_inputs": ["5\n5 2 1 3 4", "3\n1 2 3", "4\n4 3 2 1"], "sample_outputs": ["2", "0", "3"], "notes": "NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages."}, "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}"}, {"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"}], "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"} {"nl": {"description": "Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of disks on the combination lock. The second line contains a string of n digits\u00a0\u2014 the original state of the disks. The third line contains a string of n digits\u00a0\u2014 Scrooge McDuck's combination that opens the lock.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of moves Scrooge McDuck needs to open the lock.", "sample_inputs": ["5\n82195\n64723"], "sample_outputs": ["13"], "notes": "NoteIn the sample he needs 13 moves: 1 disk: 2 disk: 3 disk: 4 disk: 5 disk: "}, "positive_code": [{"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}"}, {"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}"}, {"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}"}], "negative_code": [], "src_uid": "5adb1cf0529c3d6c93c107cf72fa5e0b"} {"nl": {"description": "It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x\u2009+\u20091, y), (x\u2009-\u20091, y), (x, y\u2009+\u20091), (x, y\u2009-\u20091) \u2014 one ant in each direction. No other ant movements will happen. Ants never interfere with each other.Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.", "input_spec": "First input line contains integers n (0\u2009\u2264\u2009n\u2009\u2264\u200930000) and t (1\u2009\u2264\u2009t\u2009\u2264\u200950000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109). Queries may coincide. It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).", "output_spec": "Print t integers, one per line \u2014 the number of ants at the corresponding junctions when the movement of the ants stops.", "sample_inputs": ["1 3\n0 1\n0 0\n0 -1", "6 5\n0 -2\n0 -1\n0 0\n0 1\n0 2"], "sample_outputs": ["0\n1\n0", "0\n1\n2\n1\n0"], "notes": "NoteIn the first sample the colony consists of the one ant, so nothing happens at all.In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "e7a07efba27f2b1f9ec7c4a8fb997b00"} {"nl": {"description": "Polycarp lives on the coordinate axis $$$Ox$$$ and travels from the point $$$x=a$$$ to $$$x=b$$$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis $$$Ox$$$ at the point $$$x=c$$$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $$$r$$$. Thus, if Polycarp is at a distance less than or equal to $$$r$$$ from the point $$$x=c$$$, then he is in the network coverage area, otherwise\u00a0\u2014 no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from $$$x=a$$$ to $$$x=b$$$. His speed\u00a0\u2014 one unit of distance per minute.", "input_spec": "The first line contains a positive integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. In the following lines are written $$$t$$$ test cases. The description of each test case is one line, which contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$r$$$ ($$$-10^8 \\le a,b,c \\le 10^8$$$, $$$0 \\le r \\le 10^8$$$)\u00a0\u2014 the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively. Any of the numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.", "output_spec": "Print $$$t$$$ numbers\u00a0\u2014 answers to given test cases in the order they are written in the test. Each answer is an integer\u00a0\u2014 the number of minutes during which Polycarp will be unavailable during his movement.", "sample_inputs": ["9\n1 10 7 1\n3 3 3 0\n8 2 10 4\n8 2 10 100\n-10 20 -17 2\n-3 2 2 0\n-3 1 2 0\n2 3 2 3\n-1 3 -2 2"], "sample_outputs": ["7\n0\n4\n0\n30\n5\n4\n0\n3"], "notes": "NoteThe following picture illustrates the first test case. Polycarp goes from $$$1$$$ to $$$10$$$. The yellow area shows the coverage area of the station with a radius of coverage of $$$1$$$, which is located at the point of $$$7$$$. The green area shows a part of the path when Polycarp is out of coverage area. "}, "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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n final private[this] val MOD = 1000000007\n\n def solve(): Unit = {\n REP(ni()) { _ =>\n var a, b = ni()\n if (a > b) {\n val t = a\n a = b\n b = t\n }\n val c, R = ni()\n val l = c - R\n val r = c + R\n val cover = max(0, min(b, r) - max(a, l))\n val n = b - a\n val ans = n - cover\n out.println(ans)\n }\n }\n}"}], "negative_code": [], "src_uid": "783772cb7a54bf65f648d3f8b7648263"} {"nl": {"description": "You are playing a very popular computer game. The next level consists of $$$n$$$ consecutive locations, numbered from $$$1$$$ to $$$n$$$, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land $$$i$$$ to any location with land $$$i + x$$$, spending $$$x$$$ coins ($$$x \\geq 0$$$).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the number of locations. The second line of the test case contains a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 1$$$), where $$$a_i = 1$$$ means that the $$$i$$$-th location is the location with land, and $$$a_i = 0$$$ means that the $$$i$$$-th location is the location with water. It is guaranteed that $$$a_1 = 1$$$ and $$$a_n = 1$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["3\n2\n1 1\n5\n1 0 1 0 1\n4\n1 0 1 1"], "sample_outputs": ["0\n4\n2"], "notes": "NoteIn the first test case, it is enough to make one free jump from the first location to the second one, which is also the last one, so the answer is $$$0$$$.In the second test case, the only way to move from the first location to the last one is to jump between them, which will cost $$$4$$$ coins.In the third test case, you can jump from the first location to the third for $$$2$$$ coins, and then jump to the fourth location for free, so the answer is $$$2$$$. It can be shown that this is the optimal way."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject Solution {\n\n def coins() = {\n val nodes = readLine.toInt\n val nodeList = readLine.split(\"\\\\s+\")\n\n val first = nodeList.indexOf(\"0\")\n val last = nodeList.length - 1 - nodeList.reverse.indexOf(\"0\")\n\n if (first == -1) 0\n else if (first == last) 2\n else last - first + 2\n }\n\n def main(args: Array[String]): Unit = {\n val cases = readLine.toInt\n for (\n i <- 0 until cases\n ) println(coins())\n }\n}\n"}], "negative_code": [], "src_uid": "f3d34922baf84c534e78e283dcadc742"} {"nl": {"description": "Limak is a little polar bear. He likes nice strings \u2014 strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print \"-1\" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u2009106). The second line contains a string s of length n, consisting of lowercase English letters.", "output_spec": "If there is no string satisfying the given conditions then print \"-1\" (without the quotes). Otherwise, print any nice string s' that .", "sample_inputs": ["4 26\nbear", "2 7\naf", "3 1000\nhey"], "sample_outputs": ["roar", "db", "-1"], "notes": null}, "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 str = in.next()\n val result = Array.ofDim[Char](n)\n val (good, left) = str.indices.foldLeft(true, k) {\n case(acc@(false, _), i) => acc\n case(acc@(_, 0), i) =>\n result(i) = str(i)\n acc\n case((_, left), i) if str(i) - 'a' >= 'z' - str(i) =>\n val minus = Math.min(str(i) - 'a', left)\n result(i) = (str(i) - minus).toChar\n (true, left - minus)\n case((_, left), i) =>\n val minus = Math.min('z' - str(i), left)\n result(i) = (str(i) + minus).toChar\n (true, left - minus)\n }\n if (good && left == 0)\n println(result.mkString)\n else\n println(-1)\n}"}], "negative_code": [], "src_uid": "b5d0870ee99e06e8b99c74aeb8e81e01"} {"nl": {"description": "Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed.After some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: \"there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly.\"There are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them.The rules of composing words are: The letters are divided into vowels and consonants in some certain way; All words have a length of exactly n; There are m rules of the form (pos1,\u2009t1,\u2009pos2,\u2009t2). Each rule is: if the position pos1 has a letter of type t1, then the position pos2 has a letter of type t2.You are given some string s of length n, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string s, find the minimal one in lexicographic order.", "input_spec": "The first line contains a single line consisting of letters 'V' (Vowel) and 'C' (Consonant), determining which letters are vowels and which letters are consonants. The length of this string l is the size of the alphabet of the new language (1\u2009\u2264\u2009l\u2009\u2264\u200926). The first l letters of the English alphabet are used as the letters of the alphabet of the new language. If the i-th character of the string equals to 'V', then the corresponding letter is a vowel, otherwise it is a consonant. The second line contains two integers n, m (1\u2009\u2264\u2009n\u2009\u2264\u2009200, 0\u2009\u2264\u2009m\u2009\u2264\u20094n(n\u2009-\u20091))\u00a0\u2014 the number of letters in a single word and the number of rules, correspondingly. Next m lines describe m rules of the language in the following format: pos1,\u2009t1,\u2009pos2,\u2009t2 (1\u2009\u2264\u2009pos1,\u2009pos2\u2009\u2264\u2009n, pos1\u2009\u2260\u2009pos2, 'V', 'C' }). The last line contains string s of length n, consisting of the first l small letters of the English alphabet. It is guaranteed that no two rules are the same.", "output_spec": "Print a smallest word of a language that is lexicographically not smaller than s. If such words does not exist (for example, if the language has no words at all), print \"-1\" (without the quotes).", "sample_inputs": ["VC\n2 1\n1 V 2 C\naa", "VC\n2 1\n1 C 2 V\nbb", "VCC\n4 3\n1 C 2 V\n2 C 3 V\n3 V 4 V\nabac"], "sample_outputs": ["ab", "-1", "acaa"], "notes": "NoteIn the first test word \"aa\" is not a word of the language, but word \"ab\" is.In the second test out of all four possibilities only word \"bb\" is not a word of a language, but all other words are lexicographically less, so there is no answer.In the third test, due to the last rule, \"abac\" doesn't belong to the language (\"a\" is a vowel, \"c\" is a consonant). The only word with prefix \"ab\" that meets the given rules is \"abaa\". But it is less than \"abac\", so the answer will be \"acaa\""}, "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\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"}, {"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"} {"nl": {"description": "Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.", "input_spec": "The first line contains a positive integer v (0\u2009\u2264\u2009v\u2009\u2264\u2009106). The second line contains nine positive integers a1,\u2009a2,\u2009...,\u2009a9 (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.", "sample_inputs": ["5\n5 4 3 2 1 2 3 4 5", "2\n9 11 1 12 5 8 9 10 6", "0\n1 1 1 1 1 1 1 1 1"], "sample_outputs": ["55555", "33", "-1"], "notes": null}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \\dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \\dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \\dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \\le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \\dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, \"aaa\" is smaller than \"aaaa\", \"abb\" is smaller than \"abc\", \"pqr\" is smaller than \"z\".", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters \u2014 the string $$$s$$$.", "output_spec": "Print one string \u2014 the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.", "sample_inputs": ["3\naaa", "5\nabcda"], "sample_outputs": ["aa", "abca"], "notes": "NoteIn the first example you can remove any character of $$$s$$$ to obtain the string \"aa\".In the second example \"abca\" < \"abcd\" < \"abcda\" < \"abda\" < \"acda\" < \"bcda\"."}, "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 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}"}, {"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"} {"nl": {"description": "Dima got into number sequences. Now he's got sequence a1,\u2009a2,\u2009...,\u2009an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0)\u2009=\u20090; f(2\u00b7x)\u2009=\u2009f(x); f(2\u00b7x\u2009+\u20091)\u2009=\u2009f(x)\u2009+\u20091. Dima wonders, how many pairs of indexes (i,\u2009j) (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) are there, such that f(ai)\u2009=\u2009f(aj). Help him, count the number of such pairs. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3\n1 2 4", "3\n5 3 1"], "sample_outputs": ["3", "1"], "notes": "NoteIn the first sample any pair (i,\u2009j) will do, so the answer is 3.In the second sample only pair (1,\u20092) will do."}, "positive_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.toLong*(v-1)/2}) sum)\n }\n}\n \n"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n\u2009=\u20095, then after the third throw the child number 2 has the ball again. Overall, n\u2009-\u20091 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) which indicates the number of kids in the circle.", "output_spec": "In the single line print n\u2009-\u20091 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.", "sample_inputs": ["10", "3"], "sample_outputs": ["2 4 7 1 6 2 9 7 6", "2 1"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $$$(Ox)$$$ axis.On this street, there are $$$n$$$ antennas, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th antenna lies on the position $$$x_i$$$ and has an initial scope of $$$s_i$$$: it covers all integer positions inside the interval $$$[x_i - s_i; x_i + s_i]$$$.It is possible to increment the scope of any antenna by $$$1$$$, this operation costs $$$1$$$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want).To modernize the street, we need to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna. Note that it is authorized to cover positions outside $$$[1; m]$$$, even if it's not required.What is the minimum amount of coins needed to achieve this modernization?", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 80$$$ and $$$n \\le m \\le 100\\ 000$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$s_i$$$ ($$$1 \\le x_i \\le m$$$ and $$$0 \\le s_i \\le m$$$). On each position, there is at most one antenna (values $$$x_i$$$ are pairwise distinct).", "output_spec": "You have to output a single integer: the minimum amount of coins required to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna.", "sample_inputs": ["3 595\n43 2\n300 4\n554 10", "1 1\n1 1", "2 50\n20 0\n3 1", "5 240\n13 0\n50 25\n60 5\n155 70\n165 70"], "sample_outputs": ["281", "0", "30", "26"], "notes": "NoteIn the first example, here is a possible strategy: Increase the scope of the first antenna by $$$40$$$, so that it becomes $$$2 + 40 = 42$$$. This antenna will cover interval $$$[43 - 42; 43 + 42]$$$ which is $$$[1; 85]$$$ Increase the scope of the second antenna by $$$210$$$, so that it becomes $$$4 + 210 = 214$$$. This antenna will cover interval $$$[300 - 214; 300 + 214]$$$, which is $$$[86; 514]$$$ Increase the scope of the third antenna by $$$31$$$, so that it becomes $$$10 + 31 = 41$$$. This antenna will cover interval $$$[554 - 41; 554 + 41]$$$, which is $$$[513; 595]$$$ Total cost is $$$40 + 210 + 31 = 281$$$. We can prove that it's the minimum cost required to make all positions from $$$1$$$ to $$$595$$$ covered by at least one antenna.Note that positions $$$513$$$ and $$$514$$$ are in this solution covered by two different antennas, but it's not important.\u2014In the second example, the first antenna already covers an interval $$$[0; 2]$$$ so we have nothing to do.Note that the only position that we needed to cover was position $$$1$$$; positions $$$0$$$ and $$$2$$$ are covered, but it's not important."}, "positive_code": [{"source_code": "object E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n case class Antenna(x: Int, s: Int)\n\n val n, m = nextInt\n val as = Array.fill(n) {\n val x, s = nextInt\n Antenna(x - 1, s)\n }.sortBy(_.x)\n\n val min = Array.fill(m)(Int.MaxValue / 2)\n\n for (i <- 0 until n) {\n val a = as(i)\n var add = 0\n while (add <= m) {\n val lPos = a.x - (if (add <= a.s) a.s else add)\n val leftMin = if (lPos > 0) min(lPos - 1) else 0\n val total = leftMin + (if (add > a.s) add - a.s else 0)\n val rPos = Math.min(m - 1, a.x + add)\n if (lPos >= 0 && total < min(lPos)) min(lPos) = total\n if (rPos < m && total < min(rPos)) {\n min(rPos) = total\n }\n add += 1\n }\n var aMin = Int.MaxValue / 2\n while (add >= 0) {\n val lPos = Math.max(0, a.x - add)\n val rPos = Math.min(m - 1, a.x + add)\n if (min(rPos) < aMin) aMin = min(rPos)\n if (aMin < min(lPos)) min(lPos) = aMin\n if (aMin < min(rPos)) min(rPos) = aMin\n add -= 1\n }\n }\n\n out.println(min.last)\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 case class Antenna(x: Int, s: Int)\n\n val n, m = nextInt\n val as = Array.fill(n) {\n val x, s = nextInt\n Antenna(x - 1, s)\n }.sortBy(_.x)\n\n val min = Array.fill(m)(Int.MaxValue / 2)\n\n for (i <- 0 until n) {\n val a = as(i)\n var add = 0\n var minMinLeft = Int.MaxValue / 2\n while (add <= a.s) {\n val leftPos = a.x - a.s\n val lPos = a.x - add\n val leftMin = if (leftPos > 0) min(leftPos - 1) else 0\n val leftMin2 = if (lPos > 0) min(lPos - 1) else 0\n if (leftMin < minMinLeft) minMinLeft = leftMin\n if (leftMin2 < minMinLeft) minMinLeft = leftMin2\n val total = minMinLeft\n val rPos = a.x + add\n if (lPos >= 0 && total < min(lPos)) min(lPos) = total\n if (rPos < m && total < min(rPos)) {\n min(rPos) = total\n }\n add += 1\n }\n while (add <= m) {\n val lPos = a.x - add\n val leftMin = if (lPos > 0) min(lPos - 1) else 0\n if (leftMin < minMinLeft) minMinLeft = leftMin\n val total = minMinLeft + (if (add > a.s) add - a.s else 0)\n val rPos = a.x + add\n if (lPos >= 0 && total < min(lPos)) min(lPos) = total\n if (rPos < m && total < min(rPos)) {\n min(rPos) = total\n }\n add += 1\n }\n }\n\n out.println(min.last)\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 E {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n case class Antenna(x: Int, s: Int)\n\n val n, m = nextInt\n val as = Array.fill(n) {\n val x, s = nextInt\n Antenna(x - 1, s)\n }.sortBy(_.x)\n\n val min = Array.fill(m)(Int.MaxValue / 2)\n\n for (i <- 0 until n) {\n val a = as(i)\n var add = 0\n var minMinLeft = Int.MaxValue / 2\n while (add <= a.s) {\n val leftPos = a.x - a.s\n val lPos = a.x - add\n val leftMin = if (leftPos > 0) min(leftPos - 1) else 0\n val leftMin2 = if (lPos > 0) min(lPos - 1) else 0\n if (leftMin < minMinLeft) minMinLeft = leftMin\n if (leftMin2 < minMinLeft) minMinLeft = leftMin2\n val total = minMinLeft\n val rPos = Math.min(m - 1, a.x + add)\n if (lPos >= 0 && total < min(lPos)) min(lPos) = total\n if (rPos < m && total < min(rPos)) {\n min(rPos) = total\n }\n add += 1\n }\n while (add <= m) {\n val lPos = a.x - add\n val leftMin = if (lPos > 0) min(lPos - 1) else 0\n if (leftMin < minMinLeft) minMinLeft = leftMin\n val total = minMinLeft + (if (add > a.s) add - a.s else 0)\n val rPos = Math.min(m - 1, a.x + add)\n if (lPos >= 0 && total < min(lPos)) min(lPos) = total\n if (rPos < m && total < min(rPos)) {\n min(rPos) = total\n }\n add += 1\n }\n }\n\n out.println(min.last)\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": "fccb8049e7b0f0bcd1dcd93620a86b5c"} {"nl": {"description": "They say \"years are like dominoes, tumbling one after the other\". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?", "input_spec": "The first line of the input contains two integers h and w (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u2009500)\u00a0\u2013 the number of rows and the number of columns, respectively. The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#'\u00a0\u2014 denoting an empty or forbidden cell, respectively. The next line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of queries. Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1\u2009\u2264\u2009r1i\u2009\u2264\u2009r2i\u2009\u2264\u2009h,\u20091\u2009\u2264\u2009c1i\u2009\u2264\u2009c2i\u2009\u2264\u2009w)\u00a0\u2014 the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.", "output_spec": "Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.", "sample_inputs": ["5 8\n....#..#\n.#......\n##.#....\n##..#.##\n........\n4\n1 1 2 3\n4 1 4 1\n1 2 4 5\n2 5 5 8", "7 39\n.......................................\n.###..###..#..###.....###..###..#..###.\n...#..#.#..#..#.........#..#.#..#..#...\n.###..#.#..#..###.....###..#.#..#..###.\n.#....#.#..#....#.....#....#.#..#..#.#.\n.###..###..#..###.....###..###..#..###.\n.......................................\n6\n1 1 3 20\n2 10 6 30\n2 10 7 30\n2 2 7 7\n1 7 7 7\n1 8 7 8"], "sample_outputs": ["4\n0\n10\n15", "53\n89\n120\n23\n0\n2"], "notes": "NoteA red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways. "}, "positive_code": [{"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}"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "d9fdf0827940883069bead0d00b3da53"} {"nl": {"description": "Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.\u00a0There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\\le n\\le 2 \\cdot 10^5$$$, $$$1\\le k< n$$$) \u00a0\u2014 the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\\le u,v\\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.", "output_spec": "Print the only line containing a single integer \u00a0\u2014 the maximum possible sum of happinesses of all envoys.", "sample_inputs": ["7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7", "4 1\n1 2\n1 3\n2 4", "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5"], "sample_outputs": ["7", "2", "9"], "notes": "NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$."}, "positive_code": [{"source_code": "import scala.collection.mutable\nimport scala.io.StdIn\n\nobject Solution_C extends App {\n\n type Graph = Array[mutable.MutableList[Int]]\n val Array(n, k) = StdIn.readLine().split(' ').map{_.toInt}\n val graph = Array.fill[mutable.MutableList[Int]](n + 1)(mutable.MutableList())\n for (e <- 1 until n) {\n val Array(from, to) = StdIn.readLine().split(' ').map{_.toInt}\n graph(from) += to\n graph(to) += from\n }\n val visited = Array.ofDim[Int](n + 1)\n val distance = Array.ofDim[Int](n + 1)\n val parent = Array.ofDim[Int](n + 1)\n val subtreeSize = Array.ofDim[Int](n + 1)\n val stack = mutable.Stack[(Int, mutable.MutableList[Int])]()\n parent(1) = 1\n stack.push((1, graph(1)))\n visited(1) = 1\n while (stack.nonEmpty) {\n val (root, edges) = stack.top\n var black = true\n var tmp = edges\n while (black && tmp.nonEmpty) {\n val to = tmp.head\n tmp = tmp.tail\n if (visited(to) == 0) {\n visited(to) = 1\n distance(to) = distance(root) + 1\n parent(to) = root\n stack.pop()\n stack.push((root, tmp))\n stack.push((to, graph(to)))\n black = false\n }\n }\n if (black) {\n var sum = 0\n graph(root) foreach { to =>\n if (parent(root) != to) {\n sum += subtreeSize(to) + 1\n }\n }\n subtreeSize(root) = sum\n stack.pop()\n }\n }\n\n for (i <- 0 to n) {\n subtreeSize(i) = distance(i) - subtreeSize(i)\n }\n var res = 0L\n val sorted = subtreeSize.slice(1, n + 1).sortWith(_ > _)\n for (i <- 0 until k) {\n res += sorted(i)\n }\n println(res)\n}\n"}], "negative_code": [], "src_uid": "47129977694cb371c7647cfd0db63d29"} {"nl": {"description": "The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. \"Rozdil\").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print \"Still Rozdil\", if he stays in Rozdil.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.", "output_spec": "Print the answer on a single line \u2014 the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print \"Still Rozdil\" (without the quotes).", "sample_inputs": ["2\n7 4", "7\n7 4 47 100 4 9 12"], "sample_outputs": ["2", "Still Rozdil"], "notes": "NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one \u2014 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is \"Still Rozdil\"."}, "positive_code": [{"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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $$$n$$$.Madoka is too tired of math to solve it herself, so help her to solve this problem!", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the required sum of the digits.", "output_spec": "For each test case print the maximum number you can obtain.", "sample_inputs": ["5\n1\n2\n3\n4\n5"], "sample_outputs": ["1\n2\n21\n121\n212"], "notes": "NoteThe only numbers with the sum of digits equal to $$$2$$$ without zeros are $$$2$$$ and $$$11$$$. But the last one has two ones in a row, so it's not valid. That's why the answer is $$$2$$$.The only numbers with the sum of digits equal to $$$3$$$ without zeros are $$$111$$$, $$$12$$$, $$$21$$$, and $$$3$$$. The first one has $$$2$$$ ones in a row, so it's not valid. So the maximum valid number is $$$21$$$.The only numbers with the sum of digits equals to $$$4$$$ without zeros are $$$1111$$$, $$$211$$$, $$$121$$$, $$$112$$$, $$$13$$$, $$$31$$$, $$$22$$$, and $$$4$$$. Numbers $$$1111$$$, $$$211$$$, $$$112$$$, $$$22$$$ aren't valid, because they have some identical digits in a row. So the maximum valid number is $$$121$$$."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\r\n\r\nobject Solution {\r\n def solve() = {\r\n val i = readLine().toInt\r\n val r = i % 3\r\n if (r == 0) {\r\n val len = i * 2 / 3\r\n (for (\r\n\r\n j <- 0 until len;\r\n res = if (j % 2 == 0) 2 else 1\r\n ) yield res) mkString (\"\")\r\n\r\n }\r\n else if (r == 1) {\r\n val len = 1 + i * 2 / 3\r\n (for (\r\n\r\n j <- 0 until len;\r\n res = if (j % 2 == 0) 1 else 2\r\n ) yield res) mkString (\"\")\r\n }\r\n else {\r\n val len = i * 2 / 3\r\n (for (\r\n j <- 0 until len;\r\n res = if (j % 2 == 0) 2 else 1\r\n )yield res) mkString (\"\");\r\n\r\n\r\n } \r\n\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 ) println(solve())\r\n\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "1a5f266b49aadbeef59e19bcf5524a57"} {"nl": {"description": "You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press\u00a0\u2014 upvote and downvote.However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.$$$n$$$ reviewers enter the site one by one. Each reviewer is one of the following types: type $$$1$$$: a reviewer has watched the movie, and they like it\u00a0\u2014 they press the upvote button; type $$$2$$$: a reviewer has watched the movie, and they dislike it\u00a0\u2014 they press the downvote button; type $$$3$$$: a reviewer hasn't watched the movie\u00a0\u2014 they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once.Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the number of reviewers. The second line of each testcase contains $$$n$$$ integers $$$r_1, r_2, \\dots, r_n$$$ ($$$1 \\le r_i \\le 3$$$)\u00a0\u2014 the types of the reviewers in the same order they enter the site.", "output_spec": "For each testcase print a single integer\u00a0\u2014 the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to.", "sample_inputs": ["4\n1\n2\n3\n1 2 3\n5\n1 1 1 1 1\n3\n3 3 2"], "sample_outputs": ["0\n2\n5\n2"], "notes": "NoteIn the first testcase of the example you can send the only reviewer to either of the servers\u00a0\u2014 they'll downvote anyway. The movie won't receive any upvotes.In the second testcase of the example you can send all reviewers to the first server: the first reviewer upvotes; the second reviewer downvotes; the last reviewer sees that the number of downvotes is not greater than the number of upvotes\u00a0\u2014 upvote themselves. There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer\u00a0\u2014 to the second server: the first reviewer upvotes on the first server; the second reviewer downvotes on the first server; the last reviewer sees no upvotes or downvotes on the second server\u00a0\u2014 upvote themselves. "}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "$$$n$$$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $$$i$$$-th robot is currently located at the point having coordinates ($$$x_i$$$, $$$y_i$$$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $$$X$$$ and $$$Y$$$, and when each robot receives this command, it starts moving towards the point having coordinates ($$$X$$$, $$$Y$$$). The robot stops its movement in two cases: either it reaches ($$$X$$$, $$$Y$$$); or it cannot get any closer to ($$$X$$$, $$$Y$$$). Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($$$x_c$$$, $$$y_c$$$). Then the movement system allows it to move to any of the four adjacent points: the first action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c - 1$$$, $$$y_c$$$); the second action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c$$$, $$$y_c + 1$$$); the third action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c + 1$$$, $$$y_c$$$); the fourth action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c$$$, $$$y_c - 1$$$). Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $$$X$$$ and $$$Y$$$ so that each robot can reach the point ($$$X$$$, $$$Y$$$). Is it possible to find such a point?", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 10^5$$$)\u00a0\u2014 the number of queries. Then $$$q$$$ queries follow. Each query begins with one line containing one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of robots in the query. Then $$$n$$$ lines follow, the $$$i$$$-th of these lines describes the $$$i$$$-th robot in the current query: it contains six integer numbers $$$x_i$$$, $$$y_i$$$, $$$f_{i, 1}$$$, $$$f_{i, 2}$$$, $$$f_{i, 3}$$$ and $$$f_{i, 4}$$$ ($$$-10^5 \\le x_i, y_i \\le 10^5$$$, $$$0 \\le f_{i, j} \\le 1$$$). The first two numbers describe the initial location of the $$$i$$$-th robot, and the following four numbers describe which actions the $$$i$$$-th robot can use to move ($$$f_{i, j} = 1$$$ if the $$$i$$$-th robot can use the $$$j$$$-th action, and $$$f_{i, j} = 0$$$ if it cannot use the $$$j$$$-th action). It is guaranteed that the total number of robots over all queries does not exceed $$$10^5$$$.", "output_spec": "You should answer each query independently, in the order these queries appear in the input. To answer a query, you should do one of the following: if it is impossible to find a point that is reachable by all $$$n$$$ robots, print one number $$$0$$$ on a separate line; if it is possible to find a point that is reachable by all $$$n$$$ robots, print three space-separated integers on the same line: $$$1$$$ $$$X$$$ $$$Y$$$, where $$$X$$$ and $$$Y$$$ are the coordinates of the point reachable by all $$$n$$$ robots. Both $$$X$$$ and $$$Y$$$ should not exceed $$$10^5$$$ by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding $$$10^5$$$ by absolute value.", "sample_inputs": ["4\n2\n-1 -2 0 0 0 0\n-1 -2 0 0 0 0\n3\n1 5 1 1 1 1\n2 5 0 1 0 1\n3 5 1 0 0 0\n2\n1337 1337 0 1 1 1\n1336 1337 1 1 0 1\n1\n3 5 1 1 1 1"], "sample_outputs": ["1 -1 -2\n1 2 5\n0\n1 -100000 -100000"], "notes": null}, "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"}, {"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"}], "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"} {"nl": {"description": "It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x,\u2009y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1,\u2009a2,\u2009...,\u2009an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.", "input_spec": "The first line of input contains two space-separated integers n,\u2009k\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a00\u2009\u2264\u2009k\u2009\u2264\u2009108).", "output_spec": "If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1,\u2009a2,\u2009...,\u2009an\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "sample_inputs": ["5 2", "5 3", "7 2"], "sample_outputs": ["1 2 3 4 5", "2 4 3 7 1", "-1"], "notes": "Notegcd(x,\u2009y) is greatest common divisor of x and y."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Suppose there is a $$$h \\times w$$$ grid consisting of empty or full cells. Let's make some definitions: $$$r_{i}$$$ is the number of consecutive full cells connected to the left side in the $$$i$$$-th row ($$$1 \\le i \\le h$$$). In particular, $$$r_i=0$$$ if the leftmost cell of the $$$i$$$-th row is empty. $$$c_{j}$$$ is the number of consecutive full cells connected to the top end in the $$$j$$$-th column ($$$1 \\le j \\le w$$$). In particular, $$$c_j=0$$$ if the topmost cell of the $$$j$$$-th column is empty. In other words, the $$$i$$$-th row starts exactly with $$$r_i$$$ full cells. Similarly, the $$$j$$$-th column starts exactly with $$$c_j$$$ full cells. These are the $$$r$$$ and $$$c$$$ values of some $$$3 \\times 4$$$ grid. Black cells are full and white cells are empty. You have values of $$$r$$$ and $$$c$$$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $$$r$$$ and $$$c$$$. Since the answer can be very large, find the answer modulo $$$1000000007\\,(10^{9} + 7)$$$. In other words, find the remainder after division of the answer by $$$1000000007\\,(10^{9} + 7)$$$.", "input_spec": "The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \\le h, w \\le 10^{3}$$$)\u00a0\u2014 the height and width of the grid. The second line contains $$$h$$$ integers $$$r_{1}, r_{2}, \\ldots, r_{h}$$$ ($$$0 \\le r_{i} \\le w$$$)\u00a0\u2014 the values of $$$r$$$. The third line contains $$$w$$$ integers $$$c_{1}, c_{2}, \\ldots, c_{w}$$$ ($$$0 \\le c_{j} \\le h$$$)\u00a0\u2014 the values of $$$c$$$.", "output_spec": "Print the answer modulo $$$1000000007\\,(10^{9} + 7)$$$.", "sample_inputs": ["3 4\n0 3 1\n0 2 3 0", "1 1\n0\n1", "19 16\n16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12\n6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4"], "sample_outputs": ["2", "0", "797922655"], "notes": "NoteIn the first example, this is the other possible case. In the second example, it's impossible to make a grid to satisfy such $$$r$$$, $$$c$$$ values.In the third example, make sure to print answer modulo $$$(10^9 + 7)$$$."}, "positive_code": [{"source_code": "object B {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val h, w = nextInt\n\n val rs = nextInts(h)\n val cs = nextInts(w)\n\n val grid = Array.fill(h, w)(0)\n var ok = true\n\n for (i <- rs.indices) {\n val lim = rs(i) min w\n for (j <- 0 until lim) grid(i)(j) = 1\n if (lim < w) grid(i)(lim) = 2\n }\n\n for (j <- cs.indices) {\n val lim = cs(j) min h\n for (i <- 0 until lim) {\n if (grid(i)(j) == 2) ok = false\n grid(i)(j) = 1\n }\n if (lim < h) {\n if (grid(lim)(j) == 1) ok = false\n grid(lim)(j) = 2\n }\n }\n//grid.foreach(g => println(g.mkString))\n val freeCount = grid.flatten.count(_ == 0)\n\n val res = if (ok) BigInt(2).modPow(freeCount, 1000000007L) else BigInt(0)\n\n out.println(res)\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": "907f7db88fb16178d6be57bea12f90a2"} {"nl": {"description": "Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be \"similar\". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words \"permanent\" and \"pergament\" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000) \u2014 the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters.", "output_spec": "In the first line, print number x \u2014 the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n, i\u2009\u2260\u2009j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print \"-1 -1\", if it is not necessary to swap characters. If there are multiple possible answers, print any of them.", "sample_inputs": ["9\npergament\npermanent", "6\nwookie\ncookie", "4\npetr\negor", "6\ndouble\nbundle"], "sample_outputs": ["1\n4 6", "1\n-1 -1", "2\n1 2", "2\n4 1"], "notes": "NoteIn the second test it is acceptable to print i\u2009=\u20092, j\u2009=\u20093."}, "positive_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,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}"}, {"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"}, {"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"}], "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"} {"nl": {"description": "You are given four integers $$$a$$$, $$$b$$$, $$$x$$$ and $$$y$$$. Initially, $$$a \\ge x$$$ and $$$b \\ge y$$$. You can do the following operation no more than $$$n$$$ times: Choose either $$$a$$$ or $$$b$$$ and decrease it by one. However, as a result of this operation, value of $$$a$$$ cannot become less than $$$x$$$, and value of $$$b$$$ cannot become less than $$$y$$$. Your task is to find the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \\cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains five integers $$$a$$$, $$$b$$$, $$$x$$$, $$$y$$$ and $$$n$$$ ($$$1 \\le a, b, x, y, n \\le 10^9$$$). Additional constraint on the input: $$$a \\ge x$$$ and $$$b \\ge y$$$ always holds.", "output_spec": "For each test case, print one integer: the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \\cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.", "sample_inputs": ["7\n10 10 8 5 3\n12 8 8 7 2\n12343 43 4543 39 123212\n1000000000 1000000000 1 1 1\n1000000000 1000000000 1 1 1000000000\n10 11 2 1 5\n10 11 9 1 10"], "sample_outputs": ["70\n77\n177177\n999999999000000000\n999999999\n55\n10"], "notes": "NoteIn the first test case of the example, you need to decrease $$$b$$$ three times and obtain $$$10 \\cdot 7 = 70$$$.In the second test case of the example, you need to decrease $$$a$$$ one time, $$$b$$$ one time and obtain $$$11 \\cdot 7 = 77$$$.In the sixth test case of the example, you need to decrease $$$a$$$ five times and obtain $$$5 \\cdot 11 = 55$$$.In the seventh test case of the example, you need to decrease $$$b$$$ ten times and obtain $$$10 \\cdot 1 = 10$$$."}, "positive_code": [{"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}"}, {"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": "/**\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}"}, {"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"}], "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"} {"nl": {"description": "A wise man told Kerem \"Different is good\" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string \"aba\" has substrings \"\" (empty substring), \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the length of the string s. The second line contains the string s of length n consisting of only lowercase English letters.", "output_spec": "If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.", "sample_inputs": ["2\naa", "4\nkoko", "5\nmurat"], "sample_outputs": ["1", "2", "0"], "notes": "NoteIn the first sample one of the possible solutions is to change the first character to 'b'.In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes \"abko\"."}, "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 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"}, {"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"} {"nl": {"description": "Valera is a collector. Once he wanted to expand his collection with exactly one antique item.Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.", "input_spec": "The first line contains two space-separated integers n,\u2009v (1\u2009\u2264\u2009n\u2009\u2264\u200950;\u00a0104\u2009\u2264\u2009v\u2009\u2264\u2009106) \u2014 the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1\u2009\u2264\u2009ki\u2009\u2264\u200950) the number of items of the i-th seller. Then go ki space-separated integers si1,\u2009si2,\u2009...,\u2009siki (104\u2009\u2264\u2009sij\u2009\u2264\u2009106) \u2014 the current prices of the items of the i-th seller. ", "output_spec": "In the first line, print integer p \u2014 the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1,\u2009q2,\u2009...,\u2009qp (1\u2009\u2264\u2009qi\u2009\u2264\u2009n) \u2014 the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order. ", "sample_inputs": ["3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000"], "sample_outputs": ["3\n1 2 3", "0"], "notes": "NoteIn the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller.In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him."}, "positive_code": [{"source_code": "import java.util.StringTokenizer\n\nimport scala.collection.mutable.ArrayBuilder\n\nobject _441A 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 v = next.toInt\n val builder = new ArrayBuilder.ofInt\n for (i <- 1 to n) {\n val m = next.toInt\n if ((1 to m).map(i => next.toInt).min < v) builder += i\n }\n val res = builder.result\n println(res.length)\n println(res.mkString(\" \"))\n}\n"}, {"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": "/**\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"}, {"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) in.next().split(\" \").map(_.toInt).tail.min).count(_ > v))\n}\n"}], "src_uid": "7804152ee14264afef019c5ad33094f9"} {"nl": {"description": "The sequence of $$$m$$$ integers is called the permutation if it contains all integers from $$$1$$$ to $$$m$$$ exactly once. The number $$$m$$$ is called the length of the permutation.Dreamoon has two permutations $$$p_1$$$ and $$$p_2$$$ of non-zero lengths $$$l_1$$$ and $$$l_2$$$.Now Dreamoon concatenates these two permutations into another sequence $$$a$$$ of length $$$l_1 + l_2$$$. First $$$l_1$$$ elements of $$$a$$$ is the permutation $$$p_1$$$ and next $$$l_2$$$ elements of $$$a$$$ is the permutation $$$p_2$$$. You are given the sequence $$$a$$$, and you need to find two permutations $$$p_1$$$ and $$$p_2$$$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $$$n$$$ ($$$2 \\leq n \\leq 200\\,000$$$): the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq n-1$$$). The total sum of $$$n$$$ is less than $$$200\\,000$$$.", "output_spec": "For each test case, the first line of output should contain one integer $$$k$$$: the number of ways to divide $$$a$$$ into permutations $$$p_1$$$ and $$$p_2$$$. Each of the next $$$k$$$ lines should contain two integers $$$l_1$$$ and $$$l_2$$$ ($$$1 \\leq l_1, l_2 \\leq n, l_1 + l_2 = n$$$), denoting, that it is possible to divide $$$a$$$ into two permutations of length $$$l_1$$$ and $$$l_2$$$ ($$$p_1$$$ is the first $$$l_1$$$ elements of $$$a$$$, and $$$p_2$$$ is the last $$$l_2$$$ elements of $$$a$$$). You can print solutions in any order.", "sample_inputs": ["6\n5\n1 4 3 2 1\n6\n2 4 1 3 2 1\n4\n2 1 1 3\n4\n1 3 3 1\n12\n2 1 3 4 5 6 7 8 9 1 10 2\n3\n1 1 1"], "sample_outputs": ["2\n1 4\n4 1\n1\n4 2\n0\n0\n1\n2 10\n0"], "notes": "NoteIn the first example, two possible ways to divide $$$a$$$ into permutations are $$$\\{1\\} + \\{4, 3, 2, 1\\}$$$ and $$$\\{1,4,3,2\\} + \\{1\\}$$$.In the second example, the only way to divide $$$a$$$ into permutations is $$$\\{2,4,1,3\\} + \\{2,1\\}$$$.In the third example, there are no possible ways."}, "positive_code": [{"source_code": "object B extends App {\n\n private def restore(as: List[Int]): List[(Int, Int)] = {\n val n = as.length\n val ma = as.max\n\n List(ma, n - ma)\n .foldLeft(List.empty[(Int, Int)]) {\n case (ls, i) =>\n val (l1, l2) = (i, n - i)\n\n val (q1, q2) = as.splitAt(i)\n val (p1, p2) = (q1.distinct, q2.distinct)\n\n if (p1.length == l1 && p1.min == 1 && p1.max == l1 &&\n p2.length == l2 && p2.min == 1 && p2.max == l2)\n (l1, l2) :: ls\n else\n ls\n }\n .distinct\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[List[Int]] = (0 until t)\n .foldLeft(List.empty[List[Int]]) { (input, _) =>\n val n = scala.io.StdIn.readInt()\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n as :: input\n }\n .reverse\n\n val output = input.map(restore)\n\n output.foreach { ls =>\n println(ls.length)\n if (ls.nonEmpty) ls.foreach { case (l1, l2) => println(s\"$l1 $l2\") }\n }\n}"}], "negative_code": [{"source_code": "object B extends App {\n\n private def restore(as: List[Int]): List[(Int, Int)] = {\n val n = as.length\n val ma = as.max\n\n List(ma, n - ma).foldLeft(List.empty[(Int, Int)]) {\n case (ls, i) =>\n val (q1, q2) = as.splitAt(i)\n val (p1, p2) = (q1.distinct, q2.distinct)\n val (l1, l2) = (i, n - i)\n\n if (p1.min == 1 && p2.min == 1 && p1.length == l1 && p2.length == l2)\n (l1, l2) :: ls\n else\n ls\n }\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[List[Int]] = (0 until t)\n .foldLeft(List.empty[List[Int]]) { (input, _) =>\n val n = scala.io.StdIn.readInt()\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n as :: input\n }\n .reverse\n\n val output = input.map(restore)\n\n output.foreach { ls =>\n println(ls.length)\n if (ls.nonEmpty) ls.foreach { case (l1, l2) => println(s\"$l1 $l2\") }\n }\n}"}, {"source_code": "object B extends App {\n\n private def restore(as: List[Int]): List[(Int, Int)] = {\n val n = as.length\n val ma = as.max\n\n List(ma, n - ma).foldLeft(List.empty[(Int, Int)]) {\n case (ls, i) =>\n val (l1, l2) = (i, n - i)\n\n val (q1, q2) = as.splitAt(i)\n val (p1, p2) = (q1.distinct, q2.distinct)\n\n if (p1.length == l1 && p2.length == l2 &&\n p1.min == 1 && p1.max == l1 &&\n p2.min == 1 && p2.max == l2)\n (l1, l2) :: ls\n else\n ls\n }\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[List[Int]] = (0 until t)\n .foldLeft(List.empty[List[Int]]) { (input, _) =>\n val n = scala.io.StdIn.readInt()\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n as :: input\n }\n .reverse\n\n val output = input.map(restore)\n\n output.foreach { ls =>\n println(ls.length)\n if (ls.nonEmpty) ls.foreach { case (l1, l2) => println(s\"$l1 $l2\") }\n }\n}"}, {"source_code": "object B extends App {\n\n private def restore(as: List[Int]): List[(Int, Int)] = {\n val n = as.length\n val ma = as.max\n\n List(ma, n - ma).foldLeft(List.empty[(Int, Int)]) {\n case (ls, i) =>\n val (p1, p2) = as.splitAt(i)\n val (l1, l2) = (i, n - i)\n\n if (p1.distinct.length == l1 && p2.distinct.length == l2)\n (l1, l2) :: ls\n else\n ls\n }\n }\n\n val t = scala.io.StdIn.readInt()\n\n val input: List[List[Int]] = (0 until t)\n .foldLeft(List.empty[List[Int]]) { (input, _) =>\n val n = scala.io.StdIn.readInt()\n val as = scala.io.StdIn.readLine().split(\" \").map(_.toInt).toList\n\n as :: input\n }\n .reverse\n\n val output = input.map(restore)\n\n output.foreach { ls =>\n println(ls.length)\n if (ls.nonEmpty) ls.foreach { case (l1, l2) => println(s\"$l1 $l2\") }\n }\n}"}], "src_uid": "5f0f79e39aaf4abc8c7414990d1f8be1"} {"nl": {"description": "Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n\u2009=\u20091, then his feeling is \"I hate it\" or if n\u2009=\u20092 it's \"I hate that I love it\", and if n\u2009=\u20093 it's \"I hate that I love that I hate it\" and so on.Please help Dr. Banner.", "input_spec": "The only line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of layers of love and hate.", "output_spec": "Print Dr.Banner's feeling in one line.", "sample_inputs": ["1", "2", "3"], "sample_outputs": ["I hate it", "I hate that I love it", "I hate that I love that I hate it"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Stepan likes to repeat vowel letters when he writes words. For example, instead of the word \"pobeda\" he can write \"pobeeeedaaaaa\".Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are \"a\", \"e\", \"i\", \"o\", \"u\" and \"y\".There are exceptions: if letters \"e\" or \"o\" repeat in a row exactly 2 times, like in words \"feet\" and \"foot\", the program must skip them and do not transform in one vowel. For example, the word \"iiiimpleeemeentatiioon\" must be converted to the word \"implemeentatioon\".Sergey is very busy and asks you to help him and write the required program.", "input_spec": "The first line contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the number of letters in the word written by Stepan. The second line contains the string s which has length that equals to n and contains only lowercase English letters \u2014 the word written by Stepan.", "output_spec": "Print the single string \u2014 the word written by Stepan converted according to the rules described in the statement.", "sample_inputs": ["13\npobeeeedaaaaa", "22\niiiimpleeemeentatiioon", "18\naeiouyaaeeiioouuyy", "24\naaaoooiiiuuuyyyeeeggghhh"], "sample_outputs": ["pobeda", "implemeentatioon", "aeiouyaeeioouy", "aoiuyeggghhh"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.\u2014 Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work\u00a0\u2014 that is, robots!The department you work in sells $$$n \\cdot k$$$ items. The first item costs $$$1$$$ dollar, the second item costs $$$2$$$ dollars, and so on: $$$i$$$-th item costs $$$i$$$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $$$n$$$ shelves in total, and each shelf contains exactly $$$k$$$ items. We will denote by $$$a_{i,j}$$$ the price of $$$j$$$-th item (counting from the left) on the $$$i$$$-th shelf, $$$1 \\le i \\le n, 1 \\le j \\le k$$$.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $$$a_{i,l}, a_{i,l+1}, \\ldots, a_{i,r}$$$ for some shelf $$$i$$$ and indices $$$l \\le r$$$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $$$a$$$ that: Every number from $$$1$$$ to $$$n \\cdot k$$$ (inclusively) occurs exactly once. For each $$$i, l, r$$$, the mean price of items from $$$l$$$ to $$$r$$$ on $$$i$$$-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 500$$$)\u00a0\u2014 the number of shelves and length of each shelf, respectively. It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum $$$k$$$ over all test cases does not exceed $$$500$$$.", "output_spec": "Print the answer for each test case. If such an arrangement exists, print \"YES\" on a single line. After that, print any example on $$$n$$$ lines of $$$k$$$ numbers each, one line per shelf. Each number from $$$1$$$ to $$$n \\cdot k$$$ must occur exactly once in the output. If no good arrangement exists, print a single word \"NO\" on its own line.", "sample_inputs": ["4\n\n1 1\n\n2 2\n\n3 3\n\n3 1"], "sample_outputs": ["YES\n1 \nYES\n1 3 \n2 4 \nNO\nYES\n1 \n2 \n3"], "notes": null}, "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 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"}, {"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"} {"nl": {"description": "The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students.", "output_spec": "Print one integer \u2014 the number of good pairs of topic.", "sample_inputs": ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"], "sample_outputs": ["7", "0"], "notes": null}, "positive_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\nimport scala.collection.Searching._\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 C627D(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 C627D(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 val b = na(n)\n val c = Array.ofDim[Int](n)\n REP(n) { i =>\n c(i) = a(i) - b(i)\n }\n s = c.toIndexedSeq.sorted\n var ans = 0L\n REP(n) { i =>\n if(s(i) > 0) {\n ans += (i - bs(0, i, -1 * s(i) + 1))\n }\n }\n out.println(ans)\n }\n\n var s: IndexedSeq[Int] = _\n\n def bs(l: Int, h: Int, n: Int): Int = {\n var lo = l\n var hi = h\n while (hi - lo > 0) {\n val md = lo + (hi - lo) / 2\n if(s(md) < n) lo = md + 1\n else hi = md\n }\n if(s(lo) >= n) lo\n else hi\n }\n}\n"}], "negative_code": [{"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\nimport scala.collection.Searching._\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 C627D(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 C627D(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 val b = na(n)\n val c = Array.ofDim[Int](n)\n REP(n) { i =>\n c(i) = a(i) - b(i)\n }\n s = c.toIndexedSeq.sorted\n var ans = 0L\n REP(n) { i =>\n if(s(i) > 0) {\n ans += (i - bs(0, i-1, -1 * s(i) + 1))\n }\n }\n out.println(ans)\n }\n\n var s: IndexedSeq[Int] = _\n\n def bs(l: Int, h: Int, n: Int): Int = {\n var lo = l\n var hi = h\n while (hi - lo > 0) {\n val md = lo + (hi - lo) / 2\n if(s(md) < n) lo = md + 1\n else hi = md\n }\n if(s(lo) >= n) lo\n else hi\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\nimport scala.collection.Searching._\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 C627D(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 C627D(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 val b = na(n)\n val c = Array.ofDim[Int](n)\n REP(n) { i =>\n c(i) = a(i) - b(i)\n }\n s = c.toIndexedSeq.sorted\n var ans = 0L\n REP(n) { i =>\n if(s(i) > 0) {\n ans += (i - bs(0, i-1, -1 * s(i) + 1))\n }\n }\n out.println(ans)\n }\n\n var s: IndexedSeq[Int] = _\n\n def bs(l: Int, h: Int, n: Int): Int = {\n var lo = l\n var hi = h\n while (hi - lo > 1) {\n val md = lo + (hi - lo) / 2\n if(s(md) < n) lo = md + 1\n else hi = md\n }\n if(s(lo) >= n) lo\n else hi\n }\n}\n"}, {"source_code": "import java.io._\nimport java.util.StringTokenizer\n\nimport scala.reflect.ClassTag\nimport scala.collection.Searching._\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 C627D(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 C627D(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 val b = na(n)\n val c = Array.ofDim[Int](n)\n REP(n) { i =>\n c(i) = a(i) - b(i)\n }\n val s = c.toIndexedSeq.sorted\n var ans = 0L\n REP(n) { i =>\n if(s(i) > 0) {\n ans += (s.search(-1 * s(i) + 1) match {\n case Found(u) => i - u\n case InsertionPoint(v) => i - v\n })\n }\n }\n out.println(ans)\n }\n}\n"}], "src_uid": "e25b247975660c5005bd4da7afd38a56"} {"nl": {"description": "The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.If $$$x$$$ is the number of passengers in a bus just before the current bus stop and $$$y$$$ is the number of passengers in the bus just after current bus stop, the system records the number $$$y-x$$$. So the system records show how number of passengers changed.The test run was made for single bus and $$$n$$$ bus stops. Thus, the system recorded the sequence of integers $$$a_1, a_2, \\dots, a_n$$$ (exactly one number for each bus stop), where $$$a_i$$$ is the record for the bus stop $$$i$$$. The bus stops are numbered from $$$1$$$ to $$$n$$$ in chronological order.Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$ (that is, at any time in the bus there should be from $$$0$$$ to $$$w$$$ passengers inclusive).", "input_spec": "The first line contains two integers $$$n$$$ and $$$w$$$ $$$(1 \\le n \\le 1\\,000, 1 \\le w \\le 10^{9})$$$ \u2014 the number of bus stops and the capacity of the bus. The second line contains a sequence $$$a_1, a_2, \\dots, a_n$$$ $$$(-10^{6} \\le a_i \\le 10^{6})$$$, where $$$a_i$$$ equals to the number, which has been recorded by the video system after the $$$i$$$-th bus stop.", "output_spec": "Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.", "sample_inputs": ["3 5\n2 1 -3", "2 4\n-1 1", "4 10\n2 4 1 2"], "sample_outputs": ["3", "4", "2"], "notes": "NoteIn the first example initially in the bus could be $$$0$$$, $$$1$$$ or $$$2$$$ passengers.In the second example initially in the bus could be $$$1$$$, $$$2$$$, $$$3$$$ or $$$4$$$ passengers.In the third example initially in the bus could be $$$0$$$ or $$$1$$$ passenger."}, "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, 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}"}, {"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"} {"nl": {"description": "Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array $$$[0, 0, 1, 0, 2]$$$ MEX equals to $$$3$$$ because numbers $$$0, 1$$$ and $$$2$$$ are presented in the array and $$$3$$$ is the minimum non-negative integer not presented in the array; for the array $$$[1, 2, 3, 4]$$$ MEX equals to $$$0$$$ because $$$0$$$ is the minimum non-negative integer not presented in the array; for the array $$$[0, 1, 4, 3]$$$ MEX equals to $$$2$$$ because $$$2$$$ is the minimum non-negative integer not presented in the array. You are given an empty array $$$a=[]$$$ (in other words, a zero-length array). You are also given a positive integer $$$x$$$.You are also given $$$q$$$ queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ and means that you have to append one element $$$y_j$$$ to the array. The array length increases by $$$1$$$ after a query.In one move, you can choose any index $$$i$$$ and set $$$a_i := a_i + x$$$ or $$$a_i := a_i - x$$$ (i.e. increase or decrease any element of the array by $$$x$$$). The only restriction is that $$$a_i$$$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of $$$q$$$ queries (i.e. the $$$j$$$-th answer corresponds to the array of length $$$j$$$).Operations are discarded before each query. I.e. the array $$$a$$$ after the $$$j$$$-th query equals to $$$[y_1, y_2, \\dots, y_j]$$$.", "input_spec": "The first line of the input contains two integers $$$q, x$$$ ($$$1 \\le q, x \\le 4 \\cdot 10^5$$$) \u2014 the number of queries and the value of $$$x$$$. The next $$$q$$$ lines describe queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ ($$$0 \\le y_j \\le 10^9$$$) and means that you have to append one element $$$y_j$$$ to the array.", "output_spec": "Print the answer to the initial problem after each query \u2014 for the query $$$j$$$ print the maximum value of MEX after first $$$j$$$ queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.", "sample_inputs": ["7 3\n0\n1\n2\n2\n0\n0\n10", "4 3\n1\n2\n1\n2"], "sample_outputs": ["1\n2\n3\n3\n4\n4\n7", "0\n0\n0\n0"], "notes": "NoteIn the first example: After the first query, the array is $$$a=[0]$$$: you don't need to perform any operations, maximum possible MEX is $$$1$$$. After the second query, the array is $$$a=[0, 1]$$$: you don't need to perform any operations, maximum possible MEX is $$$2$$$. After the third query, the array is $$$a=[0, 1, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$. After the fourth query, the array is $$$a=[0, 1, 2, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$ (you can't make it greater with operations). After the fifth query, the array is $$$a=[0, 1, 2, 2, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3]$$$. Now MEX is maximum possible and equals to $$$4$$$. After the sixth query, the array is $$$a=[0, 1, 2, 2, 0, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3, 0]$$$. Now MEX is maximum possible and equals to $$$4$$$. After the seventh query, the array is $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. You can perform the following operations: $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$, $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$, $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$, $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$, $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$, $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$. The resulting array will be $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Now MEX is maximum possible and equals to $$$7$$$. "}, "positive_code": [{"source_code": "\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(q, x) = stdin.next().split(' ').map(_.toInt)\n val r = stdin.take(q).map(_.toInt).foldLeft(List[Int] (0), Map.empty[Int, Int]) {\n case((l@(h::xs), map), el) => // replacements contains temporary elements\n // while replacements contains el -> move replacements to fixed\n val key = el % x\n val nMap = map + (key -> (map.getOrElse(el % x, 0) + 1))\n (solve(h, nMap) :: l, nMap)\n }._1.reverse.tail\n\n println(r.mkString(\"\\n\"))\n\n def solve(max: Int, map: Map[Int, Int]) = {\n// println(s\"max = ${max}\")\n// println(s\"map = ${map}\")\n var res = max;\n while (res < res % x + map.getOrElse(res % x, 0) * x) {\n res += 1\n }\n res\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "negative_code": [{"source_code": "\nobject Main extends App {\n val stdin = scala.io.Source.stdin.getLines()\n val Array(q, x) = stdin.next().split(' ').map(_.toInt)\n val r = stdin.take(q).map(_.toInt).foldLeft(List[Int] (0), Map.empty[Int, Int]) {\n case((l@(h::xs), map), el) => // replacements contains temporary elements\n // while replacements contains el -> move replacements to fixed\n val key = el % x\n val nMap = map + (key -> (map.getOrElse(el % x, 0) + 1))\n (solve(h, nMap) :: l, nMap)\n }._1.reverse.tail\n\n// println(r.mkString(\"\\n\"))\n\n def solve(max: Int, map: Map[Int, Int]) = {\n// println(s\"max = ${max}\")\n// println(s\"map = ${map}\")\n var res = max;\n while (res < res % x + map.getOrElse(res % x, 0) * x) {\n res += 1\n }\n res\n }\n}\n\n\n//1\n//6\n//1 1 1 2 2 1 2 1 2 1 1 2"}], "src_uid": "e25d4d7decfe6e0f5994f615a268b3aa"} {"nl": {"description": "Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob \u2014 to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.", "output_spec": "Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.", "sample_inputs": ["5\n2 4 7 8 10", "4\n1 2 1 1"], "sample_outputs": ["3", "2"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "You came to a local shop and want to buy some chocolate bars. There are $$$n$$$ bars in the shop, $$$i$$$-th of them costs $$$a_i$$$ coins (and you want to buy all of them).You have $$$m$$$ different coupons that allow you to buy chocolate bars. $$$i$$$-th coupon allows you to buy $$$q_i$$$ chocolate bars while you have to pay only for the $$$q_i - 1$$$ most expensive ones (so, the cheapest bar of those $$$q_i$$$ bars is for free).You can use only one coupon; if you use coupon $$$i$$$, you have to choose $$$q_i$$$ bars and buy them using the coupon, and buy all the remaining $$$n - q_i$$$ bars without any discounts.To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 the number of chocolate bars in the shop. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the cost of $$$i$$$-th chocolate bar. The third line contains one integer $$$m$$$ ($$$1 \\le m \\le n - 1$$$) \u2014 the number of coupons you have. The fourth line contains $$$m$$$ integers $$$q_1$$$, $$$q_2$$$, ..., $$$q_m$$$ ($$$2 \\le q_i \\le n$$$), where $$$q_i$$$ is the number of chocolate bars you have to buy using $$$i$$$-th coupon so that the least expensive of them will be for free. All values of $$$q_i$$$ are pairwise distinct.", "output_spec": "Print $$$m$$$ integers, $$$i$$$-th of them should be the minimum amount of money you have to pay if you buy $$$q_i$$$ bars with $$$i$$$-th coupon, and all the remaining bars one by one for their full price.", "sample_inputs": ["7\n7 1 3 1 4 10 8\n2\n3 4"], "sample_outputs": ["27\n30"], "notes": "NoteConsider the first example.If we use the first coupon, we may choose chocolate bars having indices $$$1$$$, $$$6$$$ and $$$7$$$, and we pay $$$18$$$ coins for them and $$$9$$$ coins for all other bars.If we use the second coupon, we may choose chocolate bars having indices $$$1$$$, $$$5$$$, $$$6$$$ and $$$7$$$, and we pay $$$25$$$ coins for them and $$$5$$$ coins for all other bars."}, "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"}, {"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"}], "negative_code": [], "src_uid": "c1608f6f71cac56690e31aa130c1990e"} {"nl": {"description": "You are given an undirected tree consisting of $$$n$$$ vertices. An undirected tree is a connected undirected graph with $$$n - 1$$$ edges.Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $$$1$$$ to any other vertex is at most $$$2$$$. Note that you are not allowed to add loops and multiple edges.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices in the tree. The following $$$n - 1$$$ lines contain edges: edge $$$i$$$ is given as a pair of vertices $$$u_i, v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.", "output_spec": "Print a single integer \u2014 the minimum number of edges you have to add in order to make the shortest distance from the vertex $$$1$$$ to any other vertex at most $$$2$$$. Note that you are not allowed to add loops and multiple edges.", "sample_inputs": ["7\n1 2\n2 3\n2 4\n4 5\n4 6\n5 7", "7\n1 2\n1 3\n2 4\n2 5\n3 6\n1 7", "7\n1 2\n2 3\n3 4\n3 5\n3 6\n3 7"], "sample_outputs": ["2", "0", "1"], "notes": "NoteThe tree corresponding to the first example: The answer is $$$2$$$, some of the possible answers are the following: $$$[(1, 5), (1, 6)]$$$, $$$[(1, 4), (1, 7)]$$$, $$$[(1, 6), (1, 7)]$$$.The tree corresponding to the second example: The answer is $$$0$$$.The tree corresponding to the third example: The answer is $$$1$$$, only one possible way to reach it is to add the edge $$$(1, 3)$$$."}, "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 U, V = Array.ofDim[Int](N)\n rep(N - 1) { i =>\n val v, u = sc.nextInt() - 1\n V(i) = v\n U(i) = u\n }\n val t = packTree(N, U, V)\n\n val INF = Integer.MAX_VALUE\n val d = Array.fill[Int](N)(INF)\n d(0) = 0\n val bfs = Array.ofDim[Int](N)\n val p = Array.ofDim[Int](N)\n p(0) = -1\n\n var cur = 0\n var last = 1\n def addChildren(i: Int): Unit = {\n rep(t(i).length) { k =>\n val j = t(i)(k)\n if (d(j) == INF) {\n d(j) = d(i) + 1\n p(j) = i\n bfs(last) = j\n last += 1\n }\n }\n }\n\n addChildren(cur)\n while(cur < last) {\n addChildren(bfs(cur))\n cur += 1\n }\n\n var ans = 0\n rep_r(N) { i =>\n val v = bfs(i)\n if (d(v) > 2) {\n if (d(p(v)) < 2) {\n d(v) = d(p(v)) + 1\n } else {\n ans += 1\n d(v) = 2\n d(p(v)) = 1\n if (d(p(p(v))) > 2) d(p(p(v))) = 2 // dist of grand parent\n }\n }\n }\n\n out.println(ans)\n }\n\n def main(args: Array[String]): Unit = {\n solve()\n out.flush()\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 rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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": [{"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 t = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())\n rep(N - 1) { _ =>\n val v, u = sc.nextInt() - 1\n t(v) += u\n t(u) += v\n }\n\n val INF = Integer.MAX_VALUE\n val d = Array.fill[Int](N)(INF)\n d(0) = 0\n val bfs = Array.ofDim[Int](N)\n val p = Array.ofDim[Int](N)\n p(0) = -1\n\n var cur = 0\n var last = 1\n def addChildren(i: Int): Unit = {\n t(i) foreach { j =>\n if (d(j) == INF) {\n d(j) = d(i) + 1\n bfs(last) = j\n p(j) = i\n last += 1\n }\n }\n }\n\n addChildren(cur)\n while(cur < last) {\n addChildren(cur)\n cur += 1\n }\n\n var ans = 0\n rep_r(N) { i =>\n val v = bfs(i)\n if (d(v) > 2) {\n if (d(p(v)) < 2) {\n d(v) = d(p(v)) + 1\n } else {\n ans += 1\n d(v) = 2\n d(p(v)) = 1\n if (d(p(p(v))) > 2) d(p(p(v))) = 2 // dist of grand parent\n }\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 rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\n var i = offset\n val N = n + offset\n while(i < N) { f(i); i += 1 }\n }\n def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {\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\u3060\u3068boxing\u767a\u751f\u3059\u308b\u306e\u3067\u81ea\u4f5cOrder\u3092\u7528\u610f\u3057\u305f\u3044\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"}], "src_uid": "64d85fcafab0e1b477bc888408f54eb5"} {"nl": {"description": "You are given an array a of size n, and q queries to it. There are queries of two types: 1 li ri \u2014 perform a cyclic shift of the segment [li,\u2009ri] to the right. That is, for every x such that li\u2009\u2264\u2009x\u2009<\u2009ri new value of ax\u2009+\u20091 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari; 2 li ri \u2014 reverse the segment [li,\u2009ri]. There are m important indices in the array b1, b2, ..., bm. For each i such that 1\u2009\u2264\u2009i\u2009\u2264\u2009m you have to output the number that will have index bi in the array after all queries are performed.", "input_spec": "The first line contains three integer numbers n, q and m (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009m\u2009\u2264\u2009100). The second line contains n integer numbers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). Then q lines follow. i-th of them contains three integer numbers ti, li, ri, where ti is the type of i-th query, and [li,\u2009ri] is the segment where this query is performed (1\u2009\u2264\u2009ti\u2009\u2264\u20092, 1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). The last line contains m integer numbers b1, b2, ..., bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 important indices of the array. ", "output_spec": "Print m numbers, i-th of which is equal to the number at index bi after all queries are done.", "sample_inputs": ["6 3 5\n1 2 3 4 5 6\n2 1 3\n2 3 6\n1 1 6\n2 2 1 5 3"], "sample_outputs": ["3 3 1 5 2"], "notes": null}, "positive_code": [{"source_code": "//package edu29\n\nimport scala.io.StdIn\n\nobject D extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n, q, m) = readInts\n val nums = readInts\n val qs = Array.fill(q)(readInts)\n val ms = readInts\n\n for (q <- qs.reverseIterator) {\n var i = 0\n q match {\n case Array(1, l, r) => while (i < ms.length) {\n val k = ms(i)\n if (k == l) ms(i) = r\n else if (k > l && k <= r) ms(i) = k - 1\n i += 1\n }\n case Array(2, l, r) => while (i < ms.length) {\n val k = ms(i)\n if (k >= l && k <= r) ms(i) = l + r - k\n i += 1\n }\n case _ =>\n }\n }\n\n println(ms.map(_ - 1).map(nums).mkString(\" \"))\n}\n"}], "negative_code": [{"source_code": "//package edu29\n\nimport scala.io.StdIn\n\nobject D extends App {\n def readInts = StdIn.readLine().split(\" \").map(_.toInt)\n val Array(n, q, m) = readInts\n val nums = readInts\n val qs = Array.fill(q)(readInts)\n val ms = readInts\n\n for (q <- qs.reverseIterator;i <- ms.indices)\n ms(i) = q match {\n case Array(1, l, r) if ms(i) == l => r\n case Array(1, l, r) if l < ms(i) && ms(i) <= r => ms(i) - 1\n case Array(2, l, r) if l <= ms(i) && ms(i) <= r => r + l - ms(i)\n case _ => ms(i)\n }\n\n println(ms.mkString(\" \"))\n}\n"}], "src_uid": "1efbb1e8fc46b05408d266fa72dc43e2"} {"nl": {"description": "In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with n\u2009-\u2009k\u2009+\u20091 strings s1,\u2009s2,\u2009...,\u2009sn\u2009-\u2009k\u2009+\u20091, each either \"YES\" or \"NO\". The string s1 describes a group of soldiers 1 through k (\"YES\" if the group is effective, and \"NO\" otherwise). The string s2 describes a group of soldiers 2 through k\u2009+\u20091. And so on, till the string sn\u2009-\u2009k\u2009+\u20091 that describes a group of soldiers n\u2009-\u2009k\u2009+\u20091 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names\u00a0\u2014 it's allowed to print \"Xyzzzdj\" or \"T\" for example.Find and print any solution. It can be proved that there always exists at least one solution.", "input_spec": "The first line of the input contains two integers n and k (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200950)\u00a0\u2014 the number of soldiers and the size of a group respectively. The second line contains n\u2009-\u2009k\u2009+\u20091 strings s1,\u2009s2,\u2009...,\u2009sn\u2009-\u2009k\u2009+\u20091. The string si is \"YES\" if the group of soldiers i through i\u2009+\u2009k\u2009-\u20091 is effective, and \"NO\" otherwise.", "output_spec": "Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them.", "sample_inputs": ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"], "sample_outputs": ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"], "notes": "NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is \"NO\". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is \"NO\". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is \"YES\". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is \"NO\". "}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject TaskA extends App {\n val l = readLine().split(\" \")\n\n val n = l(0).toInt\n val k = l(1).toInt\n\n val names = (for {\n f <- 'A' to 'Z'\n s <- 'a' to 'z'\n } yield s\"$f$s\").take(n).toArray\n\n readLine().split(\" \").toList.zipWithIndex\n .filter(_._1 == \"NO\")\n .map(_._2)\n .foreach { i => names(i + k - 1) = names(i) }\n\n println(names.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "046d6f213fe2d565bfa5ce537346da4f"} {"nl": {"description": "Vova had a pretty weird sleeping schedule. There are $$$h$$$ hours in a day. Vova will sleep exactly $$$n$$$ times. The $$$i$$$-th time he will sleep exactly after $$$a_i$$$ hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is $$$0$$$). Each time Vova sleeps exactly one day (in other words, $$$h$$$ hours).Vova thinks that the $$$i$$$-th sleeping time is good if he starts to sleep between hours $$$l$$$ and $$$r$$$ inclusive.Vova can control himself and before the $$$i$$$-th time can choose between two options: go to sleep after $$$a_i$$$ hours or after $$$a_i - 1$$$ hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.", "input_spec": "The first line of the input contains four integers $$$n, h, l$$$ and $$$r$$$ ($$$1 \\le n \\le 2000, 3 \\le h \\le 2000, 0 \\le l \\le r < h$$$) \u2014 the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i < h$$$), where $$$a_i$$$ is the number of hours after which Vova goes to sleep the $$$i$$$-th time.", "output_spec": "Print one integer \u2014 the maximum number of good sleeping times Vova can obtain if he acts optimally.", "sample_inputs": ["7 24 21 23\n16 17 14 20 20 11 22"], "sample_outputs": ["3"], "notes": "NoteThe maximum number of good times in the example is $$$3$$$.The story starts from $$$t=0$$$. Then Vova goes to sleep after $$$a_1 - 1$$$ hours, now the time is $$$15$$$. This time is not good. Then Vova goes to sleep after $$$a_2 - 1$$$ hours, now the time is $$$15 + 16 = 7$$$. This time is also not good. Then Vova goes to sleep after $$$a_3$$$ hours, now the time is $$$7 + 14 = 21$$$. This time is good. Then Vova goes to sleep after $$$a_4 - 1$$$ hours, now the time is $$$21 + 19 = 16$$$. This time is not good. Then Vova goes to sleep after $$$a_5$$$ hours, now the time is $$$16 + 20 = 12$$$. This time is not good. Then Vova goes to sleep after $$$a_6$$$ hours, now the time is $$$12 + 11 = 23$$$. This time is good. Then Vova goes to sleep after $$$a_7$$$ hours, now the time is $$$23 + 22 = 21$$$. This time is also good."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with $$$n$$$ stations, indexed consecutively from $$$1$$$ to $$$n$$$. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers $$$l$$$ and $$$r$$$ ($$$l \\le r$$$), and then check, whether the train is located on a station with index between $$$l$$$ and $$$r$$$, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most $$$k$$$ stations away. Formally, if the train was at the station $$$x$$$ when the gadget was applied, then at the next application of the gadget the train can appear at any station $$$y$$$ such that $$$\\max(1, x - k) \\leq y \\leq \\min(n, x + k)$$$.Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than $$$4500$$$ applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than $$$4500$$$ applications of the gadgets?", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 10^{18}$$$, $$$0 \\leq k \\leq 10$$$)\u00a0\u2014 the number of stations and the maximum number of stations the train can move between two applications of the gadget.", "output_spec": null, "sample_inputs": ["10 2\n\nYes\n\nNo\n\nYes\n\nYes"], "sample_outputs": ["3 5\n\n3 3\n\n3 4\n\n5 5"], "notes": "NoteIn the first sample, the train was initially at the station $$$5$$$, after the first application of the gadget it did not move, after the second application it moved to the station $$$3$$$, and after the third application moved again to the station $$$5$$$."}, "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\n def solve(): Unit = {\n val N = nl()\n val K = ni()\n var l = 1L\n var h = N\n while(true) {\n if (h - l > 4 * K + 5) {\n val m = (h + l) / 2\n println(s\"$l $m\")\n ns() match {\n case \"Bad\" => return ()\n case \"Yes\" => h = m\n case \"No\" => l = m + 1\n }\n l = max(l - K, 1)\n h = min(N, h + K)\n } else {\n import scala.util.Random\n val i = Random.nextInt((h - l + 1).toInt) + l\n println(s\"$i $i\")\n ns() match {\n case \"Bad\" => return ()\n case \"Yes\" => return ()\n case \"No\" =>\n l = max(l - K, 1)\n h = min(N, h + K)\n }\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\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 import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\n import mutable.{ArrayBuffer, ListBuffer}\n import scala.reflect.ClassTag\n\n val MOD = 1000000007\n\n def solve(): Unit = {\n val N = nl()\n val K = ni()\n var l = 1L\n var h = N\n while(true) {\n if (h - l > 4 * K + 5) {\n val m = (h + l) / 2\n println(s\"$l $m\")\n ns() match {\n case \"Bad\" => return ()\n case \"Yes\" => h = m\n case \"No\" => l = m + 1\n }\n l = max(l - K, 1)\n h = min(N, h + K)\n } else {\n import scala.util.Random\n val i = Random.nextInt((h - l).toInt) + l\n println(s\"$i $i\")\n ns() match {\n case \"Bad\" => return ()\n case \"Yes\" => return ()\n case \"No\" =>\n l = max(l - K, 1)\n h = min(N, h + K)\n }\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\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\n def solve(): Unit = {\n val N = nl()\n val K = ni()\n var l = 1L\n var h = N\n while(true) {\n if (h - l > 4 * K + 5) {\n val m = (h + l) / 2\n println(s\"$l $m\")\n ns() match {\n case \"Bad\" => return ()\n case \"Yes\" => h = m\n case \"No\" => l = m + 1\n }\n l = max(l - K, 0)\n h = min(N, h + K)\n } else {\n import scala.util.Random\n val i = Random.nextInt((h - l).toInt) + l\n println(s\"$i $i\")\n ns() match {\n case \"Bad\" => return ()\n case \"Yes\" => return ()\n case \"No\" =>\n l = max(l - K, 0)\n h = min(N, h + K)\n }\n }\n }\n }\n\n def main(args: Array[String]): Unit = {\n solve()\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": "c46d1a87c6a6540d573c0391e845e1db"} {"nl": {"description": "Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word \"hello\", the following words could be printed: \"hello\", \"hhhhello\", \"hheeeellllooo\", but the following could not be printed: \"hell\", \"helo\", \"hhllllooo\".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.", "output_spec": "Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.", "sample_inputs": ["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"], "sample_outputs": ["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"], "notes": null}, "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\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}, {"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"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "There are $$$n$$$ workers and $$$m$$$ tasks. The workers are numbered from $$$1$$$ to $$$n$$$. Each task $$$i$$$ has a value $$$a_i$$$\u00a0\u2014 the index of worker who is proficient in this task.Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in $$$1$$$ hour. Otherwise, it takes them $$$2$$$ hours.The workers work in parallel, independently of each other. Each worker can only work on one task at once.Assign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time $$$0$$$. What's the minimum time all tasks can be completed by?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of workers and the number of tasks. The second line contains $$$m$$$ integers $$$a_1, a_2, \\dots, a_m$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the index of the worker proficient in the $$$i$$$-th task. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the minimum time all tasks can be completed by.", "sample_inputs": ["4\n\n2 4\n\n1 2 1 2\n\n2 4\n\n1 1 1 1\n\n5 5\n\n5 1 3 2 4\n\n1 1\n\n1"], "sample_outputs": ["2\n3\n1\n1"], "notes": "NoteIn the first testcase, the first worker works on tasks $$$1$$$ and $$$3$$$, and the second worker works on tasks $$$2$$$ and $$$4$$$. Since they both are proficient in the corresponding tasks, they take $$$1$$$ hour on each. Both of them complete $$$2$$$ tasks in $$$2$$$ hours. Thus, all tasks are completed by $$$2$$$ hours.In the second testcase, it's optimal to assign the first worker to tasks $$$1, 2$$$ and $$$3$$$ and the second worker to task $$$4$$$. The first worker spends $$$3$$$ hours, the second worker spends $$$2$$$ hours (since they are not proficient in the taken task).In the third example, each worker can be assigned to the task they are proficient at. Thus, each of them complete their task in $$$1$$$ hour."}, "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[Long](n)\r\n for (i<- A.indices){\r\n A(i) = 0\r\n }\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to m) {\r\n val a = tokenizer.nextToken().toInt\r\n A(a-1)= A(a-1)+ 1\r\n }\r\n var l = 0\r\n var r = A.max\r\n while ((r - l) > 1) {\r\n val t = (l+r)/2\r\n var sum: Long = 0\r\n for (i <- A){\r\n sum+= {if (i>=t) t else i + ((t-i) / 2)}\r\n }\r\n if (sum >= m){\r\n r = t.toInt\r\n }\r\n else {\r\n l = t.toInt\r\n }\r\n }\r\n println(r)\r\n }\r\n }\r\n}"}], "negative_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[Int](n)\r\n for (i<- A.indices){\r\n A(i) = 0\r\n }\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to m) {\r\n val a = tokenizer.nextToken().toInt\r\n A(a-1)= A(a-1)+ 1\r\n }\r\n var l = 0\r\n var r = A.max\r\n while ((r - l) > 1) {\r\n val t = (l+r)/2\r\n var sum = 0\r\n for (i <- A){\r\n sum+= {if (i>=t) t else i + ((t-i) / 2)}\r\n }\r\n if (sum >= m){\r\n r = t\r\n }\r\n else {\r\n l = t\r\n }\r\n }\r\n println(r)\r\n }\r\n }\r\n}"}, {"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[Int](n)\r\n for (i<- A.indices){\r\n A(i) = 0\r\n }\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 1 to m) {\r\n val a = tokenizer.nextToken().toInt\r\n A(a-1)= A(a-1)+ 1\r\n }\r\n var l = 0\r\n var r = A.max\r\n while ((r - l) > 1) {\r\n var t = (l+r)/2\r\n var sum = 0\r\n for (i <- A){\r\n sum+= min(i,t) + max(0, (t - i) / 2)\r\n }\r\n if (sum >= m){\r\n r = t\r\n }\r\n else {\r\n l = t\r\n }\r\n }\r\n println(r)\r\n }\r\n }\r\n}"}], "src_uid": "87302bcc6c8f239641ab6f6dbeeae09c"} {"nl": {"description": "Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.", "input_spec": "The first line contains a single number n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of the tram's stops. Then n lines follow, each contains two integers ai and bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement. The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1\u2009=\u20090. At the last stop, all the passengers exit the tram and it becomes empty. More formally, . No passenger will enter the train at the last stop. That is, bn\u2009=\u20090. ", "output_spec": "Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).", "sample_inputs": ["4\n0 3\n2 5\n4 2\n4 0"], "sample_outputs": ["6"], "notes": "NoteFor the first example, a capacity of 6 is sufficient: At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer."}, "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": "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}"}, {"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"} {"nl": {"description": "Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:In the above formula, 1\u2009\u2264\u2009l\u2009<\u2009r\u2009\u2264\u2009n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.", "input_spec": "The first line contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the size of the array a. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (-109\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the array elements.", "output_spec": "Print the only integer\u00a0\u2014 the maximum value of f.", "sample_inputs": ["5\n1 4 2 3 1", "4\n1 5 4 7"], "sample_outputs": ["3", "6"], "notes": "NoteIn the first sample case, the optimal value of f is reached on intervals [1,\u20092] and [2,\u20095].In the second case maximal value of f is reachable only on the whole array."}, "positive_code": [{"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}"}, {"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\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"}], "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"} {"nl": {"description": "One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, the sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while the bracket sequences \")(\", \"(()\" and \"(()))(\" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence \u2014 a non-empty string which consists only of characters \"(\" and \")\". The sum of lengths of all bracket sequences in the input is at most $$$5 \\cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.", "output_spec": "Print a single integer \u2014 the maximum number of pairs which can be made, adhering to the conditions in the statement.", "sample_inputs": ["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first example, it's optimal to construct two pairs: \"(( \u00a0\u00a0\u00a0 )())\" and \"( \u00a0\u00a0\u00a0 )\"."}, "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 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\u304c\u5c11\u306a\u3044\u3068rank\u3082\u5c11\u306a\u3044\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\u306b\u306a\u3063\u3061\u3083\u3060\u3081\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 \u306a\u306e\u3067 <\u3067\u6bd4\u8f03\u3059\u308b\u3068\u304d\u306f+1\u3057\u306a\u3044\u3068\u3044\u3051\u306a\u3044\n if (capR != null) {\n val rs = byCaps.get(capR)\n selectR(rs, l.i) match {\n case None =>\n case Some(selected) =>\n // \u3053\u3053\u3067false\u306b\u306a\u308b\u306f\u305a\u306f\u306a\u3044\u3093\u3060\u3051\u3069\n if (!used(selected)) {\n ans += 1\n if (rs.isEmpty) byCaps.remove(capR)\n // R\u304b\u3089remove\u3059\u308b\u306e\u306f\u30b3\u30b9\u30c8\u9ad8\u3044\u306e\u3067\u3084\u3089\u306a\u3044\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}"}, {"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"} {"nl": {"description": "This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\\lfloor \\frac{n}{2} \\rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?", "input_spec": null, "output_spec": null, "sample_inputs": ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"], "sample_outputs": ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"], "notes": "NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:"}, "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 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"}, {"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"} {"nl": {"description": "Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a,\u2009b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1,\u2009s3)\u2009=\u2009f(s2,\u2009s3)\u2009=\u2009t. If there is no such string, print \u2009-\u20091.", "input_spec": "The first line contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009t\u2009\u2264\u2009n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.", "output_spec": "Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.", "sample_inputs": ["3 2\nabc\nxyc", "1 0\nc\nb"], "sample_outputs": ["ayd", "-1"], "notes": null}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.", "input_spec": "The only line of the input contains one string s of length n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7104) containing only lowercase English letters.", "output_spec": "If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible. If there exists multiple answers, you are allowed to print any of them.", "sample_inputs": ["bbbabcbbb", "rquwmzexectvnbanemsmdufrg"], "sample_outputs": ["bbbcbbb", "rumenanemur"], "notes": "NoteA subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward."}, "positive_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\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[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}"}, {"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}"}, {"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}"}], "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"} {"nl": {"description": "It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1\u2009+\u20091 to a1\u2009+\u2009a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of piles. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009103, a1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009an\u2009\u2264\u2009106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105), the number of juicy worms said by Marmot. The fourth line contains m integers q1,\u2009q2,\u2009...,\u2009qm (1\u2009\u2264\u2009qi\u2009\u2264\u2009a1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009an), the labels of the juicy worms.", "output_spec": "Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.", "sample_inputs": ["5\n2 7 3 4 9\n3\n1 25 11"], "sample_outputs": ["1\n5\n3"], "notes": "NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile. "}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).", "input_spec": "The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \\le n \\le 2\\cdot10^{5}$$$, $$$0 \\le a, b \\le 2\\cdot10^{5}$$$, $$$a + b > 0$$$) \u2014 total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters \".\" and \"*\". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.", "output_spec": "Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.", "sample_inputs": ["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"], "sample_outputs": ["2", "4", "7", "0"], "notes": "NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B \u2014 student-athlete."}, "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"}, {"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"}], "negative_code": [], "src_uid": "6208dbdf9567b759b0026db4af4545a9"} {"nl": {"description": "A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\\dots, p_n]$$$ which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) exactly once. For example, $$$p=[4, 2, 6, 5, 3, 1]$$$ is a permutation of length $$$6$$$.You are given three integers $$$n$$$, $$$a$$$ and $$$b$$$, where $$$n$$$ is an even number. Print any permutation of length $$$n$$$ that the minimum among all its elements of the left half equals $$$a$$$ and the maximum among all its elements of the right half equals $$$b$$$. Print -1 if no such permutation exists.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$), the number of test cases in the test. The following $$$t$$$ lines contain test case descriptions. Each test case description contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \\le n \\le 100$$$; $$$1 \\le a,b \\le n$$$; $$$a \\ne b$$$), where $$$n$$$ is an even number (i.e. $$$n \\bmod 2 = 0$$$).", "output_spec": "For each test case, print a single line containing any suitable permutation. Print -1 no such permutation exists. If there are multiple answers, print any of them.", "sample_inputs": ["7\n6 2 5\n6 1 3\n6 4 3\n4 2 4\n10 5 3\n2 1 2\n2 2 1"], "sample_outputs": ["4 2 6 5 3 1\n-1\n6 4 5 1 3 2 \n3 2 4 1 \n-1\n1 2 \n2 1"], "notes": null}, "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 maxn = 10010\n val mp = mutable.Map[Char, Int]()\n\n val t = readInt()\n for (tt <- 1 to t) {\n val n = readInt()\n val a = readInt()\n val b = readInt()\n val arr = new Array[Int](n+1)\n val mark = new Array[Boolean](n+1)\n var flag = true\n arr(1) = a\n arr(n) = b\n mark(a) = true\n mark(b) = true\n var po = n\n for (i <- 2 to n/2) {\n while(mark(po))\n po -= 1\n arr(i) = po\n mark(po) = true\n if (po < a)\n flag = false\n }\n po = 1\n for (i <- n/2 + 1 to n - 1) {\n while(mark(po))\n po += 1\n arr(i) = po\n mark(po) = true\n if (po > b)\n flag = false\n }\n if (flag) {\n for (i <- 1 to n)\n writer.print(arr(i) + \" \")\n writer.println()\n } else {\n writer.println(-1)\n }\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "6ea491419f3ea387cf2aded8a8db914d"} {"nl": {"description": "Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road si and width of lawn gi. For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009gi). After it new road width of the i-th part will be equal to s'i\u2009=\u2009si\u2009+\u2009xi and new lawn width will be equal to g'i\u2009=\u2009gi\u2009-\u2009xi.On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1\u2009\u2264\u2009i\u2009<\u2009n) the inequation |s'i\u2009+\u20091\u2009-\u2009s'i|\u2009\u2264\u20091 should hold. Initially this condition might not be true.You need to find the the total width of lawns the Mayor will destroy according to his plan.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 number of parts of the street. Each of the following n lines contains two integers si,\u2009gi (1\u2009\u2264\u2009si\u2009\u2264\u2009106, 0\u2009\u2264\u2009gi\u2009\u2264\u2009106) \u2014 current width of road and width of the lawn on the i-th part of the street.", "output_spec": "In the first line print the total width of lawns which will be removed. In the second line print n integers s'1,\u2009s'2,\u2009...,\u2009s'n (si\u2009\u2264\u2009s'i\u2009\u2264\u2009si\u2009+\u2009gi) \u2014 new widths of the road starting from the first part and to the last. If there is no solution, print the only integer -1 in the first line.", "sample_inputs": ["3\n4 5\n4 5\n4 10", "4\n1 100\n100 1\n1 100\n100 1", "3\n1 1\n100 100\n1 1"], "sample_outputs": ["16\n9 9 10", "202\n101 101 101 101", "-1"], "notes": null}, "positive_code": [{"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val n = readInt\n val road = 1 to n map(_ => readLine split ' ' map(_.toLong) match {\n case Array(s, g) => (s, g)\n }) toArray\n val xRoad = road map(_._1)\n val yRoad = road map(_._1)\n\n xRoad(0) += road(0)._2\n for (i <- 1 until n)\n xRoad(i) = math.min(road(i)._1 + road(i)._2, xRoad(i - 1) + 1)\n\n yRoad(n - 1) += road(n - 1)._2\n for (i <- n - 2 to (0, -1))\n yRoad(i) = math.min(road(i)._1 + road(i)._2, yRoad(i + 1) + 1)\n\n val sRoad = xRoad zip yRoad map(cur => math.min(cur._1, cur._2))\n if (sRoad.zipWithIndex.forall{ case (s, index) => road(index)._1 <= s && s <= road(index)._1 + road(index)._2}) {\n println((sRoad sum) - (road map(_._1) sum))\n sRoad foreach(s => print(s\"$s \"))\n }\n else\n println(-1)\n}"}], "negative_code": [{"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val n = readInt\n val road = 1 to n map(_ => readLine split ' ' map(_.toInt) match {\n case Array(s, g) => (s, g)\n }) toArray\n val xRoad = road map(_._1)\n val yRoad = road map(_._1)\n xRoad(0) += road(0)._2\n for (i <- 1 until n)\n xRoad(i) = math.min(road(i)._1 + road(i)._2, xRoad(i - 1) + 1)\n yRoad(n - 1) += road(n - 1)._2\n for (i <- n - 2 to (0, -1))\n yRoad(i) = math.min(road(i)._1 + road(i)._2, xRoad(i + 1) + 1)\n val sRoad = xRoad zip yRoad map(cur => math.min(cur._1, cur._2))\n if (sRoad.zipWithIndex.forall{ case (s, index) => road(index)._1 <= s && s <= road(index)._1 + road(index)._2}) {\n println((sRoad sum) - (road map(_._1) sum))\n sRoad foreach(s => print(s\"$s \"))\n }\n else\n println(-1)\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val n = readInt\n val road = 1 to n map(_ => readLine split ' ' map(_.toInt) match {\n case Array(s, g) => (s, g)\n }) toArray\n val newRoad = road map(_._1)\n newRoad(0) += road(0)._2\n for (i <- 1 until n)\n newRoad(i) = math.min(road(i)._1 + road(i)._2, newRoad(i - 1) + 1)\n for (i <- n-2 to (0, -1))\n newRoad(i) = math.min(newRoad(i + 1) + 1, newRoad(i))\n val s = newRoad zip road map(item => item._1 - item._2._1) sum\n\n if (s < 0)\n println(-1)\n else {\n println(newRoad zip road map (item => item._1 - item._2._1) sum)\n newRoad foreach (size => print(s\"$size \"))\n }\n}"}, {"source_code": "import scala.io.StdIn._\n\nobject Codeforces extends App {\n val n = readInt\n val road = 1 to n map(_ => readLine split ' ' map(_.toInt) match {\n case Array(s, g) => (s, g)\n }) toArray\n val xRoad = road map(_._1)\n val yRoad = road map(_._1)\n \n xRoad(0) += road(0)._2\n for (i <- 1 until n)\n xRoad(i) = math.min(road(i)._1 + road(i)._2, xRoad(i - 1) + 1)\n \n yRoad(n - 1) += road(n - 1)._2\n for (i <- n - 2 to (0, -1))\n yRoad(i) = math.min(road(i)._1 + road(i)._2, yRoad(i + 1) + 1)\n \n val sRoad = xRoad zip yRoad map(cur => math.min(cur._1, cur._2))\n if (sRoad.zipWithIndex.forall{ case (s, index) => road(index)._1 <= s && s <= road(index)._1 + road(index)._2}) {\n println((sRoad sum) - (road map(_._1) sum))\n sRoad foreach(s => print(s\"$s \"))\n }\n else\n println(-1)\n}"}], "src_uid": "0f637be16ae6087208974eb2c8f3b403"} {"nl": {"description": "Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $$$n$$$ sectors, and the outer area is equally divided by $$$m$$$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position. The inner area's sectors are denoted as $$$(1,1), (1,2), \\dots, (1,n)$$$ in clockwise direction. The outer area's sectors are denoted as $$$(2,1), (2,2), \\dots, (2,m)$$$ in the same manner. For a clear understanding, see the example image above.Amugae wants to know if he can move from one sector to another sector. He has $$$q$$$ questions.For each question, check if he can move between two given sectors.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \\le n, m \\le 10^{18}$$$, $$$1 \\le q \\le 10^4$$$)\u00a0\u2014 the number of sectors in the inner area, the number of sectors in the outer area and the number of questions. Each of the next $$$q$$$ lines contains four integers $$$s_x$$$, $$$s_y$$$, $$$e_x$$$, $$$e_y$$$ ($$$1 \\le s_x, e_x \\le 2$$$; if $$$s_x = 1$$$, then $$$1 \\le s_y \\le n$$$, otherwise $$$1 \\le s_y \\le m$$$; constraints on $$$e_y$$$ are similar). Amague wants to know if it is possible to move from sector $$$(s_x, s_y)$$$ to sector $$$(e_x, e_y)$$$.", "output_spec": "For each question, print \"YES\" if Amugae can move from $$$(s_x, s_y)$$$ to $$$(e_x, e_y)$$$, and \"NO\" otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["4 6 3\n1 1 2 3\n2 6 1 2\n2 6 2 4"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteExample is shown on the picture in the statement."}, "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"}, {"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"}], "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"} {"nl": {"description": "A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously: there were b milliliters poured in total. That is, the bottle need to be emptied; after the process is over, the volumes of the drink in the mugs should be equal. ", "input_spec": "The first line contains a pair of integers n, b (2\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009b\u2009\u2264\u2009100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009100), where ai is the current volume of drink in the i-th mug.", "output_spec": "Print a single number \"-1\" (without the quotes), if there is no solution. Otherwise, print n float numbers c1,\u2009c2,\u2009...,\u2009cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.", "sample_inputs": ["5 50\n1 2 3 4 5", "2 2\n1 100"], "sample_outputs": ["12.000000\n11.000000\n10.000000\n9.000000\n8.000000", "-1"], "notes": null}, "positive_code": [{"source_code": "object ProblemAboutEquation174A 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 b = scanner.nextDouble()\n val mugs = (1 to n).map(_ => scanner.nextDouble())\n val totalLiquid = mugs.sum+b\n val onEachMug = totalLiquid/n\n val resultA = mugs.map(a => onEachMug-a)\n if(mugs.exists(_ > onEachMug))\n out.println(-1)\n else\n out.println(resultA.map(s => f\"$s%.7f\").mkString(System.lineSeparator()))\n }\n}"}], "negative_code": [], "src_uid": "65fea461d3caa5a932d1e2c13e99a59e"} {"nl": {"description": "There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team\u2019s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person\u2019s teammate?", "input_spec": "There are 2n lines in the input. The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009400) \u2014 the number of teams to be formed. The i-th line (i\u2009>\u20091) contains i\u2009-\u20091 numbers ai1, ai2, ... , ai(i\u2009-\u20091). Here aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)", "output_spec": "Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.", "sample_inputs": ["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"], "sample_outputs": ["2 1 4 3", "6 5 4 3 2 1"], "notes": "NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "8051385dab9d7286f54fd332c64e836e"} {"nl": {"description": "Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \\le r \\le 100$$$)\u00a0\u2014 the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive,\u00a0\u2014 the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.", "output_spec": "Print all tram lines that Arkady could be in, in arbitrary order.", "sample_inputs": ["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"], "sample_outputs": ["1 4", "1"], "notes": "NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$."}, "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(n) = readInts(1)\n var s = readLine.split(\" \").tail.map(_.toInt).toSet\n for (_ <- 1 until n) {\n val s2 = readLine.split(\" \").tail.map(_.toInt).toSet\n s = s.intersect(s2)\n }\n\n println(s.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "16c54cf7d8b484b5e22a7d391fdc5cd3"} {"nl": {"description": "There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \\dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of participants. The second line of the test case contains $$$n$$$ integers $$$w_1, w_2, \\dots, w_n$$$ ($$$1 \\le w_i \\le n$$$), where $$$w_i$$$ is the weight of the $$$i$$$-th participant.", "output_spec": "For each test case, print one integer $$$k$$$: the maximum number of teams people can compose with the total weight $$$s$$$, if you choose $$$s$$$ optimally.", "sample_inputs": ["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"], "sample_outputs": ["2\n3\n4\n1\n2"], "notes": "NoteIn the first test case of the example, we can reach the optimal answer for $$$s=6$$$. Then the first boat is used by participants $$$1$$$ and $$$5$$$ and the second boat is used by participants $$$2$$$ and $$$4$$$ (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for $$$s=12$$$. Then first $$$6$$$ participants can form $$$3$$$ pairs.In the third test case of the example, we can reach the optimal answer for $$$s=3$$$. The answer is $$$4$$$ because we have $$$4$$$ participants with weight $$$1$$$ and $$$4$$$ participants with weight $$$2$$$.In the fourth test case of the example, we can reach the optimal answer for $$$s=4$$$ or $$$s=6$$$.In the fifth test case of the example, we can reach the optimal answer for $$$s=3$$$. Note that participant with weight $$$3$$$ can't use the boat because there is no suitable pair for him in the list."}, "positive_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 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"}, {"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": "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"}], "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"} {"nl": {"description": "Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1,\u2009a2,\u2009...,\u2009an is the sequence of points earned by the team of students in the non-increasing order (a1\u2009\u2265\u2009a2\u2009\u2265\u2009...\u2009\u2265\u2009an), then sk\u2009=\u2009a1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.", "input_spec": "The first line of the input contains exactly six integers n,\u2009k,\u2009l,\u2009r,\u2009sall,\u2009sk (1\u2009\u2264\u2009n,\u2009k,\u2009l,\u2009r\u2009\u2264\u20091000; l\u2009\u2264\u2009r; k\u2009\u2264\u2009n; 1\u2009\u2264\u2009sk\u2009\u2264\u2009sall\u2009\u2264\u2009106). It's guaranteed that the input is such that the answer exists.", "output_spec": "Print exactly n integers a1,\u2009a2,\u2009...,\u2009an \u2014 the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order. ", "sample_inputs": ["5 3 1 3 13 9", "5 3 1 3 15 9"], "sample_outputs": ["2 3 2 3 3", "3 3 3 3 3"], "notes": null}, "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}"}, {"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"}], "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"} {"nl": {"description": "Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $$$(0, 0)$$$ on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string $$$s$$$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $$$(x, y)$$$ right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to $$$(x - 1, y)$$$; if the current instruction is 'R', then the robot can move to the right to $$$(x + 1, y)$$$; if the current instruction is 'U', then the robot can move to the top to $$$(x, y + 1)$$$; if the current instruction is 'D', then the robot can move to the bottom to $$$(x, y - 1)$$$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $$$(0, 0)$$$) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell $$$(0, 0)$$$, performs the given instructions, visits no cell other than $$$(0, 0)$$$ two or more times and ends the path in the cell $$$(0, 0)$$$. Also cell $$$(0, 0)$$$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: \"UD\", \"RL\", \"UUURULLDDDDLDDRRUU\", and the following are considered invalid: \"U\" (the endpoint is not $$$(0, 0)$$$) and \"UUDD\" (the cell $$$(0, 1)$$$ is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).You have to answer $$$q$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. The next $$$q$$$ lines contain test cases. The $$$i$$$-th test case is given as the string $$$s$$$ consisting of at least $$$1$$$ and no more than $$$10^5$$$ characters 'L', 'R', 'U' and 'D' \u2014 the initial sequence of instructions. It is guaranteed that the sum of $$$|s|$$$ (where $$$|s|$$$ is the length of $$$s$$$) does not exceed $$$10^5$$$ over all test cases ($$$\\sum |s| \\le 10^5$$$).", "output_spec": "For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $$$t$$$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $$$0$$$, you are allowed to print an empty line (but you can don't print it).", "sample_inputs": ["6\nLRU\nDURLDRUDRULRDURDDL\nLRUDDLRUDRUL\nLLLLRRRR\nURDUR\nLLL"], "sample_outputs": ["2\nLR\n14\nRUURDDDDLLLUUR\n12\nULDDDRRRUULL\n2\nLR\n2\nUD\n0"], "notes": "NoteThere are only two possible answers in the first test case: \"LR\" and \"RL\".The picture corresponding to the second test case: Note that the direction of traverse does not matter Another correct answer to the third test case: \"URDDLLLUURDR\"."}, "positive_code": [{"source_code": "object CF605B extends App {\n\n import scala.io.StdIn\n\n val q = StdIn.readInt\n for (_ <- 0 until q) {\n val moves = StdIn.readLine.toCharArray\n\n val up = moves.count(_ == 'U')\n val down = moves.count(_ == 'D')\n val left = moves.count(_ == 'L')\n val right = moves.count(_ == 'R')\n\n val minUpDown = math.min(up, down)\n val minLeftRight = math.min(left, right)\n\n val finalUpDown = if (minLeftRight == 0) math.min(minUpDown, 1) else minUpDown\n val finalLeftRight = if (minUpDown == 0) math.min(minLeftRight, 1) else minLeftRight\n\n val answer = \"L\"*finalLeftRight + \"U\"*finalUpDown + \"R\"*finalLeftRight + \"D\"*finalUpDown\n println(answer.length)\n println(answer)\n }\n}\n"}], "negative_code": [{"source_code": "object CF605B extends App {\n\n import scala.io.StdIn\n\n val q = StdIn.readInt\n for (_ <- 0 until q) {\n val moves = StdIn.readLine.toCharArray\n\n val up = moves.count(_ == 'U')\n val down = moves.count(_ == 'D')\n val left = moves.count(_ == 'L')\n val right = moves.count(_ == 'R')\n\n val minUpDown = math.min(up, down)\n val minLeftRight = math.min(left, right)\n\n val finalUpDown = if (minLeftRight == 0) math.min(minUpDown, 1) else minUpDown\n val finalLeftRight = if (minUpDown == 0) math.min(minLeftRight, 1) else minLeftRight\n\n val answer = \"L\"*minLeftRight + \"U\"*minUpDown + \"R\"*minLeftRight + \"D\"*minUpDown\n println(answer.length)\n println(answer)\n }\n}"}], "src_uid": "1fba9a290d0492a3d658a7a33388db13"} {"nl": {"description": "One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers: a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the sequence that the shooshuns found.", "output_spec": "Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.", "sample_inputs": ["3 2\n3 1 1", "3 1\n3 1 1"], "sample_outputs": ["1", "-1"], "notes": "NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1."}, "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)\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": "\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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \\le u_i, v_i \\le n, u_i \\ne v_i$$$). It is guaranteed that the given edges form a tree.", "output_spec": "Print $$$n$$$ integers $$$res_1, res_2, \\dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$.", "sample_inputs": ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"], "sample_outputs": ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"], "notes": "NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$."}, "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 a = na(n)\n REP(n) { i =>\n if(a(i) == 0) a(i) = -1\n }\n from = Array.ofDim[Int](n-1)\n to = Array.ofDim[Int](n-1)\n\n REP(n-1) { i =>\n from(i) = ni() - 1\n to(i) = ni() - 1\n }\n\n build(n)\n// g.foreach(f => out.println(f.mkString(\" \")))\n\n dp = Array.ofDim[Int](n)\n ans = Array.ofDim[Int](n)\n dfs(0, -1)\n dfs1(0, -1)\n out.println(ans.mkString(\" \"))\n }\n\n def dfs(u: Int, p: Int): Unit = {\n dp(u) = a(u)\n g(u).foreach { v =>\n if(p != v) {\n dfs(v, u)\n dp(u) += scala.math.max(dp(v), 0)\n }\n }\n }\n\n def build(n: Int): Unit = {\n val count = Array.fill[Int](n)(0)\n g = Array.ofDim[Array[Int]](n)\n REP(n-1) { i =>\n count(from(i)) += 1\n count(to(i)) += 1\n }\n\n REP(n) { i =>\n g(i) = Array.ofDim[Int](count(i))\n }\n\n REP(n-1) { i =>\n g(from(i))(count(from(i))-1) = to(i)\n g(to(i))(count(to(i))-1) = from(i)\n count(from(i))-=1\n count(to(i))-=1\n }\n }\n\n def dfs1(u: Int, p: Int): Unit = {\n ans(u) = dp(u)\n g(u).foreach { v =>\n if(p != v) {\n dp(u) -= scala.math.max(dp(v), 0)\n dp(v) += scala.math.max(dp(u), 0)\n dfs1(v, u)\n dp(v) -= scala.math.max(dp(u), 0)\n dp(u) += scala.math.max(dp(v), 0)\n }\n }\n }\n\n var a: Array[Int] = _\n var dp: Array[Int] = _\n var ans: Array[Int] = _\n var g: Array[Array[Int]] = _\n var from: Array[Int] = _\n var to: Array[Int] = _\n}"}], "negative_code": [], "src_uid": "cb8895ddd54ffbd898b1bf5e169feb63"} {"nl": {"description": "The \"Road Accident\" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.Treeland consists of n cities, some pairs of cities are connected by bidirectional roads. Overall the country has n\u2009-\u20091 roads. We know that it is possible to get to any city from any other one. The cities are numbered by integers from 1 to n. For every city we know its value ri \u2014 the number of people in it.We know that the band will travel along some path, having concerts in some cities along the path. The band's path will not pass one city twice, each time they move to the city that hasn't been previously visited. Thus, the musicians will travel along some path (without visiting any city twice) and in some (not necessarily all) cities along the way they will have concerts.The band plans to gather all the big stadiums and concert halls during the tour, so every time they will perform in a city which population is larger than the population of the previously visited with concert city. In other words, the sequence of population in the cities where the concerts will be held is strictly increasing.In a recent interview with the leader of the \"road accident\" band promised to the fans that the band will give concert in the largest possible number of cities! Thus the band will travel along some chain of cities of Treeland and have concerts in some of these cities, so that the population number will increase, and the number of concerts will be the largest possible.The fans of Treeland are frantically trying to figure out how many concerts the group will have in Treeland. Looks like they can't manage without some help from a real programmer! Help the fans find the sought number of concerts.", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u20096000) \u2014 the number of cities in Treeland. The next line contains n integers r1,\u2009r2,\u2009...,\u2009rn (1\u2009\u2264\u2009ri\u2009\u2264\u2009106), where ri is the population of the i-th city. The next n\u2009-\u20091 lines contain the descriptions of the roads, one road per line. Each road is defined by a pair of integers aj, bj (1\u2009\u2264\u2009aj,\u2009bj\u2009\u2264\u2009n) \u2014 the pair of the numbers of the cities that are connected by the j-th road. All numbers in the lines are separated by spaces.", "output_spec": "Print the number of cities where the \"Road Accident\" band will have concerts.", "sample_inputs": ["6\n1 2 3 4 5 1\n1 2\n2 3\n3 4\n3 5\n3 6", "5\n1 2 3 4 5\n1 2\n1 3\n2 4\n3 5"], "sample_outputs": ["4", "3"], "notes": null}, "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 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}"}, {"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"} {"nl": {"description": "Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ \u2014 the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose some books from the given $$$n$$$ books in such a way that: Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set; the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le t_i \\le 10^4$$$, $$$0 \\le a_i, b_i \\le 1$$$), where: $$$t_i$$$ \u2014 the amount of time required for reading the $$$i$$$-th book; $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise; $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise. ", "output_spec": "If there is no solution, print only one integer -1. Otherwise print one integer $$$T$$$ \u2014 the minimum total reading time of the suitable set of books.", "sample_inputs": ["8 4\n7 1 1\n2 1 1\n4 0 1\n8 1 1\n1 0 1\n1 1 1\n1 0 1\n3 0 0", "5 2\n6 0 0\n9 0 0\n1 0 1\n2 1 1\n5 1 0", "5 3\n3 0 0\n2 1 0\n3 1 0\n5 0 1\n3 0 1"], "sample_outputs": ["18", "8", "-1"], "notes": null}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "There are $$$n$$$ beautiful skyscrapers in New York, the height of the $$$i$$$-th one is $$$h_i$$$. Today some villains have set on fire first $$$n - 1$$$ of them, and now the only safety building is $$$n$$$-th skyscraper.Let's call a jump from $$$i$$$-th skyscraper to $$$j$$$-th ($$$i < j$$$) discrete, if all skyscrapers between are strictly lower or higher than both of them. Formally, jump is discrete, if $$$i < j$$$ and one of the following conditions satisfied: $$$i + 1 = j$$$ $$$\\max(h_{i + 1}, \\ldots, h_{j - 1}) < \\min(h_i, h_j)$$$ $$$\\max(h_i, h_j) < \\min(h_{i + 1}, \\ldots, h_{j - 1})$$$. At the moment, Vasya is staying on the first skyscraper and wants to live a little longer, so his goal is to reach $$$n$$$-th skyscraper with minimal count of discrete jumps. Help him with calcualting this number.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 total amount of skyscrapers. The second line contains $$$n$$$ integers $$$h_1, h_2, \\ldots, h_n$$$ ($$$1 \\le h_i \\le 10^9$$$) \u2014 heights of skyscrapers.", "output_spec": "Print single number $$$k$$$ \u2014 minimal amount of discrete jumps. We can show that an answer always exists.", "sample_inputs": ["5\n1 3 1 4 5", "4\n4 2 2 4", "2\n1 1", "5\n100 1 100 1 100"], "sample_outputs": ["3", "1", "1", "2"], "notes": "NoteIn the first testcase, Vasya can jump in the following way: $$$1 \\rightarrow 2 \\rightarrow 4 \\rightarrow 5$$$.In the second and third testcases, we can reach last skyscraper in one jump.Sequence of jumps in the fourth testcase: $$$1 \\rightarrow 3 \\rightarrow 5$$$."}, "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"}, {"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}"}], "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"} {"nl": {"description": "A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with \"#\". As this operation is pretty expensive, you should find the minimum number of characters to replace with \"#\", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.", "input_spec": "The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100\u2009000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.", "output_spec": "Print the minimum number of characters that must be replaced with \"#\" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.", "sample_inputs": ["intellect\ntell", "google\napple", "sirisiri\nsir"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first sample AI's name may be replaced with \"int#llect\".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be \"s#ris#ri\"."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1,\u2009l2,\u2009...,\u2009lm (1\u2009\u2264\u2009li\u2009\u2264\u2009n). For each number li he wants to know how many distinct numbers are staying on the positions li, li\u2009+\u20091, ..., n. Formally, he want to find the number of distinct numbers among ali,\u2009ali\u2009+\u20091,\u2009...,\u2009an.?Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the array elements. Next m lines contain integers l1,\u2009l2,\u2009...,\u2009lm. The i-th line contains integer li (1\u2009\u2264\u2009li\u2009\u2264\u2009n).", "output_spec": "Print m lines \u2014 on the i-th line print the answer to the number li.", "sample_inputs": ["10 10\n1 2 3 4 1 2 3 4 100000 99999\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10"], "sample_outputs": ["6\n6\n6\n6\n6\n5\n4\n3\n2\n1"], "notes": null}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "1e156dfc65ef88f19ca1833f75192259"} {"nl": {"description": "This is an interactive problem.Omkar has just come across a duck! The duck is walking on a grid with $$$n$$$ rows and $$$n$$$ columns ($$$2 \\leq n \\leq 25$$$) so that the grid contains a total of $$$n^2$$$ cells. Let's denote by $$$(x, y)$$$ the cell in the $$$x$$$-th row from the top and the $$$y$$$-th column from the left. Right now, the duck is at the cell $$$(1, 1)$$$ (the cell in the top left corner) and would like to reach the cell $$$(n, n)$$$ (the cell in the bottom right corner) by moving either down $$$1$$$ cell or to the right $$$1$$$ cell each second.Since Omkar thinks ducks are fun, he wants to play a game with you based on the movement of the duck. First, for each cell $$$(x, y)$$$ in the grid, you will tell Omkar a nonnegative integer $$$a_{x,y}$$$ not exceeding $$$10^{16}$$$, and Omkar will then put $$$a_{x,y}$$$ uninteresting problems in the cell $$$(x, y)$$$. After that, the duck will start their journey from $$$(1, 1)$$$ to $$$(n, n)$$$. For each cell $$$(x, y)$$$ that the duck crosses during their journey (including the cells $$$(1, 1)$$$ and $$$(n, n)$$$), the duck will eat the $$$a_{x,y}$$$ uninteresting problems in that cell. Once the duck has completed their journey, Omkar will measure their mass to determine the total number $$$k$$$ of uninteresting problems that the duck ate on their journey, and then tell you $$$k$$$.Your challenge, given $$$k$$$, is to exactly reproduce the duck's path, i. e. to tell Omkar precisely which cells the duck crossed on their journey. To be sure of your mastery of this game, Omkar will have the duck complete $$$q$$$ different journeys ($$$1 \\leq q \\leq 10^3$$$). Note that all journeys are independent: at the beginning of each journey, the cell $$$(x, y)$$$ will still contain $$$a_{x,y}$$$ uninteresting tasks.", "input_spec": null, "output_spec": null, "sample_inputs": ["4\n\n\n\n\n3\n23\n\n\n\n\n\n\n\n26\n\n\n\n\n\n\n\n27"], "sample_outputs": ["1 2 3 6\n4 6 2 10\n9 0 7 3\n2 8 8 2\n\n\n1 1\n1 2\n1 3\n2 3\n2 4\n3 4\n4 4\n\n1 1\n2 1\n3 1\n3 2\n3 3\n3 4\n4 4\n\n1 1\n1 2\n1 3\n1 4\n2 4\n3 4\n4 4"], "notes": "NoteThe duck's three journeys are illustrated below.$$$1 + 2 + 3 + 2 + 10 + 3 + 2 = 23$$$ $$$1 + 4 + 9 + 0 + 7 + 3 + 2 = 26$$$ $$$1 + 2 + 3 + 6 + 10 + 3 + 2 = 27$$$ "}, "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => if (i % 2 == 0) 0L else 1L << (i + j)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = l | u | as(i)(j)\n }\n }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (as(i)(j) == 0) {\n if (i > 0 && (as(i - 1)(j) & k) != 0) {\n i -= 1\n } else {\n j -= 1\n }\n } else {\n if (j > 0 && (as(i)(j - 1) & k) != 0) {\n j -= 1\n } else {\n i -= 1\n }\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val min, max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (i == 0 && j == 0) {\n min(i)(j) = as(i)(j)\n } else {\n val l = if (j > 0) min(i)(j - 1) else Long.MaxValue\n val u = if (i > 0) min(i - 1)(j) else Long.MaxValue\n min(i)(j) = Math.min(l, u) + as(i)(j)\n }\n }\n }\n// for (aa <- min) {\n// out.println(aa.mkString(\" \"))\n// out.flush()\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (j > 0 && min(i)(j - 1) <= k) {\n j -= 1\n } else {\n i -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n if (k != as(0)(0)) {\n while (true) {\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val min, max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (i == 0 && j == 0) {\n min(i)(j) = as(i)(j)\n } else {\n val l = if (j > 0) min(i)(j - 1) else Long.MaxValue\n val u = if (i > 0) min(i - 1)(j) else Long.MaxValue\n min(i)(j) = Math.min(l, u) + as(i)(j)\n }\n }\n }\n// for (aa <- min) {\n// out.println(aa.mkString(\" \"))\n// out.flush()\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (j > 0 && min(i)(j - 1) <= k) {\n j -= 1\n } else {\n i -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n if (k != as(0)(0)) {\n while (true) {\n\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => (1L << (n + i - 1)) + (1L << j)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << (2 * i)))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => (1024L << i) - j\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n// for (aa <- max) {\n// out.println(aa.mkString(\" \"))\n// out.flush()\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n if (k != as(0)(0)) {\n throw new NoSuchElementException\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n// for (aa <- max) {\n// out.println(aa.mkString(\" \"))\n// out.flush()\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n if (k != as(0)(0)) {\n while (true) {\n\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => (1L << (n + i)) + (1L << j)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n if (k != as(0)(0)) {\n throw new NoSuchElementException\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val min, max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n if (i == 0 && j == 0) {\n min(i)(j) = as(i)(j)\n } else {\n val l = if (j > 0) min(i)(j - 1) else Long.MaxValue\n val u = if (i > 0) min(i - 1)(j) else Long.MaxValue\n min(i)(j) = Math.min(l, u) + as(i)(j)\n }\n }\n }\n// for (aa <- min) {\n// out.println(aa.mkString(\" \"))\n// out.flush()\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (j > 0 && min(i)(j - 1) <= k) {\n j -= 1\n } else {\n i -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n if (k != as(0)(0)) {\n while (true) {\n\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$y $x\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => 1L << i //(1024L << i) - j\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(100L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n if (k != as(0)(0)) {\n while (true) {\n\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => (1L << (n + n - i - 1)) + (1L << (n - j - 1))\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => 1L << (n + i - j - 1)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n)(i => Array.fill(n)(1L << i))\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n for (aa <- max) {\n out.println(aa.mkString(\" \"))\n out.flush()\n }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }\n }\n if (k != as(0)(0)) {\n throw new NoSuchElementException\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => if (i % 2 == 0) 0L else 1L << (i + j)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = Math.max(l, u) + as(i)(j)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j) >= k) {\n i -= 1\n } else {\n j -= 1\n }// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n// case (i, j) => (1L << (n + n - i - 1)) + (1L << (n - j - 1))\n case (i, j) => 1L << (n + j - i - 1)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n// case (i, j) => (1L << (n + n - i - 1)) + (1L << (n - j - 1))\n case (i, j) => 1L << (n + i - j)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => 1L << (n + j - i - 1)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(Set.empty[Long])\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val a = as(i)(j)\n val lu = if (i == 0 && j == 0) {\n Set(0L)\n } else {\n val l = if (j > 0) max(i)(j - 1) else Set.empty[Long]\n val u = if (i > 0) max(i - 1)(j) else Set.empty[Long]\n l | u\n }\n max(i)(j) = lu.map(_ + a)\n }\n }\n\n// println()\n// for (aa <- max) {\n// println(aa.mkString(\" \"))\n// }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && max(i - 1)(j)(k)) {\n i -= 1\n } else {\n j -= 1\n }\n// if (i > 0 && max(i - 1)(j) >= k) {\n// i -= 1\n// } else {\n// j -= 1\n// }\n }\n// if (k != as(0)(0)) {\n// while (true) {\n//\n// }\n// }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject E {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = Array.tabulate(n, n) {\n case (i, j) => if (i % 2 == 0) 0L else 1L << (i + j)\n }\n\n for (aa <- as) {\n out.println(aa.mkString(\" \"))\n }\n out.flush()\n\n val max = Array.fill(n, n)(0L)\n for (i <- 0 until n) {\n for (j <- 0 until n) {\n val l = if (j > 0) max(i)(j - 1) else 0\n val u = if (i > 0) max(i - 1)(j) else 0\n max(i)(j) = l | u | as(i)(j)\n }\n }\n\n val q = nextInt\n\n for (_ <- 1 to q) {\n var k = nextLong\n var i, j = n - 1\n val res = ArrayBuffer.empty[(Int, Int)]\n while (i > 0 || j > 0) {\n res += ((i + 1, j + 1))\n k -= as(i)(j)\n if (i > 0 && (max(i - 1)(j) & k) != 0) {\n i -= 1\n } else {\n j -= 1\n }\n }\n res += ((1, 1))\n for ((x, y) <- res.reverseIterator) {\n out.println(s\"$x $y\")\n out.flush()\n }\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"}], "src_uid": "8b0ec419248bb98b5e0c3d991c7e14fb"} {"nl": {"description": "Chouti is working on a strange math problem.There was a sequence of $$$n$$$ positive integers $$$x_1, x_2, \\ldots, x_n$$$, where $$$n$$$ is even. The sequence was very special, namely for every integer $$$t$$$ from $$$1$$$ to $$$n$$$, $$$x_1+x_2+...+x_t$$$ is a square of some integer number (that is, a perfect square).Somehow, the numbers with odd indexes turned to be missing, so he is only aware of numbers on even positions, i.e. $$$x_2, x_4, x_6, \\ldots, x_n$$$. The task for him is to restore the original sequence. Again, it's your turn to help him.The problem setter might make mistakes, so there can be no possible sequence at all. If there are several possible sequences, you can output any.", "input_spec": "The first line contains an even number $$$n$$$ ($$$2 \\le n \\le 10^5$$$). The second line contains $$$\\frac{n}{2}$$$ positive integers $$$x_2, x_4, \\ldots, x_n$$$ ($$$1 \\le x_i \\le 2 \\cdot 10^5$$$).", "output_spec": "If there are no possible sequence, print \"No\". Otherwise, print \"Yes\" and then $$$n$$$ positive integers $$$x_1, x_2, \\ldots, x_n$$$ ($$$1 \\le x_i \\le 10^{13}$$$), where $$$x_2, x_4, \\ldots, x_n$$$ should be same as in input data. If there are multiple answers, print any. Note, that the limit for $$$x_i$$$ is larger than for input data. It can be proved that in case there is an answer, there must be a possible sequence satisfying $$$1 \\le x_i \\le 10^{13}$$$.", "sample_inputs": ["6\n5 11 44", "2\n9900", "6\n314 1592 6535"], "sample_outputs": ["Yes\n4 5 16 11 64 44", "Yes\n100 9900", "No"], "notes": "NoteIn the first example $$$x_1=4$$$ $$$x_1+x_2=9$$$ $$$x_1+x_2+x_3=25$$$ $$$x_1+x_2+x_3+x_4=36$$$ $$$x_1+x_2+x_3+x_4+x_5=100$$$ $$$x_1+x_2+x_3+x_4+x_5+x_6=144$$$ All these numbers are perfect squares.In the second example, $$$x_1=100$$$, $$$x_1+x_2=10000$$$. They are all perfect squares. There're other answers possible. For example, $$$x_1=22500$$$ is another answer.In the third example, it is possible to show, that no such sequence exists."}, "positive_code": [{"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"}, {"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).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"}], "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"} {"nl": {"description": "This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Then they applied a sequence of no more than $$$n$$$ (possibly zero) operations. $$$i$$$-th operation is denoted by two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$), and means swapping two elements of the string with indices $$$a_i$$$ and $$$b_i$$$. All operations were done in the order they were placed in the sequence. For example, if $$$s$$$ is xyz and $$$2$$$ following operations are performed: $$$a_1 = 1, b_1 = 2$$$; $$$a_2 = 2, b_2 = 3$$$, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so $$$t$$$ is yzx.You are asked to restore the original string $$$s$$$. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is $$$n$$$, and get the resulting string after those operations.Can you guess the original string $$$s$$$ asking the testing system to run the sequence of swaps no more than $$$3$$$ times?The string $$$s$$$ and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution.", "input_spec": "Initially the testing system sends one string $$$t$$$, consisting of lowercase Latin letters ($$$1 \\le |t| = n \\le 10^4$$$).", "output_spec": "To give the answer, your program should print one line $$$!$$$ $$$s$$$ with a line break in the end. After that, it should flush the output and terminate gracefully.", "sample_inputs": ["yzx\naab\nbaa\naba"], "sample_outputs": ["? baa\n? aba\n? aab\n! xyz"], "notes": "NoteIn the sample, the testcase described in the statement is used. The participant asks the first query with string baa, which is transformed to aab. The second query contains string aba, which is transformed to baa. The third query contains string aab, which is transformed to aba. The participant can deduce that the initial string $$$s$$$ was xyz.Note for hacking phase:To submit a test in hacking phase, you should provide it in the following format:The first line should contain the string $$$s$$$ you guess, consisting of $$$n \\in [1, 10000]$$$ lowercase Latin letters.The second line should contain $$$k$$$ ($$$0 \\le k \\le n$$$) \u2014 the number of swap operations in the sequence.Then $$$k$$$ lines should follow, $$$i$$$-th of them should denote $$$i$$$-th operation with two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$).For example, the sample test would look like that:xyz21 22 3"}, "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\n // \u88cf\u306b1-N\u3092\u4e26\u3073\u66ff\u3048\u305f\u6570\u5217\u304c\u3042\u308b\u3068\u8003\u3048\u308b\n\n /**\n * 26\u9032\u8868\u73fe\u306b\u3057\u305f\u6642\u3001k\u6841\u76ee\u304ca-z\u306e\u5834\u6240\u306f\u3069\u3053\u304b\n */\n def queryDigits(k: Int): Array[mutable.Set[Int]] = {\n val div = math.round(math.pow(26, k)).toInt\n val str = map(N) { i =>\n ('a' + i / div % 26).toChar\n }.mkString\n\n// debug(s\"query $str\")\n\n out.println(s\"? $str\")\n out.flush()\n\n val res = ns()\n val pos = Array.fill[mutable.Set[Int]](26)(mutable.Set())\n REP(N) { i =>\n pos(res(i) - 'a') += i\n }\n pos\n }\n\n // \u6841 => letter => {pos}\n val d = map(3)(queryDigits)\n// REP(3) { i =>\n// debug(d(i).mkString)\n// }\n\n val f = Array.ofDim[Int](N) // \u5909\u63db\u95a2\u6570\n REP(26) { i =>\n REP(26) { j =>\n val mg01 = d(0)(i).intersect(d(1)(j))\n REP(26) { k =>\n val mged = mg01.intersect(d(2)(k))\n val pos = i + j * 26 + k * 26 * 26\n if (pos < N && mged.nonEmpty) f(i + j * 26 + k * 26 * 26) = mged.head\n }\n }\n }\n\n// debug(\"f\")\n// debug(f)\n\n val g = Array.ofDim[Int](N) // \u9006\u95a2\u6570\n REP(N) { i =>\n g(f(i)) = i\n }\n\n// debug(\"g\")\n// debug(g)\n\n val ans = Array.ofDim[Char](N)\n REP(N) { i =>\n ans(g(i)) = S(i)\n }\n\n// debug(s\"ans ${ans.mkString}\")\n\n out.println(s\"! ${ans.mkString}\")\n out.flush()\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": [], "src_uid": "e9079292d6bb328d8fe355101028cc6a"} {"nl": {"description": "You are given $$$n$$$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.Your task is the following: for every $$$k \\in [1..n]$$$, calculate the number of points with integer coordinates such that the number of segments that cover these points equals $$$k$$$. A segment with endpoints $$$l_i$$$ and $$$r_i$$$ covers point $$$x$$$ if and only if $$$l_i \\le x \\le r_i$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of segments. The next $$$n$$$ lines contain segments. The $$$i$$$-th line contains a pair of integers $$$l_i, r_i$$$ ($$$0 \\le l_i \\le r_i \\le 10^{18}$$$) \u2014 the endpoints of the $$$i$$$-th segment.", "output_spec": "Print $$$n$$$ space separated integers $$$cnt_1, cnt_2, \\dots, cnt_n$$$, where $$$cnt_i$$$ is equal to the number of points such that the number of segments that cover these points equals to $$$i$$$.", "sample_inputs": ["3\n0 3\n1 3\n3 8", "3\n1 3\n2 4\n5 7"], "sample_outputs": ["6 2 1", "5 2 0"], "notes": "NoteThe picture describing the first example:Points with coordinates $$$[0, 4, 5, 6, 7, 8]$$$ are covered by one segment, points $$$[1, 2]$$$ are covered by two segments and point $$$[3]$$$ is covered by three segments.The picture describing the second example:Points $$$[1, 4, 5, 6, 7]$$$ are covered by one segment, points $$$[2, 3]$$$ are covered by two segments and there are no points covered by three segments."}, "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}"}, {"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}"}], "negative_code": [], "src_uid": "e53a6f0bd06550e078e8093590de0360"} {"nl": {"description": "Ehab has an array $$$a$$$ of length $$$n$$$. He has just enough free time to make a new array consisting of $$$n$$$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.", "input_spec": "The first line contains an integer $$$t$$$\u00a0\u2014 the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{n}$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array $$$a$$$. The sum of $$$n$$$ across the test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each testcase, output the length of the longest increasing subsequence of $$$a$$$ if you concatenate it to itself $$$n$$$ times.", "sample_inputs": ["2\n3\n3 2 1\n6\n3 1 4 1 5 9"], "sample_outputs": ["3\n5"], "notes": "NoteIn the first sample, the new array is $$$[3,2,\\textbf{1},3,\\textbf{2},1,\\textbf{3},2,1]$$$. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be $$$[1,3,4,5,9]$$$."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "b978ca6fdef4a02cc027485294caa0f5"} {"nl": {"description": "You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^{18}, 1 \\le m \\le 10^5$$$) \u2014 the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \\dots , a_m$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer \u2014 the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).", "sample_inputs": ["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"], "sample_outputs": ["2\n-1\n0"], "notes": null}, "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 * 2).map(_.split(\" \").map(_.toLong)).grouped(2).map(arr => {\n var Array(n, m) = arr.head\n solve(n, arr.last)\n })\n println(rel.mkString(\"\\n\"))\n\n def solve(n: Long, arr: Array[Long]): Int =\n if (arr.sum < n) -1\n else solveNoCheck(n, arr.groupBy(i => i).map(pair => pair._1 -> pair._2.length), 1)\n\n def solveNoCheck(n: Long, map: Map[Long, Int], split: Long): Int = {\n if (split > n) 0\n else if (map.get(split / 2).exists(_ >= 2))\n solveNoCheck(n, map + (split -> (map.getOrElse(split, 0) + map(split / 2) / 2)) + (split / 2 -> 0), split)\n else if ((n / split) % 2 == 0) solveNoCheck(n, map, split * 2)\n else {\n var nMap = map\n var nSplit = split\n var count = 0\n while (nMap.getOrElse(nSplit, 0) == 0) {\n nMap += (nSplit -> 1)\n nSplit = nSplit * 2\n count += 1\n }\n nMap += (nSplit -> (nMap(nSplit) - 1))\n count + solveNoCheck(n, nMap, split * 2)\n }\n }\n}\n\n"}], "negative_code": [], "src_uid": "79440d6707a1d7553493130ebced47e3"} {"nl": {"description": "Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.", "output_spec": "On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.", "sample_inputs": ["4\n4 1 2 10", "7\n1 2 3 4 5 6 7"], "sample_outputs": ["12 5", "16 12"], "notes": "NoteIn the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5."}, "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": "\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"}, {"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"} {"nl": {"description": "This problem is different from the easy version. In this version Ujan makes at most $$$2n$$$ swaps. In addition, $$$k \\le 1000, n \\le 50$$$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $$$2n$$$ times: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \\le i,j \\le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$.Ujan's goal is to make the strings $$$s$$$ and $$$t$$$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $$$2n$$$ or shorter is suitable.", "input_spec": "The first line contains a single integer $$$k$$$ ($$$1 \\leq k \\leq 1000$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 50$$$), the length of the strings $$$s$$$ and $$$t$$$. Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.", "output_spec": "For each test case, output \"Yes\" if Ujan can make the two strings equal with at most $$$2n$$$ operations and \"No\" otherwise. You can print each letter in any case (upper or lower). In the case of \"Yes\" print $$$m$$$ ($$$1 \\le m \\le 2n$$$) on the next line, where $$$m$$$ is the number of swap operations to make the strings equal. Then print $$$m$$$ lines, each line should contain two integers $$$i, j$$$ ($$$1 \\le i, j \\le n$$$) meaning that Ujan swaps $$$s_i$$$ and $$$t_j$$$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $$$2n$$$ is suitable.", "sample_inputs": ["4\n5\nsouse\nhouhe\n3\ncat\ndog\n2\naa\naz\n3\nabc\nbca"], "sample_outputs": ["Yes\n1\n1 4\nNo\nNo\nYes\n3\n1 2\n3 1\n2 3"], "notes": null}, "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_599_B2 { 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 var w1 = readLine.string.toCharArray()\n var w2 = readLine.string.toCharArray()\n\n def change(i1: Int, i2: Int) {\n val ch1 = w1(i1)\n w1(i1) = w2(i2)\n w2(i2) = ch1\n }\n \n def debugWords() {\n debug(s\"w1: \" + w1.mkString(\"\"))\n debug(s\"w2: \" + w2.mkString(\"\"))\n }\n \n var diffsL = List[Int]()\n for (i <- 0 until n) {\n if (w1(i) != w2(i)) diffsL ::= i\n }\n val diffs = diffsL.toArray.reverse\n val allLetters = diffs.flatMap(i => Array(w1(i), w2(i)))\n val evenNumber = allLetters.groupBy(x => x).mapValues(a => a.size % 2 == 0).values.forall(x => x)\n \n var res = if (evenNumber) {\n var steps = List[String]()\n def recordStep(ind1: Int, ind2: Int) = { steps ::= (ind1+1) + \" \" + (ind2+1) }\n for(st <- 0 until diffs.length) {\n val ind = diffs(st)\n val ch1 = w1(ind)\n debug(s\"Step. Pos:$st, ind:$ind, ch1:$ch1\")\n if (ch1 != w2(ind)) { //need to do something\n val inW1 = findAvailable(w1, diffs, st+1, ch1)\n if (inW1 != -1) { //one step\n change(inW1, ind)\n recordStep(inW1, ind)\n debug(\" only one step: \" + steps.head)\n } else {\n val inW2 = findAvailable(w2, diffs, st+1, ch1)\n val w1InterPos = diffs(st+1)\n change(w1InterPos, inW2)\n recordStep(w1InterPos, inW2)\n debug(\" first step: \" + steps.head)\n debugWords\n change(w1InterPos, ind)\n recordStep(w1InterPos, ind)\n debug(\" second step: \" + steps.head)\n }\n debugWords\n } else {\n debug(s\" -- nothing\")\n }\n \n }\n \n \"Yes\\n\" + steps.size + \"\\n\" + steps.reverse.mkString(\"\\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 def findAvailable(ww: Array[Char], diffs: Array[Int], fromDif: Int, ch: Char): Int = {\n for (i <- fromDif until diffs.length) {\n if (ww(diffs(i)) == ch) {\n return diffs(i)\n }\n }\n -1\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 = \"\"\"\n1\n3\nabc\nbca\n\"\"\"\n\nval sa3 = \"\"\"\n10100\n\"\"\"\n }\n}\n\n"}], "negative_code": [], "src_uid": "4985f4d65d636a006f2619ed821368ad"} {"nl": {"description": "The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai\u2009-\u2009x to ai\u2009+\u2009y, inclusive (numbers x,\u2009y\u2009\u2265\u20090 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai\u2009-\u2009x\u2009\u2264\u2009bj\u2009\u2264\u2009ai\u2009+\u2009y.", "input_spec": "The first input line contains four integers n, m, x and y (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 0\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009109) \u2014 the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) in non-decreasing order, separated by single spaces \u2014 the desired sizes of vests. The third line contains m integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009109) in non-decreasing order, separated by single spaces \u2014 the sizes of the available vests.", "output_spec": "In the first line print a single integer k \u2014 the maximum number of soldiers equipped with bulletproof vests. In the next k lines print k pairs, one pair per line, as \"ui vi\" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order. If there are multiple optimal answers, you are allowed to print any of them.", "sample_inputs": ["5 3 0 0\n1 2 3 3 4\n1 3 5", "3 3 2 2\n1 5 9\n3 5 7"], "sample_outputs": ["2\n1 1\n3 2", "3\n1 1\n2 2\n3 3"], "notes": "NoteIn the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped."}, "positive_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, (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}"}, {"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"} {"nl": {"description": "Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter \u2014 its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi\u2009>\u2009x) to leave to Vasya the chores with complexity less than or equal to x (hi\u2009\u2264\u2009x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a\u2009+\u2009b\u2009=\u2009n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?", "input_spec": "The first input line contains three integers n,\u2009a and b (2\u2009\u2264\u2009n\u2009\u2264\u20092000; a,\u2009b\u2009\u2265\u20091; a\u2009+\u2009b\u2009=\u2009n) \u2014 the total number of chores, the number of Petya's chores and the number of Vasya's chores. The next line contains a sequence of integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different. All numbers on the lines are separated by single spaces.", "output_spec": "Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.", "sample_inputs": ["5 2 3\n6 2 3 100 1", "7 3 4\n1 1 9 1 1 1 1"], "sample_outputs": ["3", "0"], "notes": "NoteIn the first sample the possible values of x are 3, 4 or 5.In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4."}, "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}"}, {"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}"}], "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"} {"nl": {"description": "Given an array $$$a$$$ of length $$$n$$$, find another array, $$$b$$$, of length $$$n$$$ such that: for each $$$i$$$ $$$(1 \\le i \\le n)$$$ $$$MEX(\\{b_1$$$, $$$b_2$$$, $$$\\ldots$$$, $$$b_i\\})=a_i$$$. The $$$MEX$$$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.If such array doesn't exist, determine this.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$0 \\le a_i \\le i$$$)\u00a0\u2014 the elements of the array $$$a$$$. It's guaranteed that $$$a_i \\le a_{i+1}$$$ for $$$1\\le i < n$$$. ", "output_spec": "If there's no such array, print a single line containing $$$-1$$$. Otherwise, print a single line containing $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, $$$\\ldots$$$, $$$b_n$$$ ($$$0 \\le b_i \\le 10^6$$$) If there are multiple answers, print any.", "sample_inputs": ["3\n1 2 3", "4\n0 0 0 2", "3\n1 1 3"], "sample_outputs": ["0 1 2", "1 3 4 0", "0 2 1"], "notes": "NoteIn the second test case, other answers like $$$[1,1,1,0]$$$, for example, are valid."}, "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 val n = nextInt\n val as = nextInts(n)\n val res = Array.ofDim[Int](n)\n\n val need = new java.util.TreeSet[Int]()\n var prev = -1\n for (a <- as) {\n if (prev < a) {\n prev += 1\n while (prev < a) {\n need.add(prev)\n prev += 1\n }\n }\n }\n\n var maxPrev = 0\n for (i <- 0 until n) {\n if (as(i) > maxPrev) {\n need.add(maxPrev)\n maxPrev = as(i)\n }\n if (!need.isEmpty) {\n res(i) = need.first()\n need.remove(res(i))\n } else if (as(i) == 0) {\n res(i) = n + 1\n } else {\n res(i) = as(i) - 1\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": "import java.util\n\nimport scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {\n\n val n = nextInt\n val as = nextInts(n)\n val res = Array.ofDim[Int](n)\n\n val need = new mutable.TreeSet[Int]()\n var prev = -1\n for (a <- as) {\n if (prev < a) {\n prev += 1\n while (prev < a) {\n need.add(prev)\n prev += 1\n }\n }\n }\n\n var maxPrev = 0\n for (i <- 0 until n) {\n if (need.nonEmpty) {\n res(i) = need.min\n need.remove(res(i))\n } else if (as(i) == 0) {\n res(i) = n + 1\n } else {\n res(i) = maxPrev\n }\n if (as(i) > maxPrev) {\n maxPrev = as(i)\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"}], "src_uid": "9a31d88a2fcaf8f3d059ef0e74d6e821"} {"nl": {"description": "Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.Formally, for a name si in the i-th line, output \"YES\" (without quotes) if there exists an index j such that si\u2009=\u2009sj and j\u2009<\u2009i, otherwise, output \"NO\" (without quotes).", "input_spec": "First line of input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100.", "output_spec": "Output n lines each containing either \"YES\" or \"NO\" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower).", "sample_inputs": ["6\ntom\nlucius\nginny\nharry\nginny\nharry", "3\na\na\na"], "sample_outputs": ["NO\nNO\nNO\nNO\nYES\nYES", "NO\nYES\nYES"], "notes": "NoteIn test case 1, for i\u2009=\u20095 there exists j\u2009=\u20093 such that si\u2009=\u2009sj and j\u2009<\u2009i, which means that answer for i\u2009=\u20095 is \"YES\"."}, "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}"}, {"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"}], "negative_code": [], "src_uid": "7f934f96cbe3990945e5ebcf5c208043"} {"nl": {"description": "Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n\u2009\u00d7\u2009m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.", "input_spec": "The first line contains 2 space-separated numbers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200925) \u2014 the office room dimensions. Then there follow n lines with m characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free.", "output_spec": "Output one number \u2014 the maximum possible perimeter of a bargaining table for Bob's office room.", "sample_inputs": ["3 3\n000\n010\n000", "5 4\n1100\n0000\n0000\n0000\n0000"], "sample_outputs": ["8", "16"], "notes": null}, "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, m) = readLine.split(\" \").map(_.toInt);\n var a = Array.ofDim[Char](n, m);\n for (i <- 0 until n) {\n a(i) = readLine.toArray;\n }\n var max = 0;\n for (i <- 0 until n) { //i - x1\n for (j <- 0 until m) { //j - y1\n for (ii <- i to n) { //ii - x2\n for (jj <- j to m) { //jj - y2\n var free = true;\n for (x <- i until ii) {\n for (y <- j until jj) {\n if (a(x)(y) == '1') free = false;\n }\n }\n if (free && (ii - i) != 0 && (jj - j) != 0) {\n max = math.max(max, (ii - i) * 2 + (jj - j) * 2);\n }\n }\n }\n }\n }\n println(max);\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 Array(n, m) = readLine.split(\" \").map(_.toInt);\n var a = Array.ofDim[Char](n, m);\n for (i <- 0 until n) {\n a(i) = readLine.toArray;\n }\n var max = 0;\n for (i <- 0 until n) {\n for (j <- 0 until m) {\n for (ii <- i to n) {\n for (jj <- j to m) {\n var free = true;\n for (x <- i until ii) {\n for (y <- j until jj) {\n if (a(x)(y) == '1') free = false;\n }\n }\n if (free) {\n max = math.max(max, (ii - i) * 2 + (jj - j) * 2);\n }\n }\n }\n }\n }\n println(max);\n }\n\n}"}], "src_uid": "99f1db0155f3d6dd580a2c1479c34585"} {"nl": {"description": "Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of rectangles. Each of the following n lines contains four integers x1,\u2009y1,\u2009x2,\u2009y2 (1\u2009\u2264\u2009x1\u2009\u2264\u2009x2\u2009\u2264\u2009100, 1\u2009\u2264\u2009y1\u2009\u2264\u2009y2\u2009\u2264\u2009100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle.", "output_spec": "In a single line print the sum of all values in the cells of the table.", "sample_inputs": ["2\n1 1 2 3\n2 2 3 3", "2\n1 1 3 3\n1 1 3 3"], "sample_outputs": ["10", "18"], "notes": "NoteNote to the first sample test:Values of the table in the first three rows and columns will be as follows:121121110So, the sum of values will be equal to 10.Note to the second sample test:Values of the table in the first three rows and columns will be as follows:222222222So, the sum of values will be equal to 18."}, "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 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"}, {"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}"}, {"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"}], "negative_code": [], "src_uid": "ca5c44093b1ab7c01970d83b5f49d0c6"} {"nl": {"description": "Mainak has an array $$$a_1, a_2, \\ldots, a_n$$$ of $$$n$$$ positive integers. He will do the following operation to this array exactly once: Pick a subsegment of this array and cyclically rotate it by any amount. Formally, he can do the following exactly once: Pick two integers $$$l$$$ and $$$r$$$, such that $$$1 \\le l \\le r \\le n$$$, and any positive integer $$$k$$$. Repeat this $$$k$$$ times: set $$$a_l=a_{l+1}, a_{l+1}=a_{l+2}, \\ldots, a_{r-1}=a_r, a_r=a_l$$$ (all changes happen at the same time). Mainak wants to maximize the value of $$$(a_n - a_1)$$$ after exactly one such operation. Determine the maximum value of $$$(a_n - a_1)$$$ that he can obtain.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 50$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 999$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the maximum value of $$$(a_n - a_1)$$$ that Mainak can obtain by doing the operation exactly once.", "sample_inputs": ["5\n\n6\n\n1 3 9 11 5 7\n\n1\n\n20\n\n3\n\n9 99 999\n\n4\n\n2 1 8 1\n\n3\n\n2 1 5"], "sample_outputs": ["10\n0\n990\n7\n4"], "notes": "Note In the first test case, we can rotate the subarray from index $$$3$$$ to index $$$6$$$ by an amount of $$$2$$$ (i.e. choose $$$l = 3$$$, $$$r = 6$$$ and $$$k = 2$$$) to get the optimal array: $$$$$$[1, 3, \\underline{9, 11, 5, 7}] \\longrightarrow [1, 3, \\underline{5, 7, 9, 11}]$$$$$$ So the answer is $$$a_n - a_1 = 11 - 1 = 10$$$. In the second testcase, it is optimal to rotate the subarray starting and ending at index $$$1$$$ and rotating it by an amount of $$$2$$$. In the fourth testcase, it is optimal to rotate the subarray starting from index $$$1$$$ to index $$$4$$$ and rotating it by an amount of $$$3$$$. So the answer is $$$8 - 1 = 7$$$."}, "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: 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"}, {"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"} {"nl": {"description": "There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that: Alice will get $$$a$$$ ($$$a > 0$$$) candies; Betty will get $$$b$$$ ($$$b > 0$$$) candies; each sister will get some integer number of candies; Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$); all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^9$$$) \u2014 the number of candies you have.", "output_spec": "For each test case, print the answer \u2014 the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.", "sample_inputs": ["6\n7\n1\n2\n3\n2000000000\n763243547"], "sample_outputs": ["3\n0\n0\n1\n999999999\n381621773"], "notes": "NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are: $$$a=6$$$, $$$b=1$$$; $$$a=5$$$, $$$b=2$$$; $$$a=4$$$, $$$b=3$$$. "}, "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": "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"}, {"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"} {"nl": {"description": "Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). Each of the next n\u2009-\u20091 lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n; ui\u2009\u2260\u2009vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).", "output_spec": "In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.", "sample_inputs": ["10\n2 1\n3 1\n4 2\n5 1\n6 2\n7 5\n8 6\n9 8\n10 5\n1 0 1 1 0 1 0 1 0 1\n1 0 1 0 0 1 1 1 0 1"], "sample_outputs": ["2\n4\n7"], "notes": null}, "positive_code": [{"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 mapping = Array.fill[List[Int]](n){ Nil }\n in.take(n - 1).map(_.split(' ').map(_.toInt - 1)).foreach {\n case Array(a, b) => \n mapping(a) ::= b\n mapping(b) ::= a\n }\n val init = in.next().split(' ').map(_.toInt)\n val goal = in.next().split(' ').map(_.toInt)\n val changes = Array.ofDim[Int](n)\n val changesNext = Array.ofDim[Int](n)\n val visited = Array.ofDim[Boolean](n)\n val current = mutable.Queue(0)\n var result = 0\n var res = List.empty[Int]\n\n while (current.nonEmpty) {\n val head = current.dequeue()\n visited(head) = true\n val newNodes = mapping(head).filterNot(visited)\n\n if ((init(head) + changes(head)) % 2 != goal(head)) {\n res ::= (head + 1)\n result += 1\n newNodes.foreach{i =>\n changesNext(i) = (changes(head) + 1) % 2\n changes(i) = changesNext(head)\n }\n } else {\n newNodes.foreach{i =>\n changes(i) = changesNext(head)\n changesNext(i) = changes(head)\n }\n }\n\n current.enqueue(newNodes: _*)\n }\n\n println(result)\n println(res.mkString(\"\\n\"))\n}"}], "negative_code": [], "src_uid": "f3a27e4dc3085712608ecf844e663dfd"} {"nl": {"description": "In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \\bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states: If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \\bmod n$$$. If it is anticlockwise, snakes can only go from room $$$(i+1) \\bmod n$$$ to $$$i$$$. If it is off, snakes can travel in either direction. Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$): the number of test cases. The description of the test cases follows. The first line of each test case description contains a single integer $$$n$$$ ($$$2 \\le n \\le 300\\,000$$$): the number of rooms. The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '<', '>' and '-'. If $$$s_{i} = $$$ '>', the $$$i$$$-th conveyor belt goes clockwise. If $$$s_{i} = $$$ '<', the $$$i$$$-th conveyor belt goes anticlockwise. If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off. It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\\,000$$$.", "output_spec": "For each test case, output the number of returnable rooms.", "sample_inputs": ["4\n4\n-><-\n5\n>>>>>\n3\n<--\n2\n<>"], "sample_outputs": ["3\n5\n3\n0"], "notes": "NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts."}, "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 = nextInt\n val s = nextLine\n val hasL = s.contains('<')\n val hasR = s.contains('>')\n\n val res = if (!hasL || !hasR) n\n else {\n var cnt = 0\n for (l <- 0 until n) {\n val r = (l + 1) % n\n if (s(l) == '-' || s(r) == '-') cnt += 1\n }\n cnt\n }\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": [], "src_uid": "f82685f41f4ba1146fea8e1eb0c260dc"} {"nl": {"description": "One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains n space-separated integers ri (1\u2009\u2264\u2009ri\u2009\u2264\u20091000) \u2014 the circles' radii. It is guaranteed that all circles are different.", "output_spec": "Print the single real number \u2014 total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10\u2009-\u20094.", "sample_inputs": ["1\n1", "3\n1 4 2"], "sample_outputs": ["3.1415926536", "40.8407044967"], "notes": "NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals \u03c0\u2009\u00d7\u200912\u2009=\u2009\u03c0.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (\u03c0\u2009\u00d7\u200942\u2009-\u2009\u03c0\u2009\u00d7\u200922)\u2009+\u2009\u03c0\u2009\u00d7\u200912\u2009=\u2009\u03c0\u2009\u00d7\u200912\u2009+\u2009\u03c0\u2009=\u200913\u03c0"}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "Colossal!\u00a0\u2014 exclaimed Hawk-nose.\u00a0\u2014 A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book \"Equations of Mathematical Magic\" Roman Oira-Oira and Cristobal Junta found an interesting equation: $$$a - (a \\oplus x) - x = 0$$$ for some given $$$a$$$, where $$$\\oplus$$$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $$$x$$$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.", "input_spec": "Each test contains several possible values of $$$a$$$ and your task is to find the number of equation's solution for each of them. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of these values. The following $$$t$$$ lines contain the values of parameter $$$a$$$, each value is an integer from $$$0$$$ to $$$2^{30} - 1$$$ inclusive.", "output_spec": "For each value of $$$a$$$ print exactly one integer\u00a0\u2014 the number of non-negative solutions of the equation for the given value of the parameter. Print answers in the same order as values of $$$a$$$ appear in the input. One can show that the number of solutions is always finite.", "sample_inputs": ["3\n0\n2\n1073741823"], "sample_outputs": ["1\n2\n1073741824"], "notes": "NoteLet's define the bitwise exclusive OR (XOR) operation. Given two integers $$$x$$$ and $$$y$$$, consider their binary representations (possibly with leading zeroes): $$$x_k \\dots x_2 x_1 x_0$$$ and $$$y_k \\dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of the number $$$x$$$ and $$$y_i$$$ is the $$$i$$$-th bit of the number $$$y$$$. Let $$$r = x \\oplus y$$$ be the result of the XOR operation of $$$x$$$ and $$$y$$$. Then $$$r$$$ is defined as $$$r_k \\dots r_2 r_1 r_0$$$ where:$$$$$$ r_i = \\left\\{ \\begin{aligned} 1, ~ \\text{if} ~ x_i \\ne y_i \\\\ 0, ~ \\text{if} ~ x_i = y_i \\end{aligned} \\right. $$$$$$For the first value of the parameter, only $$$x = 0$$$ is a solution of the equation.For the second value of the parameter, solutions are $$$x = 0$$$ and $$$x = 2$$$."}, "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 val pow2 = Array.ofDim[Long](32)\n pow2(0) = 1\n rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2)\n\n def solve(): Unit = {\n val t = ni()\n rep(t) { _ =>\n val a = ni()\n val ans = pow2(Integer.bitCount(a))\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}"}], "negative_code": [], "src_uid": "a896ba035e56dc707f8123b1e2f2b11c"} {"nl": {"description": "On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1\u2009\u2264\u2009i\u2009\u2264\u2009n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n\u2009-\u20091)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences \"2 3 4 5 5 4 3 2\" and \"1 2 3 2 1\" are beautiful, and '1 3 3 1\" and \"1 2 3 1\" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) which is the number of trees. The second line contains integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009105) which are the heights of the trees.", "output_spec": "Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.", "sample_inputs": ["3\n2 2 2", "4\n1 2 2 1"], "sample_outputs": ["1", "0"], "notes": null}, "positive_code": [{"source_code": "object P058C extends App {\n val n = readInt\n val a = readLine.split(' ').map(_.toInt)\n val target = List.range(0, n).map(i => if (i <= (n-1)/2) i+1 else n-i)\n val m = collection.mutable.Map[Int, Int]()\n a.zip(target).foreach(x=>m.update(x._1-x._2, m.getOrElse(x._1-x._2, 0)+1))\n var maxval = 0\n for (k <- m.keys) {\n if (k >= 0 && m(k) > maxval) {\n maxval = m(k)\n }\n }\n println(n-maxval)\n}\n"}], "negative_code": [], "src_uid": "391be6b61e289ec9c14222ea580cfcdc"} {"nl": {"description": "Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.In particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.$$$n$$$ participants have registered for the tournament so far, the $$$i$$$-th of them weighs $$$a_i$$$. To split participants into divisions, Monocarp is going to establish two integer weight boundaries $$$x$$$ and $$$y$$$ ($$$x < y$$$). All participants who weigh strictly less than $$$x$$$ will be considered lightweight. All participants who weigh greater or equal to $$$y$$$ will be considered heavyweight. The remaining participants will be considered middleweight.It's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.Note that Monocarp can't kick out any of the $$$n$$$ participants who have already registered for the tournament.However, he wants to invite as little extra participants as possible. Help Monocarp to choose $$$x$$$ and $$$y$$$ in such a way that the total amount of extra participants required is as small as possible. Output that amount.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of the registered participants. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the weights of the registered participants. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the smallest number of extra participants Monocarp is required to invite after he chooses the weight boundaries $$$x$$$ and $$$y$$$.", "sample_inputs": ["4\n\n4\n\n3 1 2 1\n\n1\n\n1\n\n6\n\n2 2 2 1 1 1\n\n8\n\n6 3 6 3 6 3 6 6"], "sample_outputs": ["0\n2\n3\n2"], "notes": "NoteIn the first testcase of the example, Monocarp can choose $$$x=2$$$ and $$$y=3$$$. Lightweight, middleweight and heavyweight divisions will have $$$2$$$, $$$1$$$ and $$$1$$$ participants, respectively. They all are powers of two, so no extra participants are required.In the second testcase of the example, regardless of the choice of $$$x$$$ and $$$y$$$, one division will have $$$1$$$ participant, the rest will have $$$0$$$. Thus, Monocarp will have to invite $$$1$$$ participant into both of the remaining divisions.In the third testcase of the example, Monocarp can choose $$$x=1$$$ and $$$y=2$$$. Lightweight, middleweight and heavyweight divisions will have $$$0$$$, $$$3$$$ and $$$3$$$ participants, respectively. So an extra participant is needed in each division.In the fourth testcase of the example, Monocarp can choose $$$x=8$$$ and $$$y=9$$$. Lightweight, middleweight and heavyweight divisions will have $$$8$$$, $$$0$$$ and $$$0$$$ participants, respectively. Middleweight and heavyweight division need an extra participant each."}, "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 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 arr = new Array[Long](n+1)\n val l = new Array[Long](n+2)\n val r = new Array[Long](n+2)\n val p = new Array[Long](40)\n for (i <- 1 to n) {\n arr(readInt()) += 1\n }\n for (i <- 1 to n) {\n l(i) = l(i-1) + arr(i)\n }\n for (i <- (1 to n).reverse) {\n r(i) = r(i+1) + arr(i)\n }\n p(0) = 1\n for (i <- 1 to 37) {\n p(i) = 2L * p(i-1)\n }\n var ans = p(37)\n var pl = 0\n var pr = 0\n var cnt = 0L\n var pm = 0\n for (i <- 0 to 36) {\n while (pl < n && l(pl+1) <= p(i)) {\n pl += 1\n }\n for (j <- 0 to 36) {\n pr = bs(pl+1, n+1, p(j)).toInt\n cnt = l(pr-1) - l(pl)\n pm = 0\n while (p(pm) < cnt) {\n pm += 1\n }\n ans = min(ans, p(i) + p(j) + p(pm) - l(pl) - r(pr) - cnt)\n }\n }\n writer.println(ans)\n\n def check(kk: Long, fi: Long): Boolean = {\n if (r(kk.toInt) <= fi)\n return true\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": "003a8719fbf3683671fafe3f01711a0a"} {"nl": {"description": "Hooray! Polycarp turned $$$n$$$ years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his $$$n$$$ birthdays: from the $$$1$$$-th to the $$$n$$$-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $$$1$$$, $$$77$$$, $$$777$$$, $$$44$$$ and $$$999999$$$. The following numbers are not beautiful: $$$12$$$, $$$11110$$$, $$$6969$$$ and $$$987654321$$$.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from $$$1$$$ to $$$n$$$ (inclusive) that are beautiful.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of one line, which contains a positive integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) \u2014 how many years Polycarp has turned.", "output_spec": "Print $$$t$$$ integers \u2014 the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $$$1$$$ and $$$n$$$, inclusive.", "sample_inputs": ["6\n18\n1\n9\n100500\n33\n1000000000"], "sample_outputs": ["10\n1\n9\n45\n12\n81"], "notes": "NoteIn the first test case of the example beautiful years are $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$, $$$8$$$, $$$9$$$ and $$$11$$$."}, "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 }"}, {"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"}], "negative_code": [], "src_uid": "99a5b21a5984d5248e82f843f82e9420"} {"nl": {"description": "Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer $$$n$$$. You need to find two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \\le l < r \\le 10^{18}$$$ and $$$l + (l + 1) + \\ldots + (r - 1) + r = n$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^{18}$$$).", "output_spec": "For each test case, print the two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \\le l < r \\le 10^{18}$$$ and $$$l + (l + 1) + \\ldots + (r - 1) + r = n$$$. It can be proven that an answer always exists. If there are multiple answers, print any.", "sample_inputs": ["7\n1\n2\n3\n6\n100\n25\n3000000000000"], "sample_outputs": ["0 1\n-1 2 \n1 2 \n1 3 \n18 22\n-2 7\n999999999999 1000000000001"], "notes": "NoteIn the first test case, $$$0 + 1 = 1$$$.In the second test case, $$$(-1) + 0 + 1 + 2 = 2$$$.In the fourth test case, $$$1 + 2 + 3 = 6$$$.In the fifth test case, $$$18 + 19 + 20 + 21 + 22 = 100$$$.In the sixth test case, $$$(-2) + (-1) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 25$$$."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "A Pythagorean triple is a triple of integer numbers $$$(a, b, c)$$$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $$$a$$$, $$$b$$$ and $$$c$$$, respectively. An example of the Pythagorean triple is $$$(3, 4, 5)$$$.Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $$$c = a^2 - b$$$.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $$$(3, 4, 5)$$$: $$$5 = 3^2 - 4$$$, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $$$(a, b, c)$$$ with $$$1 \\le a \\le b \\le c \\le n$$$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$).", "output_spec": "For each test case, print one integer \u2014 the number of triples of integers $$$(a, b, c)$$$ with $$$1 \\le a \\le b \\le c \\le n$$$ such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.", "sample_inputs": ["3\n3\n6\n9"], "sample_outputs": ["0\n1\n1"], "notes": "NoteThe only Pythagorean triple satisfying $$$c = a^2 - b$$$ with $$$1 \\le a \\le b \\le c \\le 9$$$ is $$$(3, 4, 5)$$$; that's why the answer for $$$n = 3$$$ is $$$0$$$, and the answer for $$$n = 6$$$ (and for $$$n = 9$$$) is $$$1$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "31064ad58b7802c32b3c51137057b6f5"} {"nl": {"description": "Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2\\leq n\\leq 10^5$$$)\u00a0\u2014 the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.", "output_spec": "Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.", "sample_inputs": ["5\n01011\n11001", "6\n011000\n010011"], "sample_outputs": ["4", "6"], "notes": "NoteIn the first sample, you can swap bits that have indexes $$$(1, 4)$$$, $$$(2, 3)$$$, $$$(3, 4)$$$, and $$$(3, 5)$$$.In the second example, you can swap bits that have indexes $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$, $$$(3, 5)$$$, and $$$(3, 6)$$$."}, "positive_code": [{"source_code": "object Main {\n import java.io._\n import java.util.Scanner\n\n import collection.mutable.HashMap\n import scala.collection.{SortedSet, mutable}\n import 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.nextLine.toInt\n val s1 = ins.nextLine\n val s2 = ins.nextLine\n var bothZero = 0L\n var allZeros = 0L\n var oneAndZero = 0L\n var allOnes = 0L\n for(i <- s1.indices) {\n if(s1(i) == '0') {\n allZeros += 1\n if(s2(i) == '0') {\n bothZero += 1\n }\n } else {\n allOnes += 1\n if(s2(i) == '0') {\n oneAndZero += 1\n }\n }\n }\n\n println(bothZero * allOnes + oneAndZero * allZeros - bothZero * oneAndZero)\n }\n\n }\n\n}\n\n\n"}], "negative_code": [], "src_uid": "621c82478be3dadcf60c383ba078a49e"} {"nl": {"description": "The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string \"RGBRGBRGB ...\".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings \"GBRG\", \"B\", \"BR\" are substrings of the infinite string \"RGBRGBRGB ...\" while \"GR\", \"RGR\" and \"GGG\" are not.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 2000$$$)\u00a0\u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2000$$$)\u00a0\u2014 the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\\sum n \\le 2000$$$).", "output_spec": "For each query print one integer\u00a0\u2014 the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string \"RGBRGBRGB ...\".", "sample_inputs": ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"], "sample_outputs": ["1\n0\n3"], "notes": "NoteIn the first example, you can change the first character to 'R' and obtain the substring \"RG\", or change the second character to 'R' and obtain \"BR\", or change the third, fourth or fifth character to 'B' and obtain \"GB\".In the second example, the substring is \"BRG\"."}, "positive_code": [{"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"}, {"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 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 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"}], "negative_code": [], "src_uid": "1aa8f887eb3b09decb223c71b40bb25b"} {"nl": {"description": "Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1\u2009\u2192\u20092\u2009\u2192\u20094\u2009\u2192\u20095. In one second, you can perform one of the two following operations: Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b; Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1\u2009\u2192\u20092\u2009\u2192\u2009...\u2009\u2192\u2009n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.", "input_spec": "The first line contains integers n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) and k (1\u2009\u2264\u2009k\u2009\u2264\u2009105) \u2014 the number of matryoshkas and matryoshka chains in the initial configuration. The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1\u2009\u2264\u2009mi\u2009\u2264\u2009n), and then mi numbers ai1,\u2009ai2,\u2009...,\u2009aimi \u2014 the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka). It is guaranteed that m1\u2009+\u2009m2\u2009+\u2009...\u2009+\u2009mk\u2009=\u2009n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.", "output_spec": "In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.", "sample_inputs": ["3 2\n2 1 2\n1 3", "7 3\n3 1 3 7\n2 2 5\n2 4 6"], "sample_outputs": ["1", "10"], "notes": "NoteIn the first sample test there are two chains: 1\u2009\u2192\u20092 and 3. In one second you can nest the first chain into the second one and get 1\u2009\u2192\u20092\u2009\u2192\u20093.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds."}, "positive_code": [{"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": "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": "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"}, {"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"}], "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"} {"nl": {"description": "Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.", "input_spec": "The first line of the input data contains an integer number n (3\u2009\u2264\u2009n\u2009\u2264\u2009106), n \u2014 the amount of hills around the capital. The second line contains n numbers \u2014 heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.", "output_spec": "Print the required amount of pairs.", "sample_inputs": ["5\n1 2 4 5 3"], "sample_outputs": ["7"], "notes": null}, "positive_code": [{"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"}, {"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 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"}], "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"} {"nl": {"description": "Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1\u2009\u2264\u2009i\u2009\u2264\u2009n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the length of the maximum non-decreasing subsegment of sequence a.", "sample_inputs": ["6\n2 2 1 3 4 1", "3\n2 2 9"], "sample_outputs": ["3", "3"], "notes": "NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one."}, "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": "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": "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": "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}"}, {"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 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": "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"} {"nl": {"description": "Vasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Then follow n lines. Each describes a laptop as speed ram hdd cost. Besides, speed, ram, hdd and cost are integers 1000\u2009\u2264\u2009speed\u2009\u2264\u20094200 is the processor's speed in megahertz 256\u2009\u2264\u2009ram\u2009\u2264\u20094096 the RAM volume in megabytes 1\u2009\u2264\u2009hdd\u2009\u2264\u2009500 is the HDD in gigabytes 100\u2009\u2264\u2009cost\u2009\u2264\u20091000 is price in tugriks All laptops have different prices.", "output_spec": "Print a single number \u2014 the number of a laptop Vasya will choose. The laptops are numbered with positive integers from 1 to n in the order in which they are given in the input data.", "sample_inputs": ["5\n2100 512 150 200\n2000 2048 240 350\n2300 1024 200 320\n2500 2048 80 300\n2000 512 180 150"], "sample_outputs": ["4"], "notes": "NoteIn the third sample Vasya considers the first and fifth laptops outdated as all of their properties cannot match those of the third laptop. The fourth one is the cheapest among the laptops that are left. Thus, Vasya chooses the fourth laptop."}, "positive_code": [{"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}"}, {"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 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}"}], "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"} {"nl": {"description": "You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i\u2009+\u20091 for all i: 1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) on every floor x, where a\u2009\u2264\u2009x\u2009\u2264\u2009b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta,\u2009fa), (tb,\u2009fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.", "input_spec": "The first line of the input contains following integers: n: the number of towers in the building (1\u2009\u2264\u2009n\u2009\u2264\u2009108), h: the number of floors in each tower (1\u2009\u2264\u2009h\u2009\u2264\u2009108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u2009h), k: total number of queries (1\u2009\u2264\u2009k\u2009\u2264\u2009104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1\u2009\u2264\u2009ta,\u2009tb\u2009\u2264\u2009n, 1\u2009\u2264\u2009fa,\u2009fb\u2009\u2264\u2009h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.", "output_spec": "For each query print a single integer: the minimum walking time between the locations in minutes.", "sample_inputs": ["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"], "sample_outputs": ["1\n4\n2"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\\sum\\limits_{i=1}^{n} (a_i \\cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \\cdot 1 - 2 \\cdot 1 - 3 \\cdot 1 + 4 \\cdot 2 - 5 \\cdot 2 + 6 \\cdot 3 - 7 \\cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 3 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$ |a_i| \\le 10^6$$$). ", "output_spec": "Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. ", "sample_inputs": ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"], "sample_outputs": ["15", "-45", "8"], "notes": null}, "positive_code": [{"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}"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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 // \u4e00\u756a\u5de6\u3092\uff12\u756a\u76ee\u4ee5\u964d\u306e\u30b0\u30eb\u30fc\u30d7\u306b\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u306a\u3044\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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"} {"nl": {"description": "Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \\ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \\le x \\le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \\leq x \\leq b$$$ and $$$c \\leq x \\leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.", "input_spec": "The first line contains integer number $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^{5}$$$)\u00a0\u2014 the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, output one integer\u00a0\u2014 the smallest possible length of the segment which has at least one common point with all given segments.", "sample_inputs": ["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"], "sample_outputs": ["2\n4\n0\n0"], "notes": "NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments."}, "positive_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(\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"}, {"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"}, {"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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\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}"}], "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"} {"nl": {"description": "The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most \u00ablucky\u00bb for him distribution of price tags) and the largest total price (in case of the most \u00abunlucky\u00bb for him distribution of price tags).", "input_spec": "The first line of the input contains two integer number n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains n space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following m lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to n. Also it is known that the seller has in stock all fruits that Valera wants to buy.", "output_spec": "Print two numbers a and b (a\u2009\u2264\u2009b) \u2014 the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.", "sample_inputs": ["5 3\n4 2 1 10 5\napple\norange\nmango", "6 5\n3 5 1 6 8 1\npeach\ngrapefruit\nbanana\norange\norange"], "sample_outputs": ["7 19", "11 30"], "notes": null}, "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"}, {"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"}], "negative_code": [], "src_uid": "31c43b62784a514cfdb9ebb835e94cad"} {"nl": {"description": "Yaroslav has an array, consisting of (2\u00b7n\u2009-\u20091) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains (2\u00b7n\u2009-\u20091) integers \u2014 the array elements. The array elements do not exceed 1000 in their absolute value.", "output_spec": "In a single line print the answer to the problem \u2014 the maximum sum that Yaroslav can get.", "sample_inputs": ["2\n50 50 50", "2\n-1 -100 -1"], "sample_outputs": ["150", "100"], "notes": "NoteIn the first sample you do not need to change anything. The sum of elements equals 150.In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100."}, "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": "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}"}, {"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"} {"nl": {"description": "In Berland, $$$n$$$ different types of banknotes are used. Banknotes of the $$$i$$$-th type have denomination $$$10^{a_i}$$$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $$$1$$$.Let's denote $$$f(s)$$$ as the minimum number of banknotes required to represent exactly $$$s$$$ burles. For example, if the denominations of banknotes used in Berland are $$$1$$$, $$$10$$$ and $$$100$$$, then $$$f(59) = 14$$$: $$$9$$$ banknotes with denomination of $$$1$$$ burle and $$$5$$$ banknotes with denomination of $$$10$$$ burles can be used to represent exactly $$$9 \\cdot 1 + 5 \\cdot 10 = 59$$$ burles, and there's no way to do it with fewer banknotes.For a given integer $$$k$$$, find the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes (that is, $$$f(s) > k$$$).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10; 1 \\le k \\le 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 = a_1 < a_2 < \\dots < a_n \\le 9$$$).", "output_spec": "For each test case, print one integer\u00a0\u2014 the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes.", "sample_inputs": ["4\n3 13\n0 1 2\n2 777\n0 4\n3 255\n0 1 3\n10 1000000000\n0 1 2 3 4 5 6 7 8 9"], "sample_outputs": ["59\n778\n148999\n999999920999999999"], "notes": null}, "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 val n = readInt()\n var k = readLong()+1L\n val a = new Array[Long](n)\n for (i <- 1 to n) {\n a(i-1) = pow(10, readInt()).toLong\n }\n var ans = 0L\n var ind = 0\n while (k > 0) {\n if (ind < n - 1) {\n val tmp = a(ind+1)/a(ind)-1\n ans += a(ind) * min(tmp, k).toLong\n k -= min(tmp, k)\n } else {\n ans += k * a(ind)\n k = 0\n }\n ind += 1\n }\n writer.println(ans)\n }\n writer.flush()\n}\n"}], "negative_code": [], "src_uid": "e25e44b8f300d6be856df50bff8ff244"} {"nl": {"description": "Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3,\u20094,\u20095), (5,\u200912,\u200913) and (6,\u20098,\u200910) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?", "input_spec": "The only line of the input contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009109)\u00a0\u2014 the length of some side of a right triangle.", "output_spec": "Print two integers m and k (1\u2009\u2264\u2009m,\u2009k\u2009\u2264\u20091018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print \u2009-\u20091 in the only line. If there are many answers, print any of them.", "sample_inputs": ["3", "6", "1", "17", "67"], "sample_outputs": ["4 5", "8 10", "-1", "144 145", "2244 2245"], "notes": "NoteIllustration for the first sample."}, "positive_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).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"}, {"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": "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"}], "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"} {"nl": {"description": "There are $$$n$$$ points on the plane, the $$$i$$$-th of which is at $$$(x_i, y_i)$$$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.The strange area is enclosed by three lines, $$$x = l$$$, $$$y = a$$$ and $$$x = r$$$, as its left side, its bottom side and its right side respectively, where $$$l$$$, $$$r$$$ and $$$a$$$ can be any real numbers satisfying that $$$l < r$$$. The upper side of the area is boundless, which you can regard as a line parallel to the $$$x$$$-axis at infinity. The following figure shows a strange rectangular area. A point $$$(x_i, y_i)$$$ is in the strange rectangular area if and only if $$$l < x_i < r$$$ and $$$y_i > a$$$. For example, in the above figure, $$$p_1$$$ is in the area while $$$p_2$$$ is not.Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\times 10^5$$$)\u00a0\u2014 the number of points on the plane. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$1 \\leq x_i, y_i \\leq 10^9$$$)\u00a0\u2014 the coordinates of the $$$i$$$-th point. All points are distinct.", "output_spec": "Print a single integer\u00a0\u2014 the number of different non-empty sets of points she can obtain.", "sample_inputs": ["3\n1 1\n1 2\n1 3", "3\n1 1\n2 1\n3 1", "4\n2 1\n2 2\n3 1\n3 2"], "sample_outputs": ["3", "6", "6"], "notes": "NoteFor the first example, there is exactly one set having $$$k$$$ points for $$$k = 1, 2, 3$$$, so the total number is $$$3$$$.For the second example, the numbers of sets having $$$k$$$ points for $$$k = 1, 2, 3$$$ are $$$3$$$, $$$2$$$, $$$1$$$ respectively, and their sum is $$$6$$$.For the third example, as the following figure shows, there are $$$2$$$ sets having one point; $$$3$$$ sets having two points; $$$1$$$ set having four points. Therefore, the number of different non-empty sets in this example is $$$2 + 3 + 0 + 1 = 6$$$. "}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n case class Coord(x: Int, y: Int)\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val C = Array.ofDim[Coord](N)\n val X = Array.ofDim[Int](N)\n val zip = new Zipper\n REP(N) { i =>\n val x, y = ni()\n C(i) = Coord(x, y)\n X(i) = x\n }\n sort(X)\n REP(N) { i =>\n zip.get(X(i))\n }\n\n // y\u964d\u9806\n java.util.Arrays.sort(C, new Comparator[Coord] {\n override def compare(o1: Coord, o2: Coord): Int = {\n -Integer.compare(o1.y, o2.y)\n }\n })\n\n\n var ans = 0L\n val bit = new BIT(zip.gen, 0)(_ + _)\n val cur = new java.util.TreeSet[Int]\n\n def calc(): Unit = {\n var pre = 0\n val it = cur.iterator()\n while(it.hasNext) {\n val j = it.next()\n if (bit.query(j, j + 1)(_-_) == 0) bit.add(j, 1)\n val s = bit.sum(j)\n val len = s - pre\n debug(s\"prev j:$j len:$len\")\n ans -= len.toLong * (len + 1) / 2\n pre = s + 1\n }\n\n {\n val s = bit.sumAll\n val len = s - pre\n debug(s\"prev j:last len:$len\")\n ans -= len.toLong * (len + 1) / 2\n }\n\n val len = bit.sumAll\n debug(s\"len:$len\")\n ans += len.toLong * (len + 1) / 2\n cur.clear()\n }\n\n var i = 0\n while(i < N) {\n while (i + 1 < N && C(i).y == C(i + 1).y) {\n cur.add(zip.get(C(i).x))\n i += 1\n }\n cur.add(zip.get(C(i).x))\n i += 1\n calc()\n }\n\n out.println(ans)\n }\n\n\n class Zipper {\n type A = Long\n var gen = 0\n val id = mutable.HashMap[A, Int]()\n\n def get(x: A): Int = {\n id.getOrElseUpdate(x, {\n val i = gen\n gen += 1\n i\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 }\nclass 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\u3068index\u9055\u3046\u3088\n * cumsum\u306a\u3093\u304b\u3068\u3044\u3063\u3057\u3087\n */\n def sum(i: Int): Int = {\n assert(i <= n)\n var x = i\n var s: Int = 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: 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 /**\n * [l, r)\n */\n def query(l: Int, r: Int)(sub: (Int, Int) => Int): Int = {\n assert(r > l)\n sub(sum(r), sum(l))\n }\n\n def lowerBound(W: Int)(sub: (Int, Int) => Int, lt: (Int, Int) => 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}"}], "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n case class Coord(x: Int, y: Int)\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val C = Array.ofDim[Coord](N)\n REP(N) { i =>\n val x, y = ni()\n C(i) = Coord(x, y)\n }\n\n // y\u964d\u9806\n sort(C, new Comparator[Coord] {\n override def compare(o1: Coord, o2: Coord): Int = {\n -Integer.compare(o1.y, o2.y)\n }\n })\n\n var ans = 0L\n val xs = mutable.Set[Int]()\n REP(N) { i =>\n if (i > 0 && C(i - 1).y != C(i).y) {\n val len = xs.size.toLong\n ans += len * (len + 1) / 2\n }\n xs += C(i).x\n }\n val len = xs.size.toLong\n ans += len * (len + 1) / 2\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n case class Coord(x: Int, y: Int)\n\n def solve(): Unit = {\n import java.util.Comparator\n val N = ni()\n val C = Array.ofDim[Coord](N)\n REP(N) { i =>\n val x, y = ni()\n C(i) = Coord(x, y)\n }\n\n // y\u964d\u9806\n sort(C, new Comparator[Coord] {\n override def compare(o1: Coord, o2: Coord): Int = {\n -Integer.compare(o1.y, o2.y)\n }\n })\n\n var ans = 0L\n val pre = mutable.Set[Int]()\n val xs = mutable.Set[Int]()\n REP(N) { i =>\n if (i > 0 && C(i - 1).y != C(i).y) {\n val len2 = pre.size.toLong\n pre ++= xs\n val len1 = pre.size.toLong\n debug(s\"len1:$len1 len2:$len2\")\n ans += len1 * (len1 + 1) / 2 - len2 * (len2 + 1) / 2\n pre ++= xs\n xs.clear()\n }\n pre -= C(i).x\n xs += C(i).x\n }\n val len2 = pre.size.toLong\n pre ++= xs\n val len1 = pre.size.toLong\n debug(s\"len1:$len1 len2:$len2\")\n ans += len1 * (len1 + 1) / 2 - len2 * (len2 + 1) / 2\n\n out.println(ans)\n }\n}"}], "src_uid": "a45a5a4b95f97a49960bc86953dd8723"} {"nl": {"description": "Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i < c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \\cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output \"NO ESCAPE\" if no matter what path Ram takes, he cannot escape the clutches of Raghav. ", "input_spec": "The first line of input contains $$$t$$$ ($$$1 \\leq t \\leq 5 \\cdot 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \\leq n, m \\leq 10^5$$$; $$$1 \\leq k \\leq 10^5$$$)\u00a0\u2014 the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$1 \\leq x_i \\leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \\leq a_i < c_i \\leq n$$$; $$$1 \\leq b_i, d_i \\leq m$$$; $$$1 \\leq h_i \\leq 10^6$$$) \u00a0\u2014 the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i < c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.", "output_spec": "Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output \"NO ESCAPE\" (all uppercase, without quotes).", "sample_inputs": ["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"], "sample_outputs": ["16\nNO ESCAPE\n-90\n27"], "notes": "NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \\begin{align*} &\\mathrel{\\phantom{=}} x_1 \\cdot |1-3| - h_1 + x_3 \\cdot |3-2| - h_3 + x_5 \\cdot |1-3| \\\\ &= 5 \\cdot 2 - 4 + 8 \\cdot 1 - 6 + 4 \\cdot 2 \\\\ &= 16. \\end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \\begin{align*} &\\mathrel{\\phantom{=}} x_1 \\cdot |1-3| - h_1 + x_3 \\cdot |3-1| - h_2 + a_5 \\cdot |2-3| \\\\ &= 5 \\cdot 2 - 4 + 8 \\cdot 2 - 5 + 4 \\cdot 1 \\\\ &= 21. \\end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \\cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path)."}, "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, 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 n = readInt()\n val m = readInt()\n val k = readInt()\n val x = new Array[Long](n+1)\n for (i <- 1 to n) {\n x(i) = readInt()\n }\n val s = new Array[Vector[Int]](n+1)\n val e = new Array[Vector[Int]](n+1)\n for (i <- 1 to n) {\n s(i) = Vector[Int]()\n e(i) = Vector[Int]()\n }\n val l = new Array[pair](k+1)\n val d = new Array[Long](k+1)\n var i1 = 0\n var i2 = 0\n var i3 = 0\n var i4 = 0\n var i5 = 0\n for (i <- 1 to k) {\n i1 = readInt()\n i2 = readInt()\n i3 = readInt()\n i4 = readInt()\n i5 = readInt()\n s(i1) +:= i\n e(i3) +:= i\n l(i) = pair(i2, i4, i5)\n }\n var tmp = pair(0, 0, 0)\n for (i <- e(n).indices) {\n tmp = l(e(n)(i))\n d(e(n)(i)) = (m-tmp.b).toLong * x(n) - tmp.c\n }\n val inf = (1e18 + 1).toLong\n for (j <- (1 until n).reverse) {\n var lad = Vector[pair]()\n for (i <- s(j).indices) {\n lad +:= pair(l(s(j)(i)).a, s(j)(i), 0)\n }\n for (i <- e(j).indices) {\n lad +:= pair(l(e(j)(i)).b, e(j)(i), 1)\n }\n lad = lad.sorted\n var ans = inf\n for (i <- lad.indices) {\n if (i != 0) {\n if (ans != inf) {\n ans += x(j) * (lad(i).a - lad(i-1).a)\n }\n }\n if (lad(i).c == 0) {\n ans = min(ans, d(lad(i).b))\n } else {\n d(lad(i).b) = ans\n }\n }\n ans = inf\n for (i <- (lad.indices).reverse) {\n if (i != lad.length-1) {\n if (ans != inf) {\n ans += x(j) * (lad(i+1).a - lad(i).a)\n }\n }\n if (lad(i).c == 0) {\n ans = min(ans, d(lad(i).b))\n } else {\n d(lad(i).b) = min(d(lad(i).b), ans)\n if (d(lad(i).b) != inf) {\n d(lad(i).b) -= l(lad(i).b).c\n }\n }\n }\n }\n var ans = inf\n for (i <- s(1).indices) {\n if (d(s(1)(i)) != inf) {\n ans = min(ans, d(s(1)(i)) + x(1) * (l(s(1)(i)).a - 1))\n }\n }\n if (ans == inf) {\n writer.println(\"NO ESCAPE\")\n } else {\n writer.println(ans)\n }\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": "0c2fd0e84b88d407a3bd583d8879de34"} {"nl": {"description": "Let's consider all integers in the range from $$$1$$$ to $$$n$$$ (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $$$\\mathrm{gcd}(a, b)$$$, where $$$1 \\leq a < b \\leq n$$$.The greatest common divisor, $$$\\mathrm{gcd}(a, b)$$$, of two positive integers $$$a$$$ and $$$b$$$ is the biggest integer that is a divisor of both $$$a$$$ and $$$b$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 10^6$$$).", "output_spec": "For each test case, output the maximum value of $$$\\mathrm{gcd}(a, b)$$$ among all $$$1 \\leq a < b \\leq n$$$.", "sample_inputs": ["2\n3\n5"], "sample_outputs": ["1\n2"], "notes": "NoteIn the first test case, $$$\\mathrm{gcd}(1, 2) = \\mathrm{gcd}(2, 3) = \\mathrm{gcd}(1, 3) = 1$$$.In the second test case, $$$2$$$ is the maximum possible value, corresponding to $$$\\mathrm{gcd}(2, 4)$$$."}, "positive_code": [{"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}"}, {"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"}, {"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}"}], "negative_code": [], "src_uid": "b46244f39e30c0cfab592a97105c60f4"} {"nl": {"description": "You are given an array a1,\u2009a2,\u2009...,\u2009an and m sets S1,\u2009S2,\u2009...,\u2009Sm of indices of elements of this array. Let's denote Sk\u2009=\u2009{Sk,\u2009i}\u00a0(1\u2009\u2264\u2009i\u2009\u2264\u2009|Sk|). In other words, Sk,\u2009i is some element from set Sk.In this problem you have to answer q queries of the two types: Find the sum of elements with indices from set Sk: . The query format is \"? k\". Add number x to all elements at indices from set Sk: aSk,\u2009i is replaced by aSk,\u2009i\u2009+\u2009x for all i (1\u2009\u2264\u2009i\u2009\u2264\u2009|Sk|). The query format is \"+ k x\". After each first type query print the required sum.", "input_spec": "The first line contains integers n,\u2009m,\u2009q (1\u2009\u2264\u2009n,\u2009m,\u2009q\u2009\u2264\u2009105). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009108) \u2014 elements of array a. Each of the following m lines describes one set of indices. The k-th line first contains a positive integer, representing the number of elements in set (|Sk|), then follow |Sk| distinct integers Sk,\u20091,\u2009Sk,\u20092,\u2009...,\u2009Sk,\u2009|Sk| (1\u2009\u2264\u2009Sk,\u2009i\u2009\u2264\u2009n) \u2014 elements of set Sk. The next q lines contain queries. Each query looks like either \"? k\" or \"+ k x\" and sits on a single line. For all queries the following limits are held: 1\u2009\u2264\u2009k\u2009\u2264\u2009m, |x|\u2009\u2264\u2009108. The queries are given in order they need to be answered. It is guaranteed that the sum of sizes of all sets Sk doesn't exceed 105.", "output_spec": "After each first type query print the required sum on a single line. Please, do not write the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["5 3 5\n5 -5 5 1 -4\n2 1 2\n4 2 1 4 5\n2 2 5\n? 2\n+ 3 4\n? 1\n+ 2 1\n? 2"], "sample_outputs": ["-3\n4\n9"], "notes": null}, "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 => {\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}"}, {"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"} {"nl": {"description": "Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect the sum x with the minimum amount of coins. Greedy algorithm with each its step takes the coin of the highest face value, not exceeding x. Obviously, if among the coins' face values exists the face value 1, any sum x can be collected with the help of greedy algorithm. However, greedy algorithm does not always give the optimal representation of the sum, i.e. the representation with the minimum amount of coins. For example, if there are face values {1,\u20093,\u20094} and it is asked to collect the sum 6, greedy algorithm will represent the sum as 4\u2009+\u20091\u2009+\u20091, while the optimal representation is 3\u2009+\u20093, containing one coin less. By the given set of face values find out if there exist such a sum x that greedy algorithm will collect in a non-optimal way. If such a sum exists, find out the smallest of these sums.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009400) \u2014 the amount of the coins' face values. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), describing the face values. It is guaranteed that a1\u2009>\u2009a2\u2009>\u2009...\u2009>\u2009an and an\u2009=\u20091.", "output_spec": "If greedy algorithm collects any sum in an optimal way, output -1. Otherwise output the smallest sum that greedy algorithm collects in a non-optimal way.", "sample_inputs": ["5\n25 10 5 2 1", "3\n4 3 1"], "sample_outputs": ["-1", "6"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nobject GreedyChoice3 extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(x => s.nextLong()).toArray\n coins(n - 1) = 1\n val g = Array.ofDim[Int](n)\n var cnt = 0\n var min = Long.MaxValue\n val arr = Array.ofDim[Long](n)\n var len = 0\n var i = 1\n var j = 0\n while (i < n) {\n j = 0\n val v1 = greedy(coins(i - 1) - 1).map(x => x)\n while (j < n) {\n val(s, vs) = dot(v1, j)\n val w = greedy(s)\n val ws = svv()\n if (ws > vs && s < min) {\n min = s\n }\n j += 1\n }\n i += 1\n }\n\n def svv(): Long = {\n var i = 0\n var sum = 0L\n while (i < len + 1) {\n sum += arr(i)\n i += 1\n }\n sum\n }\n\n if (min == Long.MaxValue) {\n println(\"-1\")\n } else {\n println(min)\n }\n\n def dot(a: Array[Long], j: Int): (Long, Long) = {\n if (j == 0) {\n return (0, Long.MaxValue)\n }\n var i = 0\n var sum = 0L\n var sum1 = 0L\n while (i < j) {\n sum += coins(i) * a(i)\n sum1 += (a(i))\n i += 1\n }\n sum += coins(j) * (a(j) + 1)\n sum1 += a(j) + 1\n (sum, sum1)\n }\n\n def greedy(v: Long): Array[Long] = {\n var s = v\n var i = 0\n i = 0\n /* while (i < n) {\n arr(i) = 0\n i += 1\n }*/\n i = 0\n arr(i) = 0\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n arr(i) = 0\n } else {\n val mod = s % coins(i)\n arr(i) += (s / coins(i))\n s = mod\n }\n }\n len = i\n arr\n }\n\n}\n"}], "negative_code": [{"source_code": "import java.util.Scanner\n\nobject GreedyChoice2 extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(_ => s.nextInt())\n val g = Array.ofDim[Int](n)\n var cnt = 0\n var min = Integer.MAX_VALUE\n\n var i = 1\n var j = 0\n while (i < n) {\n j = 0\n val v = greedy(coins(i - 1) - 1)\n val vs = v.sum + 1\n while (j < n) {\n val s = dot(v, j)\n val w = greedy(s)\n val ws = w.sum\n if (ws > vs && s < min) {\n min = s\n }\n j += 1\n }\n i += 1\n }\n\n if (min == Integer.MAX_VALUE) {\n println(\"-1\")\n } else {\n println(min)\n }\n\n def dot(a: Array[Int], j: Int): Int = {\n var i = 0\n var sum = 0\n while (i < j) {\n sum += coins(i) * a(i)\n i += 1\n }\n sum += coins(j) * (a(j) + 1)\n sum\n }\n\n def greedy(v: Int): Array[Int] = {\n val arr = Array.ofDim[Int](n)\n var s = v\n var i = 0\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n s -= coins(i)\n arr(i) += 1\n }\n }\n arr\n }\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject GreedyChoice extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (Integer.MAX_VALUE :: (0 until n).map(_ => s.nextInt()).toList)\n\n if (n == 1) {\n println(\"-1\")\n } else {\n val ans = (1 until n + 1).map(check)\n if (ans.forall(_ == true)) {\n println(\"-1\")\n } else {\n val t = ans.zipWithIndex.reverse.find(_._1 == false).get._2\n val ceil = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt\n val result = ceil * coins(t)\n println(result)\n }\n }\n\n def ceil(t: Int): Int = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt\n\n def check(t: Int): Boolean = {\n val mt = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt\n val st = mt * coins(t)\n var s = st - coins(t - 1)\n var g = 0\n var i = t\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n s -= coins(i)\n g += 1\n }\n }\n (g <= mt - 1)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject GreedyChoice2 extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(_ => s.nextInt())\n val g = Array.ofDim[Int](n)\n var cnt = 0\n var min = Long.MaxValue\n\n var i = 1\n var j = 0\n while (i < n) {\n j = 0\n val v = greedy(coins(i - 1) - 1)\n while (j < n) {\n val s = dot(v, j)\n val vs = v.take(j).sum + 1\n val w = greedy(s)\n val ws = w.sum\n if (ws > vs && s < min) {\n min = s\n }\n j += 1\n }\n i += 1\n }\n\n if (min == Long.MaxValue) {\n println(\"-1\")\n } else {\n println(min)\n }\n\n def dot(a: Array[Long], j: Int): Long = {\n var i = 0\n var sum = 0L\n while (i < j) {\n sum += coins(i) * a(i)\n i += 1\n }\n sum += coins(j) * (a(j) + 1)\n sum\n }\n\n def greedy(v: Long): Array[Long] = {\n val arr = Array.ofDim[Long](n)\n var s = v\n var i = 0\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n val mod = s % coins(i)\n arr(i) += (s / coins(i))\n s = mod\n }\n }\n arr\n }\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject GreedyChoice extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(_ => s.nextInt())\n\n if (n == 1) {\n println(\"-1\")\n } else {\n val ans = (1 until n).map(check)\n if (ans.forall(_ == true)) {\n println(\"-1\")\n } else {\n val t = ans.zipWithIndex.find(_._1 == false).get._2 + 1\n val result = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt * coins(t)\n println(result)\n }\n }\n\n\n\n def check(t: Int): Boolean = {\n val mt = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt\n val st = mt * coins(t)\n var s = st - coins(t - 1)\n var g = 0\n var i = t\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n s -= coins(i)\n g += 1\n }\n }\n (g <= mt - 1)\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject GreedyChoice3 extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(x => s.nextLong()).toArray\n coins(n - 1) = 1\n val g = Array.ofDim[Int](n)\n var cnt = 0\n var min = Long.MaxValue\n val arr = Array.ofDim[Long](n)\n\n var i = 1\n var j = 0\n while (i < n) {\n j = 0\n val v1 = greedy(coins(i - 1) - 1).map(x => x)\n while (j < n) {\n val(s, vs) = dot(v1, j)\n val w = greedy(s)\n val ws = w.sum\n if (ws > vs && s < min) {\n min = s\n }\n j += 1\n }\n i += 1\n }\n\n if (min == Long.MaxValue) {\n println(\"-1\")\n } else {\n println(min)\n }\n\n def dot(a: Array[Long], j: Int): (Long, Long) = {\n\n if (j == 0) {\n return (0, Long.MaxValue)\n }\n var i = 0\n var sum = 0L\n var sum1 = 0L\n while (i < j) {\n sum += coins(i) * a(i)\n sum1 += (a(i))\n i += 1\n }\n sum += coins(j) * (a(j) + 1)\n sum1 += 1\n (sum, sum1)\n }\n\n def greedy(v: Long): Array[Long] = {\n var s = v\n var i = 0\n while (i < n) {\n arr(i) = 0\n i += 1\n }\n i = 0\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n val mod = s % coins(i)\n arr(i) += (s / coins(i))\n s = mod\n }\n }\n arr\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject GreedyChoice2 extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(_ => s.nextInt())\n val g = Array.ofDim[Int](n)\n var cnt = 0\n var min = Long.MaxValue\n\n var i = 1\n var j = 0\n while (i < n) {\n j = 0\n val v = greedy(coins(i - 1) - 1)\n val vs = v.sum + 1\n while (j < n) {\n val s = dot(v, j)\n val w = greedy(s)\n val ws = w.sum\n if (ws > vs && s < min) {\n min = s\n }\n j += 1\n }\n i += 1\n }\n\n if (min == Long.MaxValue) {\n println(\"-1\")\n } else {\n println(min)\n }\n\n def dot(a: Array[Long], j: Int): Long = {\n var i = 0\n var sum = 0L\n while (i < j) {\n sum += coins(i) * a(i)\n i += 1\n }\n sum += coins(j) * (a(j) + 1)\n sum\n }\n\n def greedy(v: Long): Array[Long] = {\n val arr = Array.ofDim[Long](n)\n var s = v\n var i = 0\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n s -= coins(i)\n arr(i) += 1\n }\n }\n arr\n }\n\n}\n"}, {"source_code": "import java.util.Scanner\n\nobject GreedyChoice2 extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(_ => s.nextInt())\n val g = Array.ofDim[Int](n)\n var cnt = 0\n var min = Long.MaxValue\n\n var i = 1\n var j = 0\n while (i < n) {\n j = 0\n val v = greedy(coins(i - 1) - 1)\n val vs = v.sum + 1\n while (j < n) {\n val s = dot(v, j)\n val w = greedy(s)\n val ws = w.sum\n if (ws > vs && s < min) {\n min = s\n }\n j += 1\n }\n i += 1\n }\n\n if (min == Long.MaxValue) {\n println(\"-1\")\n } else {\n println(min)\n }\n\n def dot(a: Array[Long], j: Int): Long = {\n var i = 0\n var sum = 0L\n while (i < j) {\n sum += coins(i) * a(i)\n i += 1\n }\n sum += coins(j) * (a(j) + 1)\n sum\n }\n\n def greedy(v: Long): Array[Long] = {\n val arr = Array.ofDim[Long](n)\n var s = v\n var i = 0\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n val mod = s % coins(i)\n arr(i) += (s / coins(i))\n s = mod\n }\n }\n arr\n }\n\n}\n"}, {"source_code": "//package me.jetblack.cf\n\nimport java.util.Scanner\n\nobject GreedyChoice extends App {\n\n val s = new Scanner(System.in)\n val n = s.nextInt()\n val coins = (0 until n).map(_ => s.nextInt())\n\n if (n == 1) {\n println(\"-1\")\n } else {\n val ans = (1 until n).map(check)\n if (ans.forall(_ == true)) {\n println(\"-1\")\n } else {\n val t = ans.zipWithIndex.reverse.find(_._1 == true).get._2\n val result = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt * coins(t)\n println(result)\n }\n }\n\n\n\n def check(t: Int): Boolean = {\n val mt = math.ceil(coins(t - 1).toDouble / coins(t).toDouble).toInt\n val st = mt * coins(t)\n var s = st - coins(t - 1)\n var g = 0\n var i = t\n while (s != 0) {\n if (coins(i) > s) {\n i += 1\n } else {\n s -= coins(i)\n g += 1\n }\n }\n (g <= mt - 1)\n }\n\n}\n"}], "src_uid": "c592778fe180234ab007f113f2440393"} {"nl": {"description": "You are given an array of n integer numbers a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.", "input_spec": "The first line contains positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 size of the given array. The second line contains n integers a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the array. It is guaranteed that in the array a minimum occurs at least two times.", "output_spec": "Print the only number \u2014 distance between two nearest minimums in the array.", "sample_inputs": ["2\n3 3", "3\n5 6 5", "9\n2 1 3 5 4 1 2 3 1"], "sample_outputs": ["1", "2", "3"], "notes": null}, "positive_code": [{"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"}, {"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": "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}"}, {"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}"}], "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"} {"nl": {"description": "The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui\u2009=\u2009(ui,\u20091,\u2009ui,\u20092,\u2009...,\u2009ui,\u2009|Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.We'll say that the secret is safe if the following conditions are hold: for any two indexes i,\u2009j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009k) the intersection of sets Ui and Uj is an empty set; the union of sets U1,\u2009U2,\u2009...,\u2009Uk is set (1,\u20092,\u2009...,\u2009n); in each set Ui, its elements ui,\u20091,\u2009ui,\u20092,\u2009...,\u2009ui,\u2009|Ui| do not form an arithmetic progression (in particular, |Ui|\u2009\u2265\u20093 should hold). Let us remind you that the elements of set (u1,\u2009u2,\u2009...,\u2009us) form an arithmetic progression if there is such number d, that for all i (1\u2009\u2264\u2009i\u2009<\u2009s) fulfills ui\u2009+\u2009d\u2009=\u2009ui\u2009+\u20091. For example, the elements of sets (5), (1,\u200910) and (1,\u20095,\u20099) form arithmetic progressions and the elements of sets (1,\u20092,\u20094) and (3,\u20096,\u20098) don't.Your task is to find any partition of the set of words into subsets U1,\u2009U2,\u2009...,\u2009Uk so that the secret is safe. Otherwise indicate that there's no such partition.", "input_spec": "The input consists of a single line which contains two integers n and k (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.", "output_spec": "If there is no way to keep the secret safe, print a single integer \"-1\" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret. If there are multiple solutions, print any of them.", "sample_inputs": ["11 3", "5 2"], "sample_outputs": ["3 1 2 1 1 2 3 2 2 3 1", "-1"], "notes": null}, "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 if(n 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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val m = (N - 1 + 2 - 1) / 2 + 1\n val ans = Array.ofDim[(Int, Int)](N)\n\n REP(N / 2) { i =>\n ans(i) = (1, i + 1)\n }\n REP(N / 2) { i =>\n ans(N - 1 - i) = (m, m - i)\n }\n if (N % 2 == 1) ans(N / 2) = (1, N / 2 + 1)\n\n debug(s\"m:$m\")\n debug(ans.mkString(\" \"))\n\n out.println(m)\n REP(N) { i =>\n out.println(s\"${ans(i)._1} ${ans(i)._2}\")\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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N = ni()\n val m = (N - 1 + 2) / 2 + 1\n val ans = Array.ofDim[(Int, Int)](N)\n REP(N / 2) { i =>\n ans(i) = (1, i + 1)\n }\n REP(N / 2) { i =>\n ans(N - 1 - i) = (m, m - i)\n }\n if (N % 2 == 1) ans(N / 2) = (1, N / 2 + 1)\n\n debug(s\"m:$m\")\n debug(ans.mkString(\" \"))\n\n out.println(m)\n REP(N) { i =>\n out.println(s\"${ans(i)._1} ${ans(i)._2}\")\n }\n }\n}"}], "src_uid": "6bd7cab93a779e066af39a671aba3239"} {"nl": {"description": "In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li.Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.Sticks with lengths a1, a2, a3 and a4 can make a rectangle if the following properties are observed: a1\u2009\u2264\u2009a2\u2009\u2264\u2009a3\u2009\u2264\u2009a4 a1\u2009=\u2009a2 a3\u2009=\u2009a4 A rectangle can be made of sticks with lengths of, for example, 3\u00a03\u00a03\u00a03 or 2\u00a02\u00a04\u00a04. A rectangle cannot be made of, for example, sticks 5\u00a05\u00a05\u00a07.Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4.You have to answer the question \u2014 what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014\u00a0the number of the available sticks. The second line of the input contains n positive integers li (2\u2009\u2264\u2009li\u2009\u2264\u2009106)\u00a0\u2014\u00a0the lengths of the sticks.", "output_spec": "The first line of the output must contain a single non-negative integer\u00a0\u2014\u00a0the maximum total area of the rectangles that Ilya can make from the available sticks.", "sample_inputs": ["4\n2 4 4 2", "4\n2 2 3 5", "4\n100003 100004 100005 100006"], "sample_outputs": ["8", "0", "10000800015"], "notes": null}, "positive_code": [{"source_code": "import java.io._\n\nimport scala.collection.mutable.ArrayBuffer\n\nobject C {\n\n def main(args: Array[String]) {\n new C().run()\n }\n}\n\nclass C {\n\n var in: StreamTokenizer = _\n\n var out: PrintWriter = _\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\n def nextDouble(): Double = {\n in.nextToken()\n in.nval\n }\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 run() {\n in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)))\n out = new PrintWriter(new OutputStreamWriter(System.out))\n solve()\n out.flush()\n }\n\n\n def solve() {\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(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}"}, {"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 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"}, {"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}"}, {"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"}], "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"} {"nl": {"description": "Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.", "input_spec": "The first line contains number n \u2014 the number of techniques that the wrestlers have used (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The following n lines contain integer numbers ai (|ai|\u2009\u2264\u2009109, ai\u2009\u2260\u20090). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with (\u2009-\u2009ai) points. The techniques are given in chronological order.", "output_spec": "If the first wrestler wins, print string \"first\", otherwise print \"second\"", "sample_inputs": ["5\n1\n2\n-3\n-4\n3", "3\n-1\n-2\n3", "2\n4\n-4"], "sample_outputs": ["second", "first", "second"], "notes": "NoteSequence x\u2009\u2009=\u2009\u2009x1x2... x|x| is lexicographically larger than sequence y\u2009\u2009=\u2009\u2009y1y2... y|y|, if either |x|\u2009\u2009>\u2009\u2009|y| and x1\u2009\u2009=\u2009\u2009y1,\u2009\u2009x2\u2009\u2009=\u2009\u2009y2,\u2009... ,\u2009\u2009x|y|\u2009\u2009=\u2009\u2009y|y|, or there is such number r (r\u2009\u2009<\u2009\u2009|x|,\u2009r\u2009\u2009<\u2009\u2009|y|), that x1\u2009\u2009=\u2009\u2009y1,\u2009\u2009x2\u2009\u2009=\u2009\u2009y2,\u2009\u2009... ,\u2009\u2009xr\u2009\u2009=\u2009\u2009yr and xr\u2009\u2009+\u2009\u20091\u2009\u2009>\u2009\u2009yr\u2009\u2009+\u2009\u20091.We use notation |a| to denote length of sequence a."}, "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"}, {"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}"}], "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"} {"nl": {"description": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, \"localization\" will be spelt as \"l10n\", and \"internationalization\u00bb will be spelt as \"i18n\".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.", "output_spec": "Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.", "sample_inputs": ["4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis"], "sample_outputs": ["word\nl10n\ni18n\np43s"], "notes": null}, "positive_code": [{"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.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": "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": "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 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": "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.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": "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 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 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 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": "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": "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": "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.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": "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": "/*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": "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": "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.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 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": "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 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 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 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": "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 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": "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 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": "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": "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": "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": "\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": "/**\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": "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": "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 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.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 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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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 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": "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 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 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 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 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 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 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.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": "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.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": "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 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": "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.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": "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": "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 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": "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": "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": "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": "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": "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.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": "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\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": "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 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": "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.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": "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 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": "/**\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 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 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 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 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": "\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": "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": "// 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": "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": "/*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": "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": "// 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": "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": "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": "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": "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}"}, {"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": " 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": "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"}], "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"} {"nl": {"description": "On the well-known testing system MathForces, a draw of $$$n$$$ rating units is arranged. The rating will be distributed according to the following algorithm: if $$$k$$$ participants take part in this event, then the $$$n$$$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain\u00a0\u2014 it is not given to any of the participants.For example, if $$$n = 5$$$ and $$$k = 3$$$, then each participant will recieve an $$$1$$$ rating unit, and also $$$2$$$ rating units will remain unused. If $$$n = 5$$$, and $$$k = 6$$$, then none of the participants will increase their rating.Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.For example, if $$$n=5$$$, then the answer is equal to the sequence $$$0, 1, 2, 5$$$. Each of the sequence values (and only them) can be obtained as $$$\\lfloor n/k \\rfloor$$$ for some positive integer $$$k$$$ (where $$$\\lfloor x \\rfloor$$$ is the value of $$$x$$$ rounded down): $$$0 = \\lfloor 5/7 \\rfloor$$$, $$$1 = \\lfloor 5/5 \\rfloor$$$, $$$2 = \\lfloor 5/2 \\rfloor$$$, $$$5 = \\lfloor 5/1 \\rfloor$$$.Write a program that, for a given $$$n$$$, finds a sequence of all possible rating increments.", "input_spec": "The first line contains integer number $$$t$$$ ($$$1 \\le t \\le 10$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each line contains an integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$)\u00a0\u2014 the total number of the rating units being drawn.", "output_spec": "Output the answers for each of $$$t$$$ test cases. Each answer should be contained in two lines. In the first line print a single integer $$$m$$$\u00a0\u2014 the number of different rating increment values that Vasya can get. In the following line print $$$m$$$ integers in ascending order\u00a0\u2014 the values of possible rating increments.", "sample_inputs": ["4\n5\n11\n1\n3"], "sample_outputs": ["4\n0 1 2 5 \n6\n0 1 2 3 5 11 \n2\n0 1 \n3\n0 1 3"], "notes": null}, "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 val LIMIT = 31650\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// isPrime(1) = true\n// val primes = isPrime.indices.toArray.filter(isPrime(_))\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n var x = 1\n val q = new mutable.ArrayBuilder.ofInt\n q += 0\n while (x * x <= n) {\n q += x\n val p2 = n / x\n if (p2 != x) q += p2\n x += 1\n }\n// var i = 0\n// while (primes(i) * primes(i) <= n) {\n// val p = primes(i)\n// if (p > x) q += p\n// if (p2 > x && p != p2) q += p2\n// i += 1\n// }\n val res = q.result.sorted\n println(res.size)\n println(res.mkString(\" \"))\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 java.util\n\nimport scala.collection.mutable\n\nobject C {\n import InOut._\n def main(args: Array[String]): Unit = {}\n\n val LIMIT = 31650\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 isPrime(1) = true\n val primes = isPrime.indices.toArray.filter(isPrime(_))\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n var i = 0\n val q = new mutable.ArrayBuilder.ofInt\n q += 0\n while (primes(i) * primes(i) <= n) {\n val p = primes(i)\n val p2 = n / p\n q += p\n if (p != p2) q += p2\n i += 1\n }\n val res = q.result.sorted\n println(res.size)\n println(res.mkString(\" \"))\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"}, {"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 val LIMIT = 31650\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 isPrime(1) = true\n val primes = isPrime.indices.toArray.filter(isPrime(_))\n\n val t = nextInt\n for (_ <- 1 to t) {\n val n = nextInt\n var x = 0\n val q = new mutable.ArrayBuilder.ofInt\n while (x * x <= n) {\n q += x\n x += 1\n }\n var i = 0\n while (primes(i) * primes(i) <= n) {\n val p = primes(i)\n val p2 = n / p\n if (p > x) q += p\n if (p2 > x && p != p2) q += p2\n i += 1\n }\n val res = q.result.sorted\n println(res.size)\n println(res.mkString(\" \"))\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": "1fea14a5c21bf301981656cbe015864d"} {"nl": {"description": "Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1,\u2009i2,\u2009i3, that 1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009i3\u2009\u2264\u2009n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b\u00b7k0,\u2009b\u00b7k1,\u2009...,\u2009b\u00b7kr\u2009-\u20091.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.", "input_spec": "The first line of the input contains two integers, n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20092\u00b7105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the sequence.", "output_spec": "Output a single number \u2014 the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.", "sample_inputs": ["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"], "sample_outputs": ["4", "1", "6"], "notes": "NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4."}, "positive_code": [{"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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "Recently Polycarpus has learned the \"bitwise AND\" operation (which is also called \"AND\") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a1,\u2009a2,\u2009...,\u2009an. He also wrote a square matrix b of size n\u2009\u00d7\u2009n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as bij) equals: the \"bitwise AND\" of numbers ai and aj (that is, bij\u2009=\u2009ai\u00a0&\u00a0aj), if i\u2009\u2260\u2009j; -1, if i\u2009=\u2009j. Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.Help Polycarpus, given matrix b, restore the sequence of numbers a1,\u2009a2,\u2009...,\u2009an, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix bij. It is guaranteed, that for all i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) the following condition fulfills: bii = -1. It is guaranteed that for all i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n;\u00a0i\u2009\u2260\u2009j) the following condition fulfills: 0\u2009\u2264\u2009bij\u2009\u2264\u2009109, bij\u2009=\u2009bji.", "output_spec": "Print n non-negative integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces. It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them.", "sample_inputs": ["1\n-1", "3\n-1 18 0\n18 -1 0\n0 0 -1", "4\n-1 128 128 128\n128 -1 148 160\n128 148 -1 128\n128 160 128 -1"], "sample_outputs": ["0", "18 18 0", "128 180 148 160"], "notes": "NoteIf you do not know what is the \"bitwise AND\" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.", "input_spec": "The only line contains two integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009x\u2009\u2264\u2009105)\u00a0\u2014 the number of elements in the set and the desired bitwise-xor, respectively.", "output_spec": "If there is no such set, print \"NO\" (without quotes). Otherwise, on the first line print \"YES\" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.", "sample_inputs": ["5 5", "3 6"], "sample_outputs": ["YES\n1 2 4 5 7", "YES\n1 2 5"], "notes": "NoteYou can read more about the bitwise-xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XORFor the first sample .For the second sample ."}, "positive_code": [{"source_code": "import scala.collection.immutable.HashSet\n\n/**\n * @see http://codeforces.com/contest/862/problem/C\n */\n\nobject CMahmoudAndEhabAndTheXor extends App {\n def set(n: Int, x: Int): List[Int] = {\n if (n == 1) List(x)\n else if (n == 2) {\n if (x == 0) List.empty\n else List(0, x)\n }\n else {\n val s = (1 to n - 3) ++: List.empty[Int]\n val y = s.foldLeft(0)(_ ^ _)\n val a = 1 << 17\n if (x == y) {\n val b = 1 << 18\n List[Int](a, b, a ^ b) ::: s\n } else {\n List[Int](0, a, a ^ x ^ y) ::: s\n }\n }\n }\n\n /**\n * 1 <= n <= 100000\n * 0 <= x <= 100000\n */\n val Array(n, x) = scala.io.StdIn.readLine().split(\" \").map(_.toInt)\n val s = set(n, x)\n if (s.isEmpty) println(\"NO\")\n else println(\"YES\\n\" + s.mkString(\" \"))\n}\n"}], "negative_code": [], "src_uid": "a559171e858d9a63c49fc9e0fecb44c7"} {"nl": {"description": "This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury has chosen a string $$$s$$$ consisting of $$$n$$$ characters; each character of $$$s$$$ is a lowercase Latin letter. Your task is to guess this string; initially, you know only its length.You may ask queries of two types: $$$1$$$ $$$i$$$ \u2014 the query of the first type, where $$$i$$$ is an integer from $$$1$$$ to $$$n$$$. In response to this query, the jury will tell you the character $$$s_i$$$; $$$2$$$ $$$l$$$ $$$r$$$ \u2014 the query of the second type, where $$$l$$$ and $$$r$$$ are integers such that $$$1 \\le l \\le r \\le n$$$. In response to this query, the jury will tell you the number of different characters among $$$s_l, s_{l+1}, \\dots, s_r$$$. You are allowed to ask no more than $$$26$$$ queries of the first type, and no more than $$$6000$$$ queries of the second type. Your task is to restore the string $$$s$$$.For each test in this problem, the string $$$s$$$ is fixed beforehand, and will be the same for every submission.", "input_spec": "Initially, the jury program sends one integer $$$n$$$ on a separate line \u2014 the size of $$$s$$$ ($$$1 \\le n \\le 1000$$$).", "output_spec": "To give the answer, print one line ! s with a line break in the end, where $$$s$$$ should be the string picked by the jury. After that, your program should flush the output and terminate gracefully.", "sample_inputs": ["5\n4\nu\n2\ng\ne\ns\n1"], "sample_outputs": ["? 2 1 5\n? 1 2\n? 2 1 2\n? 1 1\n? 1 3\n? 1 4\n? 2 4 5\n! guess"], "notes": "NoteLet's analyze the example of interaction.The string chosen by the jury is guess, so initially the jury sends one integer $$$5$$$. the first query is ? 2 1 5, which means \"count the number of different characters among $$$s_1, s_2, \\dots, s_5$$$\". The answer to it is $$$4$$$. the second query is ? 1 2, which means \"tell which character is $$$s_2$$$\". The answer to it is u. the third query is ? 2 1 2, which means \"count the number of different characters among $$$s_1$$$ and $$$s_2$$$\". The answer to it is $$$2$$$. the fourth query is ? 1 1, which means \"tell which character is $$$s_1$$$\". The answer to it is g. the fifth query is ? 1 3, which means \"tell which character is $$$s_3$$$\". The answer to it is e. the sixth query is ? 1 4, which means \"tell which character is $$$s_4$$$\". The answer to it is s. the seventh query is ? 2 4 5, which means \"count the number of different characters among $$$s_4$$$ and $$$s_5$$$\". The answer to it is $$$1$$$, so it's possible to deduce that $$$s_4$$$ is the same as $$$s_5$$$.In the end, the answer is submitted as ! guess, and it is deduced correctly."}, "positive_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n def ask1(i: Int): String = {\r\n output.println(\"? 1 \" + i.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l = tokenizer.nextToken()\r\n Console.flush()\r\n l\r\n }\r\n def ask2(l: Int, r:Int): Int = {\r\n output.println(\"? 2 \" + l.toString +\" \" + r.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val ll = tokenizer.nextToken().toInt\r\n Console.flush()\r\n ll\r\n }\r\n val q = tokenizer.nextToken().toInt\r\n val a = ask1(1)\r\n var n = 1\r\n val Map = mutable.Map[String,Int]()\r\n var st = \"\"\r\n st+=a\r\n Map += (a -> 1)\r\n for (i <- 2 to q){\r\n if (ask2(1,i) > n){\r\n val b = ask1(i)\r\n Map += (b -> i)\r\n n+=1\r\n st+=b\r\n }\r\n else {\r\n val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)\r\n var le = 0\r\n var ri = n\r\n while ((ri - le) > 1){\r\n if (ask2(Mapp((le + ri)/2)._2,i) == n - ((le + ri)/2)) {\r\n le = (le + ri)/2\r\n }\r\n else ri = (le + ri)/2\r\n }\r\n Map(Mapp(le)._1) = i\r\n st+=Mapp(le)._1\r\n }\r\n }\r\n\r\n output.println(\"! \"+st)\r\n }\r\n}"}], "negative_code": [{"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n def ask1(i: Int): String = {\r\n output.println(\"? 1 \" + i.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l = tokenizer.nextToken()\r\n Console.flush()\r\n l\r\n }\r\n def ask2(l: Int, r:Int): Int = {\r\n output.println(\"? 2 \" + l.toString +\" \" + r.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val ll = tokenizer.nextToken().toInt\r\n Console.flush()\r\n ll\r\n }\r\n val q = tokenizer.nextToken().toInt\r\n val a = ask1(1)\r\n var n = 1\r\n val Map = mutable.Map[String,Int]()\r\n var st = \"\"\r\n st+=a\r\n Map += (a -> 1)\r\n for (i <- 2 to q){\r\n if (ask2(1,i) > n){\r\n val b = ask1(i)\r\n Map += (b -> i)\r\n n+=1\r\n st+=b\r\n }\r\n else {\r\n val Mapp = Map.toList.sortWith((a, b) => a._2 < b._2)\r\n println(Mapp)\r\n var le = 0\r\n var ri = n\r\n while ((ri - le) > 1) {\r\n if (ask2(Mapp((le + ri) / 2)._2, i) == n - ((le + ri) / 2)) {\r\n le = (le + ri) / 2\r\n }\r\n else ri = (le + ri) / 2\r\n }\r\n Map(Mapp(le)._1) = i\r\n st += Mapp(le)._1\r\n\r\n }\r\n }\r\n output.println(\"! \"+st)\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n def ask1(i: Int): String = {\r\n output.println(\"? 1 \" + i.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l = tokenizer.nextToken()\r\n Console.flush()\r\n l\r\n }\r\n def ask2(l: Int, r:Int): Int = {\r\n output.println(\"? 2 \" + l.toString +\" \" + r.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val ll = tokenizer.nextToken().toInt\r\n Console.flush()\r\n ll\r\n }\r\n val q = tokenizer.nextToken().toInt\r\n val a = ask1(1)\r\n var n = 1\r\n val Map = mutable.Map[String,Int]()\r\n var st = \"\"\r\n st+=a\r\n Map += (a -> 1)\r\n for (i <- 2 to q){\r\n if (ask2(1,i) > n){\r\n val b = ask1(i)\r\n Map += (b -> i)\r\n n+=1\r\n st+=b\r\n }\r\n else {\r\n val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)\r\n var le = 0\r\n var ri = n-1\r\n if (ask2(Mapp(ri)._2,i) != 1) {\r\n while ((ri - le) > 1){\r\n if (ask2(Mapp((le + ri)/2)._2,i) == n - ((le + ri)/2)) {\r\n le = (le + ri)/2\r\n }\r\n else ri = (le + ri)/2\r\n }\r\n Map(Mapp(le)._1) = i\r\n st+=Mapp(le)._1\r\n }\r\n else {Map(Mapp(n-1)._1) = i\r\n st+=Mapp(n-1)._1}\r\n }\r\n }\r\n output.println(\"! \"+st)\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n def ask1(i: Int): String = {\r\n output.println(\"? 1 \" + i.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l = tokenizer.nextToken()\r\n Console.flush()\r\n l\r\n }\r\n def ask2(l: Int, r:Int): Int = {\r\n output.println(\"? 2 \" + l.toString +\" \" + r.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val ll = tokenizer.nextToken().toInt\r\n Console.flush()\r\n ll\r\n }\r\n val q = tokenizer.nextToken().toInt\r\n val a = ask1(1)\r\n var n = 1\r\n val Map = mutable.Map[String,Int]()\r\n var st = \"\"\r\n st+=a\r\n Map += (a -> 1)\r\n var pov = 0\r\n for (i <- 2 to q){\r\n if (ask2(1,i) > n+pov){\r\n val b = ask1(i)\r\n Map += (b -> i)\r\n n+=1\r\n st+=b\r\n }\r\n else {\r\n val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)\r\n var le = 0\r\n var ri = n-1\r\n if (ask2(Mapp(ri)._2,i) != 1) {\r\n while ((ri - le) > 1){\r\n if (ask2(Mapp((le + ri)/2)._2,i) == (le + ri)/2) {\r\n le = (le + ri)/2\r\n }\r\n else ri = (le + ri)/2\r\n }\r\n Map(Mapp(le)._1) = i\r\n st+=Mapp(le)._1\r\n }\r\n else {Map(Mapp(n-1)._1) = i\r\n st+=Mapp(n-1)._1}\r\n pov+=1\r\n }\r\n }\r\n output.println(\"! \"+st)\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n def ask1(i: Int): String = {\r\n output.println(\"? 1 \" + i.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l = tokenizer.nextToken()\r\n Console.flush()\r\n l\r\n }\r\n def ask2(l: Int, r:Int): Int = {\r\n output.println(\"? 2 \" + l.toString +\" \" + r.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val ll = tokenizer.nextToken().toInt\r\n Console.flush()\r\n ll\r\n }\r\n val q = tokenizer.nextToken().toInt\r\n val a = ask1(1)\r\n var n = 1\r\n val Map = mutable.Map[String,Int]()\r\n var st = \"\"\r\n st+=a\r\n Map += (a -> 1)\r\n for (i <- 2 to q){\r\n if (ask2(1,i) > n){\r\n val b = ask1(i)\r\n Map += (b -> i)\r\n n+=1\r\n st+=b\r\n }\r\n else {\r\n val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)\r\n var le = 0\r\n var ri = n-1\r\n if (ask2(Mapp(ri)._2,i) != 1) {\r\n while ((ri - le) > 1){\r\n if (ask2(Mapp((le + ri)/2)._2,i) == (le + ri)/2) {\r\n le = (le + ri)/2\r\n }\r\n else ri = (le + ri)/2\r\n }\r\n Map(Mapp(le)._1) = i\r\n st+=Mapp(le)._1\r\n }\r\n else {Map(Mapp(n-1)._1) = i\r\n st+=Mapp(n-1)._1}\r\n }\r\n }\r\n output.println(\"! \"+st)\r\n }\r\n}"}, {"source_code": "import scala.collection.mutable\r\nimport scala.collection.mutable.ListBuffer\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\r\n import java.util.StringTokenizer\r\n\r\n def run() {\r\n var tokenizer = new StringTokenizer(input.readLine())\r\n def ask1(i: Int): String = {\r\n output.println(\"? 1 \" + i.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val l = tokenizer.nextToken()\r\n Console.flush()\r\n l\r\n }\r\n def ask2(l: Int, r:Int): Int = {\r\n output.println(\"? 2 \" + l.toString +\" \" + r.toString)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n val ll = tokenizer.nextToken().toInt\r\n Console.flush()\r\n ll\r\n }\r\n val q = tokenizer.nextToken().toInt\r\n val a = ask1(1)\r\n var n = 1\r\n val Map = mutable.Map[String,Int]()\r\n var st = \"\"\r\n st+=a\r\n Map += (a -> 1)\r\n for (i <- 2 to q){\r\n if (ask2(1,i) > n){\r\n val b = ask1(i)\r\n Map += (b -> i)\r\n n+=1\r\n st+=b\r\n }\r\n else {\r\n val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)\r\n var le = 0\r\n var ri = n-1\r\n if (ask2(Mapp(ri)._2,i) != 1) {\r\n while (le - ri > 1){\r\n if (ask2(Mapp((le + ri)/2)._2,i) == (le + ri)/2) {\r\n le = (le + ri)/2\r\n }\r\n else ri = (le + ri)/2\r\n }\r\n Map(Mapp(le)._1) = i\r\n st+=Mapp(le)._1\r\n }\r\n else {Map(Mapp(n-1)._1) = i\r\n st+=Mapp(n-1)._1}\r\n }\r\n }\r\n output.println(\"! \"+st)\r\n }\r\n}"}], "src_uid": "34429ced756d3df2def51727bdbd0ff4"} {"nl": {"description": "Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $$$n$$$ boxes, arranged in a row. The $$$i$$$-th box contains $$$a_i$$$ magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the $$$i$$$-th box was covered with a lid initially, he can either move the lid from the $$$i$$$-th box to the box $$$(i-1)$$$ (if it exists), or keep the lid on the $$$i$$$-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak.You have to calculate the maximum number of magazines Monocarp can save from the rain.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of the testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of boxes. The second line contains a string of $$$n$$$ characters 0 and/or 1. If the $$$i$$$-th character is 1, the $$$i$$$-th box is initially covered with a lid. If the $$$i$$$-th character is 0, the $$$i$$$-th box is initially not covered. The third line contains a sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^4$$$), where $$$a_i$$$ is the number of magazines in the $$$i$$$-th box. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print one integer\u00a0\u2014 the maximum number of magazines Monocarp can save from the rain.", "sample_inputs": ["4\n\n5\n\n01110\n\n10 5 8 9 6\n\n6\n\n011011\n\n20 10 9 30 20 19\n\n4\n\n0000\n\n100 100 100 100\n\n4\n\n0111\n\n5 4 5 1"], "sample_outputs": ["27\n80\n0\n14"], "notes": "NoteIn the first testcase of the example, Monocarp can move the lid from the second box to the first box, so the boxes $$$1$$$, $$$3$$$ and $$$4$$$ are covered, and $$$10 + 8 + 9 = 27$$$ magazines are saved.In the second testcase, Monocarp can move the lid from the second box to the first box, then from the third box to the second box, then from the fifth box to the fourth box, and then from the sixth box to the fifth box. The boxes $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$ will be covered, so $$$20 + 10 + 30 + 20 = 80$$$ magazines can be saved.There are no lids in the third testcase, so it's impossible to save even a single magazine."}, "positive_code": [{"source_code": "object _1743C extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n = io.nextInt()\n val hasLid = \"0\" + io.nextLine()\n val mags = IndexedSeq.tabulate(n+1)(i => if (i == 0) 0 else io.nextInt())\n\n val ans = \"01+\".r.findAllMatchIn(hasLid).toList.sumWith({m =>\n val segment = mags.slice(m.start, m.end)\n segment.sum - segment.min\n })\n\n io.printLine(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 =\n t.foldLeft(n.zero)({ case (c, x) => n.plus(c, f(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 _1743C extends CodeForcesApp {\n override def solve(io: IO) = io.repeat() {\n val n = io.nextInt()\n val hasLid = \"0\" + io.nextLine()\n val mags = Seq.fill(n)(io.nextInt())\n\n val ans = \"01+\".r.findAllMatchIn(hasLid).map({m =>\n val segment = mags.slice(m.start-1, m.end-1)\n segment.sum - segment.min\n }).sum\n\n io.printLine(ans)\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"}], "src_uid": "bcc79164881d9281a6080163dd8a0c91"} {"nl": {"description": "Drazil is a monkey. He lives in a circular park. There are n trees around the park. The distance between the i-th tree and (i\u2009+\u20091)-st trees is di, the distance between the n-th tree and the first tree is dn. The height of the i-th tree is hi.Drazil starts each day with the morning run. The morning run consists of the following steps: Drazil chooses two different trees He starts with climbing up the first tree Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees.If the two trees Drazil chooses are x-th and y-th, we can estimate the energy the morning run takes to him as 2(hx\u2009+\u2009hy)\u2009+\u2009dist(x,\u2009y). Since there are children on exactly one of two arcs connecting x and y, the distance dist(x,\u2009y) between trees x and y is uniquely defined.Now, you know that on the i-th day children play between ai-th tree and bi-th tree. More formally, if ai\u2009\u2264\u2009bi, children play around the trees with indices from range [ai,\u2009bi], otherwise they play around the trees with indices from .Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.", "input_spec": "The first line contains two integer n and m (3\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u2009105), denoting number of trees and number of days, respectively. The second line contains n integers d1,\u2009d2,\u2009...,\u2009dn (1\u2009\u2264\u2009di\u2009\u2264\u2009109), the distances between consecutive trees. The third line contains n integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009109), the heights of trees. Each of following m lines contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children.", "output_spec": "For each day print the answer in a separate line.", "sample_inputs": ["5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5", "3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1"], "sample_outputs": ["12\n16\n18", "17\n22\n11"], "notes": null}, "positive_code": [{"source_code": "object C extends App {\n\n case class SegTree(as: Array[Long]) {\n\n val n = as.length\n val t = Array.ofDim[(Long, 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), 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) = if (t(v2)._1 > t(v2 + 1)._1) t(v2) else t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): (Long, Int) = {\n if (l > r) (Long.MinValue, -1)\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n val t1 = query(l, Math.min(r, tm), v2, tl, tm)\n val t2 = query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n if (t1._1 > t2._1) t1 else t2\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\n val Array(n, m) = readInts(2)\n val ds = readLongs(n)\n val hs = readLongs(n)\n\n val lToR, rToL = Array.ofDim[Long](2 * n)\n\n var dSum = 0L\n for (i <- 0 until 2 * n) {\n lToR(i) = dSum + hs(i % n) * 2\n rToL(i) = hs(i % n) * 2 - dSum\n dSum += ds(i % n)\n }\n\n val stLToR = SegTree(lToR)\n val stRToL = SegTree(rToL)\n\n for (i <- 0 until m) {\n val Array(a, b) = readInts(2).map(_ - 1)\n val (u, v) = if (a <= b) (b + 1, n + a - 1) else (b + 1, a - 1)\n val x = {\n val l = stLToR.query(u, v)\n val r1 = stRToL.query(u, l._2 - 1)\n val r2 = stRToL.query(l._2 + 1, v)\n val r = if (r1._1 > r2._1) r1 else r2\n l._1 + r._1\n }\n val y = {\n val r = stRToL.query(u, v)\n val l1 = stLToR.query(u, r._2 - 1)\n val l2 = stLToR.query(r._2 + 1, v)\n val l = if (l1._1 > l2._1) l1 else l2\n l._1 + r._1\n }\n println(x max y)\n }\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "object C extends App {\n\n case class SegTree(as: Array[Long]) {\n\n val n = as.length\n val t = Array.ofDim[(Long, 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), 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) = if (t(v2)._1 > t(v2 + 1)._1) t(v2) else t(v2 + 1)\n }\n }\n\n def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): (Long, Int) = {\n if (l > r) (Long.MinValue, -1)\n else if (l == tl && r == tr) t(v)\n else {\n val tm = (tl + tr) >> 1\n val v2 = v << 1\n val t1 = query(l, Math.min(r, tm), v2, tl, tm)\n val t2 = query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)\n if (t1._1 > t2._1) t1 else t2\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\n val Array(n, m) = readInts(2)\n val ds = readLongs(n)\n val hs = readLongs(n)\n\n val lToR, rToL = Array.ofDim[Long](2 * n)\n\n var dSum = 0L\n for (i <- 0 until 2 * n) {\n lToR(i) = dSum + hs(i % n) * 2\n rToL(i) = hs(i % n) * 2 - dSum\n dSum += ds(i % n)\n }\n\n val stLToR = SegTree(lToR)\n val stRToL = SegTree(rToL)\n\n for (i <- 0 until m) {\n val Array(a, b) = readInts(2).map(_ - 1)\n val (u, v) = if (a <= b) (b + 1, n + a - 1) else (a + 1, n + b - 1)\n val x = {\n val l = stLToR.query(u, v)\n val r1 = stRToL.query(u, l._2 - 1)\n val r2 = stRToL.query(l._2 + 1, v)\n val r = if (r1._1 > r2._1) r1 else r2\n l._1 + r._1\n }\n val y = {\n val r = stRToL.query(u, v)\n val l1 = stLToR.query(u, r._2 - 1)\n val l2 = stLToR.query(r._2 + 1, v)\n val l = if (l1._1 > l2._1) l1 else l2\n l._1 + r._1\n }\n println(x max y)\n }\n\n Console.flush\n}\n"}], "src_uid": "bd9ae0346e27605a3e26922de3398fce"} {"nl": {"description": "You are given two strings of equal length $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if $$$s$$$ is \"acbc\" you can get the following strings in one operation: \"aabc\" (if you perform $$$s_2 = s_1$$$); \"ccbc\" (if you perform $$$s_1 = s_2$$$); \"accc\" (if you perform $$$s_3 = s_2$$$ or $$$s_3 = s_4$$$); \"abbc\" (if you perform $$$s_2 = s_3$$$); \"acbb\" (if you perform $$$s_4 = s_3$$$); Note that you can also apply this operation to the string $$$t$$$.Please determine whether it is possible to transform $$$s$$$ into $$$t$$$, applying the operation above any number of times.Note that you have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$)\u00a0\u2014 the number of queries. Each query is represented by two consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \\le |s| \\le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \\le |t| \\leq 100$$$, $$$|t| = |s|$$$) consisting of lowercase Latin letters.", "output_spec": "For each query, print \"YES\" if it is possible to make $$$s$$$ equal to $$$t$$$, and \"NO\" otherwise. You may print every letter in any case you want (so, for example, the strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will all be recognized as positive answer).", "sample_inputs": ["3\nxabb\naabx\ntechnocup\ntechnocup\na\nz"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteIn the first query, you can perform two operations $$$s_1 = s_2$$$ (after it $$$s$$$ turns into \"aabb\") and $$$t_4 = t_3$$$ (after it $$$t$$$ turns into \"aabb\"). In the second query, the strings are equal initially, so the answer is \"YES\".In the third query, you can not make strings $$$s$$$ and $$$t$$$ equal. Therefore, the answer is \"NO\"."}, "positive_code": [{"source_code": "object _1241B 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 input = io.read[Seq[(String, String)]]\n val ans = input map {case (a, b) => a.toSet.intersect(b.toSet).nonEmpty.toEnglish.toUpperCase() }\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"}], "negative_code": [], "src_uid": "9b9b01e5d2329291eee80356525eaf04"} {"nl": {"description": "You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.The square still has a rectangular shape of $$$n \\times m$$$ meters. However, the picture is about to get more complicated now. Let $$$a_{i,j}$$$ be the $$$j$$$-th square in the $$$i$$$-th row of the pavement.You are given the picture of the squares: if $$$a_{i,j} = $$$ \"*\", then the $$$j$$$-th square in the $$$i$$$-th row should be black; if $$$a_{i,j} = $$$ \".\", then the $$$j$$$-th square in the $$$i$$$-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: $$$1 \\times 1$$$ tiles\u00a0\u2014 each tile costs $$$x$$$ burles and covers exactly $$$1$$$ square; $$$1 \\times 2$$$ tiles\u00a0\u2014 each tile costs $$$y$$$ burles and covers exactly $$$2$$$ adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into $$$1 \\times 1$$$ tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.What is the smallest total price of the tiles needed to cover all the white squares?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of testcases. Then the description of $$$t$$$ testcases follow. The first line of each testcase contains four integers $$$n$$$, $$$m$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 100$$$; $$$1 \\le m \\le 1000$$$; $$$1 \\le x, y \\le 1000$$$)\u00a0\u2014 the size of the Theatre square, the price of the $$$1 \\times 1$$$ tile and the price of the $$$1 \\times 2$$$ tile. Each of the next $$$n$$$ lines contains $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line is $$$a_{i,j}$$$. If $$$a_{i,j} = $$$ \"*\", then the $$$j$$$-th square in the $$$i$$$-th row should be black, and if $$$a_{i,j} = $$$ \".\", then the $$$j$$$-th square in the $$$i$$$-th row should be white. It's guaranteed that the sum of $$$n \\times m$$$ over all testcases doesn't exceed $$$10^5$$$.", "output_spec": "For each testcase print a single integer\u00a0\u2014 the smallest total price of the tiles needed to cover all the white squares in burles.", "sample_inputs": ["4\n1 1 10 1\n.\n1 2 10 1\n..\n2 1 10 1\n.\n.\n3 3 3 7\n..*\n*..\n.*."], "sample_outputs": ["10\n1\n20\n18"], "notes": "NoteIn the first testcase you are required to use a single $$$1 \\times 1$$$ tile, even though $$$1 \\times 2$$$ tile is cheaper. So the total price is $$$10$$$ burles.In the second testcase you can either use two $$$1 \\times 1$$$ tiles and spend $$$20$$$ burles or use a single $$$1 \\times 2$$$ tile and spend $$$1$$$ burle. The second option is cheaper, thus the answer is $$$1$$$.The third testcase shows that you can't rotate $$$1 \\times 2$$$ tiles. You still have to use two $$$1 \\times 1$$$ tiles for the total price of $$$20$$$.In the fourth testcase the cheapest way is to use $$$1 \\times 1$$$ tiles everywhere. The total cost is $$$6 \\cdot 3 = 18$$$."}, "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 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"}, {"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"} {"nl": {"description": "You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number $$$k > 0$$$ written on it, then exactly $$$k$$$ of its neighboring cells have a number greater than $$$0$$$ written on them. Note that if the number in the cell is $$$0$$$, there is no such restriction on neighboring cells.You are allowed to take any number in the grid and increase it by $$$1$$$. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.Two cells are considered to be neighboring if they have a common edge.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n, m \\le 300$$$) \u00a0\u2014 the number of rows and columns, respectively. The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line $$$a_{i, j}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row ($$$0 \\le a_{i, j} \\le 10^9$$$). It is guaranteed that the sum of $$$n \\cdot m$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "If it is impossible to obtain a good grid, print a single line containing \"NO\". Otherwise, print a single line containing \"YES\", followed by $$$n$$$ lines each containing $$$m$$$ integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero). If there are multiple possible answers, you may print any of them.", "sample_inputs": ["5\n3 4\n0 0 0 0\n0 1 0 0\n0 0 0 0\n2 2\n3 0\n0 0\n2 2\n0 0\n0 0\n2 3\n0 0 0\n0 4 0\n4 4\n0 0 0 0\n0 2 0 1\n0 0 0 0\n0 0 0 0"], "sample_outputs": ["YES\n0 0 0 0\n0 1 1 0\n0 0 0 0\nNO\nYES\n0 0\n0 0\nNO\nYES\n0 1 0 0\n1 4 2 1\n0 2 0 0\n1 3 1 0"], "notes": "NoteIn the first test case, we can obtain the resulting grid by increasing the number in row $$$2$$$, column $$$3$$$ once. Both of the cells that contain $$$1$$$ have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid $$$$$$0\\;1\\;0\\;0$$$$$$ $$$$$$0\\;2\\;1\\;0$$$$$$ $$$$$$0\\;0\\;0\\;0$$$$$$ All of them are accepted as valid answers.In the second test case, it is impossible to make the grid good.In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good."}, "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, 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"}, {"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"} {"nl": {"description": "Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $$$i$$$-th of them will start during the $$$x_i$$$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $$$x_1, x_2, \\dots, x_n$$$, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).Ivan can choose two properties for the alarm clock \u2014 the first minute it will ring (let's denote it as $$$y$$$) and the interval between two consecutive signals (let's denote it by $$$p$$$). After the clock is set, it will ring during minutes $$$y, y + p, y + 2p, y + 3p$$$ and so on.Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of $$$p$$$. He has to pick it among the given values $$$p_1, p_2, \\dots, p_m$$$ (his phone does not support any other options for this setting).So Ivan has to choose the first minute $$$y$$$ when the alarm clock should start ringing and the interval between two consecutive signals $$$p_j$$$ in such a way that it will ring during all given minutes $$$x_1, x_2, \\dots, x_n$$$ (and it does not matter if his alarm clock will ring in any other minutes).Your task is to tell the first minute $$$y$$$ and the index $$$j$$$ such that if Ivan sets his alarm clock with properties $$$y$$$ and $$$p_j$$$ it will ring during all given minutes $$$x_1, x_2, \\dots, x_n$$$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 3 \\cdot 10^5, 1 \\le m \\le 3 \\cdot 10^5$$$) \u2014 the number of events and the number of possible settings for the interval between signals. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$1 \\le x_i \\le 10^{18}$$$), where $$$x_i$$$ is the minute when $$$i$$$-th event starts. It is guaranteed that all $$$x_i$$$ are given in increasing order (i.\u2009e. the condition $$$x_1 < x_2 < \\dots < x_n$$$ holds). The third line of the input contains $$$m$$$ integers $$$p_1, p_2, \\dots, p_m$$$ ($$$1 \\le p_j \\le 10^{18}$$$), where $$$p_j$$$ is the $$$j$$$-th option for the interval between two consecutive signals.", "output_spec": "If it's impossible to choose such values $$$y$$$ and $$$j$$$ so all constraints are satisfied, print \"NO\" in the first line. Otherwise print \"YES\" in the first line. Then print two integers $$$y$$$ ($$$1 \\le y \\le 10^{18}$$$) and $$$j$$$ ($$$1 \\le j \\le m$$$) in the second line, where $$$y$$$ is the first minute Ivan's alarm clock should start ringing and $$$j$$$ is the index of the option for the interval between two consecutive signals (options are numbered from $$$1$$$ to $$$m$$$ in the order they are given input). These values should be chosen in such a way that the alarm clock will ring during all given minutes $$$x_1, x_2, \\dots, x_n$$$. If there are multiple answers, you can print any.", "sample_inputs": ["3 5\n3 12 18\n2 6 5 3 3", "4 2\n1 5 17 19\n4 5", "4 2\n1 5 17 19\n2 1"], "sample_outputs": ["YES\n3 4", "NO", "YES\n1 1"], "notes": null}, "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.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 X = nal(N)\n val P = nal(M)\n val D = Array.ofDim[Long](N - 1)\n REP(N -1) { i =>\n D(i) = X(i + 1) - X(i)\n }\n\n debug(D)\n val g = gcd(D)\n debug(s\"gcd:$g\")\n\n REP(M) { i =>\n if (g % P(i) == 0) {\n out.println(\"YES\")\n val y = X(0) // X0\u3088\u308a\u624b\u524d\u304b\u3089\u59cb\u3081\u308b\u7406\u7531\u304c\u306a\u3044\n out.println(s\"$y ${i+1}\")\n return\n }\n }\n\n out.println(\"NO\")\n }\n\n def gcd(a: Long, b: Long): Long = {\n if (b == 0) a\n else gcd(b, a % b)\n }\n\n def gcd(as: Array[Long]): Long = {\n var res = as(0)\n REP(as.length - 1, 1) { i =>\n res = gcd(res, as(i))\n }\n res\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}"}], "negative_code": [], "src_uid": "6493e146ea8d931582d77bb1b0f06e53"} {"nl": {"description": "There are $$$n$$$ houses numbered from $$$1$$$ to $$$n$$$ on a circle. For each $$$1 \\leq i \\leq n - 1$$$, house $$$i$$$ and house $$$i + 1$$$ are neighbours; additionally, house $$$n$$$ and house $$$1$$$ are also neighbours.Initially, $$$m$$$ of these $$$n$$$ houses are infected by a deadly virus. Each morning, Cirno can choose a house which is uninfected and protect the house from being infected permanently.Every day, the following things happen in order: Cirno chooses an uninfected house, and protect it permanently. All uninfected, unprotected houses which have at least one infected neighbor become infected. Cirno wants to stop the virus from spreading. Find the minimum number of houses that will be infected in the end, if she optimally choose the houses to protect.Note that every day Cirno always chooses a house to protect before the virus spreads. Also, a protected house will not be infected forever.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Description of test cases follows. The first line of each test case consists of two positive integers $$$n, m$$$ ($$$5 \\leq n \\leq 10^9$$$, $$$1 \\leq m \\leq \\min(n, 10^5)$$$) \u2014 the number of houses on the circle, and the number of houses that are initially infected. The second line of each test case consists of $$$m$$$ distinct positive integers $$$a_1, a_2, \\cdots , a_m$$$ ($$$1 \\leq a_i \\leq n$$$) \u2014 the indices of the houses infected initially. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output an integer on a separate line, which is the minimum number of infected houses in the end.", "sample_inputs": ["8\n\n10 3\n\n3 6 8\n\n6 2\n\n2 5\n\n20 3\n\n3 7 12\n\n41 5\n\n1 11 21 31 41\n\n10 5\n\n2 4 6 8 10\n\n5 5\n\n3 2 5 4 1\n\n1000000000 1\n\n1\n\n1000000000 4\n\n1 1000000000 10 16"], "sample_outputs": ["7\n5\n11\n28\n9\n5\n2\n15"], "notes": "NoteIn the first test case:At the start of the first day, house $$$3$$$, $$$6$$$, $$$8$$$ are infected. Choose house $$$2$$$ to protect.At the start of the second day, house $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$, $$$8$$$, $$$9$$$ are infected. Choose house $$$10$$$ to protect.At the start of the third day, no more houses are infected.In the second test case:At the start of the first day, house $$$2$$$, $$$5$$$ are infected. Choose house $$$1$$$ to protect.At the start of the second day, house $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$ are infected. No more available houses can be protected."}, "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[Long](m)\r\n tokenizer = new StringTokenizer(input.readLine())\r\n for (i <- 0 until m) {\r\n A(i) = tokenizer.nextToken().toInt\r\n }\r\n val B = A.sorted\r\n val C = new Array[Long](m)\r\n for (i <- 0 until m-1) {\r\n C(i) = B(i+1) - B(i) - 1\r\n }\r\n C(m-1) = n - B.last + B.head - 1\r\n val D = C.sorted.reverse\r\n var cou:Long = 0\r\n for (i <- 0 until D.length){\r\n cou += {if (D(i)-4*i > 1) D(i) - 4*i - 1 else if (D(i)-4*i == 1) 1 else 0}\r\n }\r\n println(n-cou)\r\n }\r\n }\r\n}"}], "negative_code": [], "src_uid": "8b007a212a940f09a9306b0c0091e2ad"} {"nl": {"description": "This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $$$n$$$ are greater than in the easy version of the problem.You are given an array $$$a$$$ of $$$n$$$ integers (the given array can contain equal elements). You can perform the following operations on array elements: choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and move the element $$$a[i]$$$ to the begin of the array; choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and move the element $$$a[i]$$$ to the end of the array. For example, if $$$n = 5$$$, $$$a = [4, 7, 2, 2, 9]$$$, then the following sequence of operations can be performed: after performing the operation of the first type to the second element, the array $$$a$$$ will become $$$[7, 4, 2, 2, 9]$$$; after performing the operation of the second type to the second element, the array $$$a$$$ will become $$$[7, 2, 2, 9, 4]$$$. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the $$$a$$$ array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities $$$a[1] \\le a[2] \\le \\ldots \\le a[n]$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the size of the array $$$a$$$. Then follow $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$)\u00a0\u2014 an array that needs to be sorted by the given operations. The given array can contain equal elements. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output one integer\u00a0\u2014 the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.", "sample_inputs": ["9\n5\n4 7 2 2 9\n5\n3 5 8 1 7\n5\n1 2 2 4 5\n2\n0 1\n3\n0 1 0\n4\n0 1 0 0\n4\n0 1 0 1\n4\n0 1 0 2\n20\n16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9"], "sample_outputs": ["2\n2\n0\n0\n1\n1\n1\n1\n16"], "notes": "NoteIn the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: $$$[4, 7, 2, 2, 9] \\rightarrow [2, 4, 7, 2, 9] \\rightarrow [2, 2, 4, 7, 9]$$$.In the second test case, you need to move the 1 to the beginning of the array, and the 8\u00a0\u2014 to the end. Therefore, the desired sequence of operations: $$$[3, 5, 8, 1, 7] \\rightarrow [1, 3, 5, 8, 7] \\rightarrow [1, 3, 5, 7, 8]$$$.In the third test case, the array is already sorted."}, "positive_code": [{"source_code": "//package codeforces.contests._1367\n\nobject FlyingSort {\n\n import java.io.{BufferedReader, InputStreamReader}\n import java.util.StringTokenizer\n\n val br = new BufferedReader(new InputStreamReader(System.in))\n\n def readInt: Int = br.readLine().toInt\n\n def readIntArrayZipped(n: Int): Array[(Int, Int)] = {\n val st = new StringTokenizer(br.readLine())\n val arr = new Array[(Int, Int)](n)\n var i = 0\n while (st.hasMoreElements) {\n arr(i) = (st.nextToken().toInt, i)\n i += 1\n }\n arr\n }\n\n def main(args: Array[String]): Unit = {\n println {\n {\n for (_ <- 1 to readInt) yield {\n val n = readInt\n val original: Array[(Int, Int)] = readIntArrayZipped(n)\n val sorted = original.sortBy(_._1)\n\n @scala.annotation.tailrec\n def loop(idx: Int, acc: Int = 0, accM: Int = 0): Int = {\n if (idx >= n) acc max accM\n else {\n val (currValue, current) = sorted(idx)\n val (prevValue, prev) = sorted(idx - 1)\n\n def forwardCount(starting: Int, value: Int) = (starting until n).takeWhile(i => sorted(i)._1 == value).length\n\n def backwardCount(starting: Int, value: Int) = (starting to 0 by -1).takeWhile(i => sorted(i)._1 == value).length\n\n if (current > prev) loop(idx + 1, acc + 1, acc max accM)\n else {\n val rightTotalCount = forwardCount(idx, currValue)\n val leftTotalCount = backwardCount(idx - 1, prevValue)\n\n val leftRange = idx - leftTotalCount until idx\n\n val (considerOnlyBothAnswer, _, _, rRemaining) = leftRange.foldLeft((0, 0, idx, rightTotalCount)) {\n case ((maxBoth, leftPassed, rIndex, rRemaining), l) =>\n val removed = {\n var r = rIndex\n while (r < idx + rightTotalCount && sorted(r)._2 < sorted(l)._2) r += 1\n r - rIndex\n }\n\n val rRemainingU = rRemaining - removed\n (maxBoth max rRemainingU + leftPassed + 1, leftPassed + 1, rIndex + removed, rRemainingU)\n }\n\n val leftEndsHereAnswer = acc + rRemaining\n\n val relevantPrev = leftRange.takeWhile(i => sorted(i)._2 < current)\n\n loop(idx + 1, relevantPrev.length + 1, acc max accM max leftEndsHereAnswer max considerOnlyBothAnswer)\n }\n }\n }\n\n n - loop(1, 1, 1)\n }\n }.mkString(\"\\n\")\n }\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1367\n\nobject FlyingSort {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val original: Array[Int] = io.StdIn.readLine.split(\" \").map(_.toInt)\n val zipped = original.zipWithIndex\n\n val ls = zipped.sortBy(_._1).map(_._2).toList\n\n\n @scala.annotation.tailrec\n def loop(ls: List[Int], prevS: List[Int] = Nil, acc: Int = 0, accM: Int = 0): Int = {\n ls match {\n case Nil => acc max accM\n case ::(current, tl) =>\n\n prevS.headOption match {\n case Some(prev) if current > prev => loop(tl, current :: prevS, acc + 1, acc max accM)\n case Some(prev) => // breakage reached, take what we get, consider both left and right view\n val prevValue = original(prev)\n val currValue = original(current)\n\n val rightTotalCount = ls.takeWhile(original(_) == currValue).length // total right\n\n val rightAnswer = {\n val dropRightGivenPrev = ls.takeWhile(i => original(i) == currValue && i < prev).length\n acc + rightTotalCount - dropRightGivenPrev\n }\n\n val relevantPrev = prevS.dropWhile(i => original(i) == prevValue && i > current)\n .takeWhile(i => original(i) == prevValue && i < current)\n\n loop(tl, current :: relevantPrev, relevantPrev.length + 1, acc max accM max rightAnswer)\n case None => loop(tl, current :: Nil, 1, accM)\n }\n }\n }\n\n println(n - loop(ls))\n }\n }\n\n}\n"}], "src_uid": "039e21a58c02b52b13d325ff9982a249"} {"nl": {"description": "Ayush and Ashish play a game on an unrooted tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$. Players make the following move in turns: Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $$$1$$$. A tree is a connected undirected graph without cycles.There is a special node numbered $$$x$$$. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10)$$$\u00a0\u2014 the number of testcases. The description of the test cases follows. The first line of each testcase contains two integers $$$n$$$ and $$$x$$$ $$$(1\\leq n \\leq 1000, 1 \\leq x \\leq n)$$$\u00a0\u2014 the number of nodes in the tree and the special node respectively. Each of the next $$$n-1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \\leq u, v \\leq n, \\text{ } u \\ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.", "output_spec": "For every test case, if Ayush wins the game, print \"Ayush\", otherwise print \"Ashish\" (without quotes).", "sample_inputs": ["1\n3 1\n2 1\n3 1", "1\n3 2\n1 2\n1 3"], "sample_outputs": ["Ashish", "Ayush"], "notes": "NoteFor the $$$1$$$st test case, Ayush can only remove node $$$2$$$ or $$$3$$$, after which node $$$1$$$ becomes a leaf node and Ashish can remove it in his turn.For the $$$2$$$nd test case, Ayush can remove node $$$2$$$ in the first move itself."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Petya has n integers: 1,\u20092,\u20093,\u2009...,\u2009n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u200960\u2009000) \u2014 the number of integers Petya has.", "output_spec": "Print the smallest possible absolute difference in the first line. In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.", "sample_inputs": ["4", "2"], "sample_outputs": ["0\n2 1 4", "1\n1 1"], "notes": "NoteIn the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1."}, "positive_code": [{"source_code": "import scala.io.StdIn\n\nobject P899C_DividingTheNumbers extends App {\n val (leftSum, rightSum, leftList) = (StdIn.readInt() to(1, -1)).foldLeft((0, 0, List.empty[Int])) {\n case ((leftSum, rightSum, leftList), num) =>\n if (leftSum > rightSum) (leftSum, rightSum + num, leftList)\n else (leftSum + num, rightSum, num :: leftList)\n }\n\n println(math.abs(leftSum - rightSum))\n println(s\"${leftList.size} ${leftList.mkString(\" \")}\")\n\n}"}], "negative_code": [], "src_uid": "4c387ab2a0d028141634ade32ae97d03"} {"nl": {"description": "In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di \u2014 buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.", "input_spec": "The input starts with two positive integers n and s (1\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009s\u2009\u2264\u200950), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0\u2009\u2264\u2009pi\u2009\u2264\u2009105) and an integer qi (1\u2009\u2264\u2009qi\u2009\u2264\u2009104) \u2014 direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.", "output_spec": "Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.", "sample_inputs": ["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"], "sample_outputs": ["S 50 8\nS 40 1\nB 25 10\nB 20 4"], "notes": "NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders."}, "positive_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).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 "}, {"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": "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"}, {"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": "\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}"}], "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"} {"nl": {"description": "There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll \u2014 inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \\le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \\dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \\le in_i < out_i \\le 10^9$$$) \u2014 the outer and inners volumes of the $$$i$$$-th matryoshka.", "output_spec": "Print one integer \u2014 the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$.", "sample_inputs": ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"], "sample_outputs": ["6"], "notes": "NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\\{1, 5\\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\\{1, 6\\}$$$; $$$\\{2, 4, 5\\}$$$; $$$\\{2, 4, 6\\}$$$; $$$\\{3, 4, 5\\}$$$; $$$\\{3, 4, 6\\}$$$. There are no more \"good\" subsets because, for example, subset $$$\\{6, 7\\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\\{4, 6, 7\\}$$$ has extra space equal to $$$2$$$."}, "positive_code": [{"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"}, {"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\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": "//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"}, {"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"}], "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"} {"nl": {"description": "You have got a shelf and want to put some books on it.You are given $$$q$$$ queries of three types: L $$$id$$$ \u2014 put a book having index $$$id$$$ on the shelf to the left from the leftmost existing book; R $$$id$$$ \u2014 put a book having index $$$id$$$ on the shelf to the right from the rightmost existing book; ? $$$id$$$ \u2014 calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $$$id$$$ will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type $$$3$$$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $$$id$$$s don't repeat in queries of first two types.Your problem is to answer all the queries of type $$$3$$$ in order they appear in the input.Note that after answering the query of type $$$3$$$ all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th line contains the $$$i$$$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $$$3$$$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before). It is guaranteed that there is at least one query of type $$$3$$$ in the input. In each query the constraint $$$1 \\le id \\le 2 \\cdot 10^5$$$ is met.", "output_spec": "Print answers to queries of the type $$$3$$$ in order they appear in the input.", "sample_inputs": ["8\nL 1\nR 2\nR 3\n? 2\nL 4\n? 1\nL 5\n? 1", "10\nL 100\nR 100000\nR 123\nL 101\n? 123\nL 10\nR 115\n? 100\nR 110\n? 115"], "sample_outputs": ["1\n1\n2", "0\n2\n1"], "notes": "NoteLet's take a look at the first example and let's consider queries: The shelf will look like $$$[1]$$$; The shelf will look like $$$[1, 2]$$$; The shelf will look like $$$[1, 2, 3]$$$; The shelf looks like $$$[1, \\textbf{2}, 3]$$$ so the answer is $$$1$$$; The shelf will look like $$$[4, 1, 2, 3]$$$; The shelf looks like $$$[4, \\textbf{1}, 2, 3]$$$ so the answer is $$$1$$$; The shelf will look like $$$[5, 4, 1, 2, 3]$$$; The shelf looks like $$$[5, 4, \\textbf{1}, 2, 3]$$$ so the answer is $$$2$$$. Let's take a look at the second example and let's consider queries: The shelf will look like $$$[100]$$$; The shelf will look like $$$[100, 100000]$$$; The shelf will look like $$$[100, 100000, 123]$$$; The shelf will look like $$$[101, 100, 100000, 123]$$$; The shelf looks like $$$[101, 100, 100000, \\textbf{123}]$$$ so the answer is $$$0$$$; The shelf will look like $$$[10, 101, 100, 100000, 123]$$$; The shelf will look like $$$[10, 101, 100, 100000, 123, 115]$$$; The shelf looks like $$$[10, 101, \\textbf{100}, 100000, 123, 115]$$$ so the answer is $$$2$$$; The shelf will look like $$$[10, 101, 100, 100000, 123, 115, 110]$$$; The shelf looks like $$$[10, 101, 100, 100000, 123, \\textbf{115}, 110]$$$ so the answer is $$$1$$$. "}, "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.util.concurrent.LinkedBlockingDeque\n val Q = ni()\n val q = new LinkedBlockingDeque[Int]()\n val qs = ArrayBuffer[(Int, (Int, Int))]()\n val ids = mutable.Map[Int, Int]()\n var idGen = 0\n var L, R = 0\n rep(Q) { _ =>\n val command = nc()\n val id_v = ni()\n val id = ids.getOrElseUpdate(id_v, {\n val id = idGen\n idGen += 1\n id\n })\n command match {\n case 'L' =>\n L += 1\n q.addFirst(id)\n\n case 'R' =>\n R += 1\n q.addLast(id)\n\n case '?' =>\n qs += ((id, (L, R)))\n L = 0\n R = 0\n }\n }\n\n val N = q.size()\n val as = Array.ofDim[Int](N)\n var i = 0\n while(!q.isEmpty){\n as(i) = q.poll()\n i += 1\n }\n val rev = Array.ofDim[Int](N)\n rep(as.length) { i =>\n rev(as(i)) = i\n }\n\n val ans = ArrayBuffer[Int]()\n qs.reverse foreach { case (id, (l, r)) =>\n ans += min(rev(id) - L, N - rev(id) - 1 - R)\n L += l\n R += r\n }\n\n ans.reverse foreach 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}"}], "negative_code": [], "src_uid": "e61509d5f0bcd405b1a0c9ba74449df2"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \\le l \\le r \\le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \\dots, p_{l-1},p_r,p_{r-1}, \\dots, p_l,p_{r+1},p_{r+2}, \\dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 500$$$)\u00a0\u2014 the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$)\u00a0\u2014 the elements of the permutation.", "output_spec": "For each test case print the lexicographically smallest permutation you can obtain.", "sample_inputs": ["4\n\n1\n\n1\n\n3\n\n2 1 3\n\n4\n\n1 4 2 3\n\n5\n\n1 2 3 4 5"], "sample_outputs": ["1 \n1 2 3 \n1 2 4 3 \n1 2 3 4 5"], "notes": "NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$."}, "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"}, {"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}"}], "negative_code": [], "src_uid": "a57823a7ca0f67a07f94175ab59d33de"} {"nl": {"description": "One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.", "input_spec": "The first input line contains a single integer n \u2014 the number of cupboards in the kitchen (2\u2009\u2264\u2009n\u2009\u2264\u2009104). Then follow n lines, each containing two integers li and ri (0\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u20091). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.", "output_spec": "In the only output line print a single integer t \u2014 the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.", "sample_inputs": ["5\n0 1\n1 0\n0 1\n1 1\n0 1"], "sample_outputs": ["3"], "notes": null}, "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.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"}, {"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"} {"nl": {"description": "IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids \u2014 one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. ", "input_spec": "The only line of the input contains three integers l3,\u2009l4,\u2009l5 (1\u2009\u2264\u2009l3,\u2009l4,\u2009l5\u2009\u2264\u20091000) \u2014 the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.", "output_spec": "Output one number \u2014 the total volume of the pyramids. Absolute or relative error should not be greater than 10\u2009-\u20099.", "sample_inputs": ["2 5 3"], "sample_outputs": ["38.546168065709"], "notes": null}, "positive_code": [{"source_code": "import java.util.Scanner\n\nimport scala.collection.mutable.ArrayBuffer\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 foo(n: Int, a: Double) = {\n var sx = 0.0\n var sy = 0.0\n var curx = 0.0\n var cury = 0.0\n for (i <- 0 until n) {\n sx = sx + curx\n sy = sy + cury\n curx = curx + Math.cos(Math.PI * 2 / n * i) * a\n cury = cury + Math.sin(Math.PI * 2 / n * i) * a\n }\n sx = sx / n\n sy = sy / n\n val d = Math.sqrt(sx * sx + sy * sy)\n val h = Math.sqrt(a * a - d * d)\n val area = n * a * a / (4 * Math.tan(Math.PI / n))\n 1.0 / 3 * h * area\n }\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 res = foo(3, a) + foo(4, b) + foo(5, c)\n\n println(res)\n }\n}"}], "negative_code": [], "src_uid": "560bc97986a355d461bd462c4e1ea9db"} {"nl": {"description": "Kris works in a large company \"Blake Technologies\". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.Printer works with a rectangular sheet of paper of size n\u2009\u00d7\u2009m. Consider the list as a table consisting of n rows and m columns. Rows are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m. Initially, all cells are painted in color 0.Your program has to support two operations: Paint all cells in row ri in color ai; Paint all cells in column ci in color ai. If during some operation i there is a cell that have already been painted, the color of this cell also changes to ai.Your program has to print the resulting table after k operation.", "input_spec": "The first line of the input contains three integers n, m and k (1\u2009\u2009\u2264\u2009\u2009n,\u2009\u2009m\u2009\u2009\u2264\u20095000, n\u00b7m\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the dimensions of the sheet and the number of operations, respectively. Each of the next k lines contains the description of exactly one query: 1\u00a0ri\u00a0ai (1\u2009\u2264\u2009ri\u2009\u2264\u2009n, 1\u2009\u2264\u2009ai\u2009\u2264\u2009109), means that row ri is painted in color ai; 2\u00a0ci\u00a0ai (1\u2009\u2264\u2009ci\u2009\u2264\u2009m, 1\u2009\u2264\u2009ai\u2009\u2264\u2009109), means that column ci is painted in color ai. ", "output_spec": "Print n lines containing m integers each\u00a0\u2014 the resulting table after all operations are applied.", "sample_inputs": ["3 3 3\n1 1 3\n2 2 1\n1 2 2", "5 3 5\n1 1 1\n1 3 1\n1 5 1\n2 1 1\n2 3 1"], "sample_outputs": ["3 1 3 \n2 2 2 \n0 1 0", "1 1 1 \n1 0 1 \n1 1 1 \n1 0 1 \n1 1 1"], "notes": "NoteThe figure below shows all three operations for the first sample step by step. The cells that were painted on the corresponding step are marked gray. "}, "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 += (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"}, {"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"} {"nl": {"description": "The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.How much work is there left to be done: that is, how many remote planets are there?", "input_spec": "The first line of the input contains an integer N (2\u2009\u2264\u2009N\u2009\u2264\u20091000) \u2013 the number of planets in the galaxy. The next N\u2009-\u20091 lines describe the hyperspace tunnels between the planets. Each of the N\u2009-\u20091 lines contains two space-separated integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.", "output_spec": "A single integer denoting the number of remote planets.", "sample_inputs": ["5\n4 1\n4 2\n1 3\n1 5", "4\n1 2\n4 3\n1 4"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first example, only planets 2, 3 and 5 are connected by a single tunnel.In the second example, the remote planets are 2 and 3.Note that this problem has only two versions \u2013 easy and medium."}, "positive_code": [{"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}"}, {"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"} {"nl": {"description": "This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on $$$n$$$ are less than in the hard version of the problem.You are given an array $$$a$$$ of $$$n$$$ integers (there are no equals elements in the array). You can perform the following operations on array elements: choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and move the element $$$a[i]$$$ to the begin of the array; choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and move the element $$$a[i]$$$ to the end of the array. For example, if $$$n = 5$$$, $$$a = [4, 7, 2, 3, 9]$$$, then the following sequence of operations can be performed: after performing the operation of the first type to the second element, the array $$$a$$$ will become $$$[7, 4, 2, 3, 9]$$$; after performing the operation of the second type to the second element, the array $$$a$$$ will become $$$[7, 2, 3, 9, 4]$$$. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the $$$a$$$ array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities $$$a[1] \\le a[2] \\le \\ldots \\le a[n]$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \\le n \\le 3000$$$)\u00a0\u2014 length of the array $$$a$$$. Then follow $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$)\u00a0\u2014 an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of $$$n$$$ for all test cases in one test does not exceed $$$3000$$$.", "output_spec": "For each test case output one integer\u00a0\u2014 the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.", "sample_inputs": ["4\n5\n4 7 2 3 9\n5\n3 5 8 1 7\n5\n1 4 5 7 12\n4\n0 2 1 3"], "sample_outputs": ["2\n2\n0\n2"], "notes": "NoteIn the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: $$$[4, 7, 2, 3, 9] \\rightarrow [3, 4, 7, 2, 9] \\rightarrow [2, 3, 4, 7, 9]$$$.In the second test case, you need to move the 1 to the beginning of the array, and the 8\u00a0\u2014 to the end. Therefore, the desired sequence of operations: $$$[3, 5, 8, 1, 7] \\rightarrow [1, 3, 5, 8, 7] \\rightarrow [1, 3, 5, 7, 8]$$$.In the third test case, the array is already sorted."}, "positive_code": [{"source_code": "//package codeforces.contests._1367\n\nobject FlyingSort {\n\n def main(args: Array[String]): Unit = {\n for (_ <- 1 to io.StdIn.readInt) {\n val n = io.StdIn.readInt()\n val original: Array[Int] = io.StdIn.readLine.split(\" \").map(_.toInt)\n val zipped = original.zipWithIndex\n\n val ls = zipped.sortBy(_._1).map(_._2).toList\n\n\n @scala.annotation.tailrec\n def loop(ls: List[Int], prevS: List[Int] = Nil, acc: Int = 0, accM: Int = 0): Int = {\n ls match {\n case Nil => acc max accM\n case ::(current, tl) =>\n\n prevS.headOption match {\n case Some(prev) if current > prev => loop(tl, current :: prevS, acc + 1, acc max accM)\n case Some(prev) => // breakage reached, take what we get, consider both left and right view\n val prevValue = original(prev)\n val currValue = original(current)\n\n val rightTotalCount = ls.takeWhile(original(_) == currValue).length // total right\n\n val rightAnswer = {\n val dropRightGivenPrev = ls.takeWhile(i => original(i) == currValue && i < prev).length\n acc + rightTotalCount - dropRightGivenPrev\n }\n\n val relevantPrev = prevS.dropWhile(i => original(i) == prevValue && i > current)\n .takeWhile(i => original(i) == prevValue && i < current)\n\n loop(tl, current :: relevantPrev, relevantPrev.length + 1, acc max accM max rightAnswer)\n case None => loop(tl, current :: Nil, 1, accM)\n }\n }\n }\n\n println(n - loop(ls))\n }\n }\n\n}\n"}], "negative_code": [], "src_uid": "05177408414e4056cd6b1ea46d1ac499"} {"nl": {"description": "Even if it's a really easy question, she won't be able to answer it\u2014 Perfect Memento in Strict SenseCirno's perfect bitmasks classroom has just started!Cirno gave her students a positive integer $$$x$$$. As an assignment, her students need to find the minimum positive integer $$$y$$$, which satisfies the following two conditions:$$$$$$x\\ \\texttt{and}\\ y > 0$$$$$$ $$$$$$x\\ \\texttt{xor}\\ y > 0$$$$$$Where $$$\\texttt{and}$$$ is the bitwise AND operation, and $$$\\texttt{xor}$$$ is the bitwise XOR operation.Among the students was Mystia, who was truly baffled by all these new operators. Please help her!", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$) \u2014 the number of input test cases. For each test case, the only line of input contains one integer $$$x$$$ ($$$1 \\leq x \\leq 2^{30}$$$).", "output_spec": "For each test case, print a single integer \u2014 the minimum number of $$$y$$$.", "sample_inputs": ["7\n\n1\n\n2\n\n5\n\n9\n\n16\n\n114514\n\n1000000"], "sample_outputs": ["3\n3\n1\n1\n17\n2\n64"], "notes": "NoteTest case 1: $$$1\\; \\texttt{and}\\; 3=1>0$$$, $$$1\\; \\texttt{xor}\\; 3=2>0$$$.Test case 2: $$$2\\; \\texttt{and}\\; 3=2>0$$$, $$$2\\; \\texttt{xor}\\; 3=1>0$$$."}, "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 -= 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"}, {"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< 1 ) (for(i <- 0 until k-1) yield {(taps(i+1) - taps(i))/2}) else Seq.empty\n val dists = (taps(0)-1) +: dtap :+ (n-taps(k-1))\n println((dists max)+1)\n if(tt != 1) water(tt-1)\n }\n}"}], "negative_code": [], "src_uid": "5de25068af66273c83cc7914910c4c84"} {"nl": {"description": "There are $$$n$$$ segments $$$[l_i, r_i]$$$ for $$$1 \\le i \\le n$$$. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.To optimize testing process you will be given multitest.", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 50000$$$) \u2014 the number of queries. Each query contains description of the set of segments. Queries are independent. First line of each query contains single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 number of segments. It is guaranteed that $$$\\sum{n}$$$ over all queries does not exceed $$$10^5$$$. The next $$$n$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ per line ($$$1 \\le l_i \\le r_i \\le 2 \\cdot 10^5$$$) \u2014 the $$$i$$$-th segment.", "output_spec": "For each query print $$$n$$$ integers $$$t_1, t_2, \\dots, t_n$$$ ($$$t_i \\in \\{1, 2\\}$$$) \u2014 for each segment (in the same order as in the input) $$$t_i$$$ equals $$$1$$$ if the $$$i$$$-th segment will belongs to the first group and $$$2$$$ otherwise. If there are multiple answers, you can print any of them. If there is no answer, print $$$-1$$$.", "sample_inputs": ["3\n2\n5 5\n2 3\n3\n3 5\n2 3\n2 3\n3\n3 3\n4 4\n5 5"], "sample_outputs": ["2 1 \n-1\n1 1 2"], "notes": "NoteIn the first query the first and the second segments should be in different groups, but exact numbers don't matter.In the second query the third segment intersects with the first and the second segments, so they should be in the same group, but then the other group becomes empty, so answer is $$$-1$$$.In the third query we can distribute segments in any way that makes groups non-empty, so any answer of $$$6$$$ possible is correct."}, "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 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\u512a\u5148\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 // \u6700\u521d\u306b\u30b0\u30eb\u30fc\u30d7\u304c\u533a\u5207\u308c\u305f\u5834\u6240\u3067\u5206\u5272\u3059\u308b\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}"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 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\u512a\u5148\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 // \u6700\u521d\u306b\u30b0\u30eb\u30fc\u30d7\u304c\u533a\u5207\u308c\u305f\u5834\u6240\u3067\u5206\u5272\u3059\u308b\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}"}, {"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}"}], "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\u512a\u5148\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 // \u6700\u521d\u306b\u30b0\u30eb\u30fc\u30d7\u304c\u533a\u5207\u308c\u305f\u5834\u6240\u3067\u5206\u5272\u3059\u308b\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"} {"nl": {"description": "There is a grid with $$$n$$$ rows and $$$m$$$ columns. Some cells are colored black, and the rest of the cells are colored white.In one operation, you can select some black cell and do exactly one of the following: color all cells in its row black, or color all cells in its column black. You are given two integers $$$r$$$ and $$$c$$$. Find the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black, or determine that it is impossible.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$r$$$, and $$$c$$$ ($$$1 \\leq n, m \\leq 50$$$; $$$1 \\leq r \\leq n$$$; $$$1 \\leq c \\leq m$$$)\u00a0\u2014 the number of rows and the number of columns in the grid, and the row and column of the cell you need to turn black, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either 'B' or 'W'\u00a0\u2014 a black and a white cell, respectively.", "output_spec": "For each test case, if it is impossible to make the cell in row $$$r$$$ and column $$$c$$$ black, output $$$-1$$$. Otherwise, output a single integer\u00a0\u2014 the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black. ", "sample_inputs": ["9\n\n3 5 1 4\n\nWBWWW\n\nBBBWB\n\nWWBBB\n\n4 3 2 1\n\nBWW\n\nBBW\n\nWBB\n\nWWB\n\n2 3 2 2\n\nWWW\n\nWWW\n\n2 2 1 1\n\nWW\n\nWB\n\n5 9 5 9\n\nWWWWWWWWW\n\nWBWBWBBBW\n\nWBBBWWBWW\n\nWBWBWBBBW\n\nWWWWWWWWW\n\n1 1 1 1\n\nB\n\n1 1 1 1\n\nW\n\n1 2 1 1\n\nWB\n\n2 1 1 1\n\nW\n\nB"], "sample_outputs": ["1\n0\n-1\n2\n2\n0\n-1\n1\n1"], "notes": "NoteThe first test case is pictured below. We can take the black cell in row $$$1$$$ and column $$$2$$$, and make all cells in its row black. Therefore, the cell in row $$$1$$$ and column $$$4$$$ will become black. In the second test case, the cell in row $$$2$$$ and column $$$1$$$ is already black.In the third test case, it is impossible to make the cell in row $$$2$$$ and column $$$2$$$ black.The fourth test case is pictured below. We can take the black cell in row $$$2$$$ and column $$$2$$$ and make its column black. Then, we can take the black cell in row $$$1$$$ and column $$$2$$$ and make its row black. Therefore, the cell in row $$$1$$$ and column $$$1$$$ will become black."}, "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 c: Long)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 for (tt <- 1 to t) {\n val n = readInt()\n val m = readInt()\n val y = readInt()\n val x = readInt()\n var ok = false\n val arr = Array.ofDim[Boolean](n+1, m+1)\n for (i <- 1 to n) {\n val s = readString()\n for (j <- s.indices) {\n if (s(j) == 'B') {\n arr(i)(j+1) = true\n ok = true\n }\n }\n }\n var found = false\n for (i <- 1 to n) {\n if (arr(i)(x)) {\n found = true\n }\n }\n for (i <- 1 to m) {\n if (arr(y)(i)) {\n found = true\n }\n }\n if (arr(y)(x)) {\n writer.println(0)\n } else if (found) {\n writer.println(1)\n } else if (ok) {\n writer.println(2)\n } else {\n writer.println(-1)\n }\n\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": "4ca13794471831953f2737ca9d4ba853"} {"nl": {"description": "There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \\leq a_i \\leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$\u00a0\u2014 the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \\leq j < i$$$), such that $$$a_i < a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i < j \\leq n$$$), such that $$$a_i < a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.", "input_spec": "On the first line there is a single integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \\ldots, l_n$$$ ($$$0 \\leq l_i \\leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \\ldots, r_n$$$ ($$$0 \\leq r_i \\leq n$$$), separated by spaces.", "output_spec": "If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print \u00abNO\u00bb (without quotes). Otherwise, print \u00abYES\u00bb (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$, separated by spaces\u00a0\u2014 the numbers of candies the children $$$1, 2, \\ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \\leq a_i \\leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.", "sample_inputs": ["5\n0 0 1 1 2\n2 0 1 0 0", "4\n0 0 2 0\n1 1 1 1", "3\n0 0 0\n0 0 0"], "sample_outputs": ["YES\n1 3 1 2 1", "NO", "YES\n1 1 1"], "notes": "NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ child\u00a0\u2014 $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy."}, "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"}, {"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"}], "negative_code": [], "src_uid": "fa531c38833907d619f1102505ddbb6a"} {"nl": {"description": "A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.", "input_spec": "The first line contains number t (1\u2009\u2264\u2009t\u2009\u2264\u200950) \u2014 the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters \".\", \"#\", \"K\", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.", "output_spec": "For each test, print on a single line the answer to the problem: \"YES\", if the semiknights can meet and \"NO\" otherwise.", "sample_inputs": ["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"], "sample_outputs": ["YES\nNO"], "notes": "NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet. "}, "positive_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 == 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"}, {"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"} {"nl": {"description": "Everybody knows that the $$$m$$$-coder Tournament will happen soon. $$$m$$$ schools participate in the tournament, and only one student from each school participates.There are a total of $$$n$$$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $$$k$$$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m, k \\le n$$$)\u00a0\u2014 the total number of students, the number of schools and the number of the Chosen Ones. The second line contains $$$n$$$ different integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\le p_i \\le n$$$), where $$$p_i$$$ denotes the power of $$$i$$$-th student. The bigger the power, the stronger the student. The third line contains $$$n$$$ integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$1 \\le s_i \\le m$$$), where $$$s_i$$$ denotes the school the $$$i$$$-th student goes to. At least one student studies in each of the schools. The fourth line contains $$$k$$$ different integers $$$c_1, c_2, \\ldots, c_k$$$ ($$$1 \\le c_i \\le n$$$) \u00a0\u2014 the id's of the Chosen Ones.", "output_spec": "Output a single integer \u00a0\u2014 the minimal number of schools to be made up by Arkady so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.", "sample_inputs": ["7 3 1\n1 5 3 4 6 7 2\n1 3 1 2 1 2 3\n3", "8 4 4\n1 2 3 4 5 6 7 8\n4 3 2 1 4 3 2 1\n3 4 5 6"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example there's just a single Chosen One with id $$$3$$$. His power is equal to $$$3$$$, but in the same school $$$1$$$, there's a student with id $$$5$$$ and power $$$6$$$, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be $$$4$$$) for the Chosen One, Technogoblet would select students with ids $$$2$$$ (strongest in $$$3$$$), $$$5$$$ (strongest in $$$1$$$), $$$6$$$ (strongest in $$$2$$$) and $$$3$$$ (strongest in $$$4$$$).In the second example, you can change the school of student $$$3$$$ to the made-up $$$5$$$ and the school of student $$$4$$$ to the made-up $$$6$$$. It will cause the Technogoblet to choose students $$$8$$$, $$$7$$$, $$$6$$$, $$$5$$$, $$$3$$$ and $$$4$$$."}, "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, M, K = ni()\n val P, S = na(N, -1)\n val choosen = na(K, -1).toSet\n\n val mx = Array.ofDim[Int](M)\n REP(N) { i =>\n mx(S(i)) = max(mx(S(i)), P(i))\n }\n\n var ans = 0\n REP(N) { i =>\n if (choosen.contains(i) && mx(S(i)) != P(i)) ans += 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"}], "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 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, M, K = ni()\n val P, S = na(N, -1)\n val choosen = na(K, -1).toSet\n\n val byS = Array.fill[ArrayBuffer[(Int, Int)]](M)(ArrayBuffer())\n REP(N) { i =>\n byS(S(i)) += i -> P(i)\n }\n\n DEBUG {\n REP(M) { i =>\n debug(byS(i).mkString(\",\"))\n }\n }\n\n val cnts = map(M) { i =>\n val sorted = byS(i).sortBy(_._2).map(_._1)\n val n = sorted.length\n var cnt = 0\n REP(n) { j =>\n if (cnt == 0 && choosen.contains(sorted(j))) {\n cnt = n - 1 - j // \u53f3\u306b\u4f55\u4eba\u3044\u308b\u304b\n }\n }\n cnt\n }\n\n debug(cnts)\n \n out.println(cnts.sum)\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"}], "src_uid": "e34f110440942a841624d0f42e0ddec4"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ points in $$$k$$$-dimensional space. Let the distance between two points $$$a_x$$$ and $$$a_y$$$ be $$$\\sum \\limits_{i = 1}^{k} |a_{x, i} - a_{y, i}|$$$ (it is also known as Manhattan distance).You have to process $$$q$$$ queries of the following two types: $$$1$$$ $$$i$$$ $$$b_1$$$ $$$b_2$$$ ... $$$b_k$$$ \u2014 set $$$i$$$-th element of $$$a$$$ to the point $$$(b_1, b_2, \\dots, b_k)$$$; $$$2$$$ $$$l$$$ $$$r$$$ \u2014 find the maximum distance between two points $$$a_i$$$ and $$$a_j$$$, where $$$l \\le i, j \\le r$$$.", "input_spec": "The first line contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le 5$$$) \u2014 the number of elements in $$$a$$$ and the number of dimensions of the space, respectively. Then $$$n$$$ lines follow, each containing $$$k$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, k}$$$ ($$$-10^6 \\le a_{i, j} \\le 10^6$$$) \u2014 the coordinates of $$$i$$$-th point. The next line contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of queries. Then $$$q$$$ lines follow, each denoting a query. There are two types of queries: $$$1$$$ $$$i$$$ $$$b_1$$$ $$$b_2$$$ ... $$$b_k$$$ ($$$1 \\le i \\le n$$$, $$$-10^6 \\le b_j \\le 10^6$$$) \u2014 set $$$i$$$-th element of $$$a$$$ to the point $$$(b_1, b_2, \\dots, b_k)$$$; $$$2$$$ $$$l$$$ $$$r$$$ ($$$1 \\le l \\le r \\le n$$$) \u2014 find the maximum distance between two points $$$a_i$$$ and $$$a_j$$$, where $$$l \\le i, j \\le r$$$. There is at least one query of the second type.", "output_spec": "Print the answer for each query of the second type.", "sample_inputs": ["5 2\n1 2\n2 3\n3 4\n4 5\n5 6\n7\n2 1 5\n2 1 3\n2 3 5\n1 5 -1 -2\n2 1 5\n1 4 -1 -2\n2 1 5"], "sample_outputs": ["8\n4\n4\n12\n10"], "notes": null}, "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 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 \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\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": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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 \u500b\u6570 \u6700\u5927\u5024\u3058\u3083\u306a\u3044\u305e\u3002\n * i\u306e\u7bc4\u56f2\u306f[0, n - 1]\n *\n * A\u304cInt\u3084Long\u306e\u3068\u304d\u306f\u57cb\u3081\u8fbc\u3093\u3067\u3057\u307e\u304a\u3046\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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\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 = 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"}, {"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"}], "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"} {"nl": {"description": "The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. ", "input_spec": "The first line contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u200960\u2009000)\u00a0\u2014 the number of friends. The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009109)\u00a0\u2014 the current coordinates of the friends, in meters. The third line contains n integers v1,\u2009v2,\u2009...,\u2009vn (1\u2009\u2264\u2009vi\u2009\u2264\u2009109)\u00a0\u2014 the maximum speeds of the friends, in meters per second.", "output_spec": "Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10\u2009-\u20096. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if holds.", "sample_inputs": ["3\n7 1 3\n1 2 1", "4\n5 10 3 2\n2 3 2 4"], "sample_outputs": ["2.000000000000", "1.400000000000"], "notes": "NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds."}, "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) \u21d2 (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"}, {"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}"}], "negative_code": [], "src_uid": "f13f27a131b9315ebbb8688e2f43ddde"} {"nl": {"description": "Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?", "input_spec": "The first line contains three integers n, r, avg (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009r\u2009\u2264\u2009109, 1\u2009\u2264\u2009avg\u2009\u2264\u2009min(r,\u2009106))\u00a0\u2014 the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009r, 1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "In the first line print the minimum number of essays.", "sample_inputs": ["5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5", "2 5 4\n5 2\n5 2"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average."}, "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": "\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}"}, {"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"} {"nl": {"description": "Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.Also Pasha has a number k and two sequences of length n\u2009/\u2009k (n is divisible by k) a1,\u2009a2,\u2009...,\u2009an\u2009/\u2009k and b1,\u2009b2,\u2009...,\u2009bn\u2009/\u2009k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k\u2009+\u20091, k\u2009+\u20092, ..., 2\u00b7k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit bi and is divisible by ai if represented as an integer. To represent the block of length k as an integer, let's write it out as a sequence c1, c2,...,ck. Then the integer is calculated as the result of the expression c1\u00b710k\u2009-\u20091\u2009+\u2009c2\u00b710k\u2009-\u20092\u2009+\u2009...\u2009+\u2009ck.Pasha asks you to calculate the number of good phone numbers of length n, for the given k, ai and bi. As this number can be too big, print it modulo 109\u2009+\u20097. ", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009min(n,\u20099))\u00a0\u2014 the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k. The second line of the input contains n\u2009/\u2009k space-separated positive integers\u00a0\u2014 sequence a1,\u2009a2,\u2009...,\u2009an\u2009/\u2009k (1\u2009\u2264\u2009ai\u2009<\u200910k). The third line of the input contains n\u2009/\u2009k space-separated positive integers\u00a0\u2014 sequence b1,\u2009b2,\u2009...,\u2009bn\u2009/\u2009k (0\u2009\u2264\u2009bi\u2009\u2264\u20099). ", "output_spec": "Print a single integer\u00a0\u2014 the number of good phone numbers of length n modulo 109\u2009+\u20097.", "sample_inputs": ["6 2\n38 56 49\n7 3 4", "8 2\n1 22 3 44\n5 4 3 2"], "sample_outputs": ["8", "32400"], "notes": "NoteIn the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698."}, "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"}, {"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"}], "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"} {"nl": {"description": "Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute \u2014 at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \\not\\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \\le L, v \\le 10^9$$$, $$$1 \\le l \\le r \\le L$$$) \u2014 destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.", "output_spec": "Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer \u2014 the answer for the $$$i$$$-th query.", "sample_inputs": ["4\n10 2 3 7\n100 51 51 51\n1234 1 100 199\n1000000000 1 1 1000000000"], "sample_outputs": ["3\n0\n1134\n0"], "notes": "NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path."}, "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, 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}"}, {"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"} {"nl": {"description": "Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $$$100^{500}$$$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $$$i$$$-th attack is performed at the beginning of the $$$a_i$$$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $$$1$$$ damage during each of the next $$$k$$$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose $$$k = 4$$$, and Monocarp stabs the dragon during the seconds $$$2$$$, $$$4$$$ and $$$10$$$. Then the poison effect is applied at the start of the $$$2$$$-nd second and deals $$$1$$$ damage during the $$$2$$$-nd and $$$3$$$-rd seconds; then, at the beginning of the $$$4$$$-th second, the poison effect is reapplied, so it deals exactly $$$1$$$ damage during the seconds $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$; then, during the $$$10$$$-th second, the poison effect is applied again, and it deals $$$1$$$ damage during the seconds $$$10$$$, $$$11$$$, $$$12$$$ and $$$13$$$. In total, the dragon receives $$$10$$$ damage.Monocarp knows that the dragon has $$$h$$$ hit points, and if he deals at least $$$h$$$ damage to the dragon during the battle \u2014 he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $$$k$$$ (the number of seconds the poison effect lasts) that is enough to deal at least $$$h$$$ damage to the dragon.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$h$$$ ($$$1 \\le n \\le 100; 1 \\le h \\le 10^{18}$$$)\u00a0\u2014 the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 10^9; a_i < a_{i + 1}$$$), where $$$a_i$$$ is the second when the $$$i$$$-th attack is performed.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the minimum value of the parameter $$$k$$$, such that Monocarp will cause at least $$$h$$$ damage to the dragon.", "sample_inputs": ["4\n2 5\n1 5\n3 10\n2 4 10\n5 3\n1 2 4 5 7\n4 1000\n3 25 64 1337"], "sample_outputs": ["3\n4\n1\n470"], "notes": "NoteIn the first example, for $$$k=3$$$, damage is dealt in seconds $$$[1, 2, 3, 5, 6, 7]$$$.In the second example, for $$$k=4$$$, damage is dealt in seconds $$$[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$$$.In the third example, for $$$k=1$$$, damage is dealt in seconds $$$[1, 2, 4, 5, 7]$$$."}, "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 = readLong()\n val arr = new Array[Long](n)\n for (i <- 1 to n) {\n arr(i-1) = readLong()\n }\n quickSort(arr)\n\n def check(kk: Long): Boolean = {\n var dmg = 0L\n for (i <- (0 until n).reverse) {\n if (i == n-1) {\n dmg += kk\n } else {\n if (arr(i) + kk < 0)\n dmg += arr(i+1) - arr(i)\n else\n dmg += min(arr(i+1), arr(i)+kk) - arr(i)\n }\n }\n if (dmg >= m)\n return true\n else\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 writer.println(bs(1, m))\n }\n writer.flush()\n}"}], "negative_code": [], "src_uid": "3d0685162fbb432c37bb6aeb5fe51f94"} {"nl": {"description": "Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n\u2009\u00d7\u2009n matrix \u0410: there is a number on the intersection of the \u0456-th row and j-th column that describes the result of the collision of the \u0456-th and the j-th car: \u2009-\u20091: if this pair of cars never collided. \u2009-\u20091 occurs only on the main diagonal of the matrix. 0: if no car turned over during the collision. 1: if only the i-th car turned over during the collision. 2: if only the j-th car turned over during the collision. 3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of cars. Each of the next n lines contains n space-separated integers that determine matrix A. It is guaranteed that on the main diagonal there are \u2009-\u20091, and \u2009-\u20091 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if Aij\u2009=\u20091, then Aji\u2009=\u20092, if Aij\u2009=\u20093, then Aji\u2009=\u20093, and if Aij\u2009=\u20090, then Aji\u2009=\u20090.", "output_spec": "Print the number of good cars and in the next line print their space-separated indices in the increasing order.", "sample_inputs": ["3\n-1 0 0\n0 -1 1\n0 2 -1", "4\n-1 3 3 3\n3 -1 3 3\n3 3 -1 3\n3 3 3 -1"], "sample_outputs": ["2\n1 3", "0"], "notes": null}, "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": "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"}, {"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"} {"nl": {"description": "Adilbek was assigned to a special project. For Adilbek it means that he has $$$n$$$ days to run a special program and provide its results. But there is a problem: the program needs to run for $$$d$$$ days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends $$$x$$$ ($$$x$$$ is a non-negative integer) days optimizing the program, he will make the program run in $$$\\left\\lceil \\frac{d}{x + 1} \\right\\rceil$$$ days ($$$\\left\\lceil a \\right\\rceil$$$ is the ceiling function: $$$\\left\\lceil 2.4 \\right\\rceil = 3$$$, $$$\\left\\lceil 2 \\right\\rceil = 2$$$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $$$x + \\left\\lceil \\frac{d}{x + 1} \\right\\rceil$$$.Will Adilbek be able to provide the generated results in no more than $$$n$$$ days?", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 50$$$) \u2014 the number of test cases. The next $$$T$$$ lines contain test cases \u2013 one per line. Each line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \\le n \\le 10^9$$$, $$$1 \\le d \\le 10^9$$$) \u2014 the number of days before the deadline and the number of days the program runs.", "output_spec": "Print $$$T$$$ answers \u2014 one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $$$n$$$ days or NO (case insensitive) otherwise.", "sample_inputs": ["3\n1 1\n4 5\n5 11"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteIn the first test case, Adilbek decides not to optimize the program at all, since $$$d \\le n$$$.In the second test case, Adilbek can spend $$$1$$$ day optimizing the program and it will run $$$\\left\\lceil \\frac{5}{2} \\right\\rceil = 3$$$ days. In total, he will spend $$$4$$$ days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $$$2$$$ days, it'll still work $$$\\left\\lceil \\frac{11}{2+1} \\right\\rceil = 4$$$ days."}, "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 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"}, {"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 (_ \u2190 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 \u21d2 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"} {"nl": {"description": "Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.", "input_spec": "First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000), the number of days. Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.", "output_spec": "Output n\u2009+\u20091 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n\u2009+\u20091)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.", "sample_inputs": ["ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler", "icm codeforces\n1\ncodeforces technex"], "sample_outputs": ["ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler", "icm codeforces\nicm technex"], "notes": "NoteIn first example, the killer starts with ross and rachel. After day 1, ross is killed and joey appears. After day 2, rachel is killed and phoebe appears. After day 3, phoebe is killed and monica appears. After day 4, monica is killed and chandler appears. "}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.There are $$$n$$$ doors, the $$$i$$$-th door initially has durability equal to $$$a_i$$$.During your move you can try to break one of the doors. If you choose door $$$i$$$ and its current durability is $$$b_i$$$ then you reduce its durability to $$$max(0, b_i - x)$$$ (the value $$$x$$$ is given).During Slavik's move he tries to repair one of the doors. If he chooses door $$$i$$$ and its current durability is $$$b_i$$$ then he increases its durability to $$$b_i + y$$$ (the value $$$y$$$ is given). Slavik cannot repair doors with current durability equal to $$$0$$$.The game lasts $$$10^{100}$$$ turns. If some player cannot make his move then he has to skip it.Your goal is to maximize the number of doors with durability equal to $$$0$$$ at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le x, y \\le 10^5$$$) \u2014 the number of doors, value $$$x$$$ and value $$$y$$$, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^5$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th door.", "output_spec": "Print one integer \u2014 the number of doors with durability equal to $$$0$$$ at the end of the game, if you and Slavik both play optimally.", "sample_inputs": ["6 3 2\n2 3 1 3 4 2", "5 3 3\n1 2 4 2 3", "5 5 6\n1 2 6 10 3"], "sample_outputs": ["6", "2", "2"], "notes": "NoteClarifications about the optimal strategy will be ignored."}, "positive_code": [{"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"}, {"source_code": "object Main {\n def main(args: Array[String]): Unit = {\n val s = new Main()\n s.solve()\n s.out.flush()\n }\n}\n\nclass Main {\n import java.io._\n import java.util.StringTokenizer\n\n import scala.collection.mutable\n import scala.util.Sorting\n import math.{abs, max, min}\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"} {"nl": {"description": "In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number\u2019s integer part. If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number\u2019s integer part. If the number\u2019s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King\u2019s order?", "input_spec": "The first line contains a single number to round up \u2014 the integer part (a non-empty set of decimal digits that do not start with 0 \u2014 with the exception of a case when the set consists of a single digit \u2014 in this case 0 can go first), then follows character \u00ab.\u00bb (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.", "output_spec": "If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message \"GOTO Vasilisa.\" (without the quotes).", "sample_inputs": ["0.0", "1.49", "1.50", "2.71828182845904523536", "3.14159265358979323846", "12345678901234567890.1", "123456789123456789.999"], "sample_outputs": ["0", "1", "2", "3", "3", "12345678901234567890", "GOTO Vasilisa."], "notes": null}, "positive_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')\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 \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"} {"nl": {"description": "Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n\u2009-\u20091 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is , where is bitwise xor operation.Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities in Mahmoud and Ehab's country. Then the second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009106) which represent the numbers attached to the cities. Integer ai is attached to the city i. Each of the next n\u2009\u2009-\u2009\u20091 lines contains two integers u and v (1\u2009\u2009\u2264\u2009\u2009u,\u2009\u2009v\u2009\u2009\u2264\u2009\u2009n, u\u2009\u2009\u2260\u2009\u2009v), denoting that there is an undirected road between cities u and v. It's guaranteed that you can reach any city from any other using these roads.", "output_spec": "Output one number denoting the total distance between all pairs of cities.", "sample_inputs": ["3\n1 2 3\n1 2\n2 3", "5\n1 2 3 4 5\n1 2\n2 3\n3 4\n3 5", "5\n10 9 8 7 6\n1 2\n2 3\n3 4\n3 5"], "sample_outputs": ["10", "52", "131"], "notes": "NoteA bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.In the first sample the available paths are: city 1 to itself with a distance of 1, city 2 to itself with a distance of 2, city 3 to itself with a distance of 3, city 1 to city 2 with a distance of , city 1 to city 3 with a distance of , city 2 to city 3 with a distance of . The total distance between all pairs of cities equals 1\u2009+\u20092\u2009+\u20093\u2009+\u20093\u2009+\u20090\u2009+\u20091\u2009=\u200910."}, "positive_code": [{"source_code": "import scala.io.StdIn.readLine\n\nobject MahmudXorTrip extends App {\n private def combWith(as: Array[Long], bs: Array[Long])(f: (Long, Long) \u21d2 Long): Array[Long] = {\n val res = Array.ofDim[Long](20)\n var i = 0\n while(i < 20){\n res(i) = f(as(i), bs(i))\n i+=1\n }\n res\n }\n case class Counts(count: Long = 0, bitCounts: Array[Long] = Array.fill(20)(0)) {\n def +(that: Counts) = Counts(count + that.count, combWith(bitCounts, that.bitCounts)(_ + _))\n def -(that: Counts) = Counts(count - that.count, combWith(bitCounts, that.bitCounts)(_ - _))\n def ^(num: Int) = Counts(count, bitCounts.zipWithIndex.map { case (c, i) \u21d2\n if ((num & (1 << i)) == 0) c else count - c\n })\n def *(that: Counts) = Counts(count * that.count, combWith(bitCounts, that.bitCounts) {\n (c, tc) \u21d2 c * (that.count - tc) + tc * (count - c)\n })\n\n private def countsStr = bitCounts.zipWithIndex.filter(_._1 != 0).mkString(\"[\", \",\", \"]\")\n override def toString: String = s\"Count($count, $countsStr)\"\n }\n val zero = Counts()\n val one = Counts(1)\n\n case class Step(num: Int, remains: List[Int], attSum: Counts = zero, detSum: Counts = zero, prodSum: Counts = zero) {\n def add(att: Counts, det: Counts) = Step(num, remains.tail, attSum + att, detSum + det, prodSum + attSum * att)\n }\n object ChildDown {\n def unapply(step: Step): Option[(Int, Step)] = step.remains match {\n case next :: rest \u21d2 Some((next, step.copy(remains = rest)))\n case Nil \u21d2 None\n }\n }\n val n = readLine().toInt\n val labels = -1 +: readLine().split(' ').map(_.toInt)\n val roads = Iterator.fill(n - 1)(readLine().split(' ').map(_.toInt))\n .flatMap { case Array(a, b) \u21d2 Seq(a \u2192 b, b \u2192 a) }\n .toList.groupBy(_._1).mapValues(_.map(_._2))\n\n def go(stack: List[Step]): Counts = {\n// println(stack)\n stack match {\n case step :: upper if step.remains.nonEmpty \u21d2\n val next = step.remains.head\n go(Step(next, roads(next).filter(_ != step.num)) :: step :: upper)\n case Step(num, _, attSum, detSum, prodSum) :: upper \u21d2\n val detach = attSum + detSum + (prodSum ^ labels(num))\n val attach = (attSum + one) ^ labels(num)\n upper match {\n case Nil \u21d2 attach + detach\n case pstep :: upup \u21d2 go(pstep.add(attach, detach) :: upup)\n }\n }\n }\n\n val resState = if(n == 1) one ^ labels(1) else go(Step(1, roads(1), zero, zero, zero) :: Nil)\n// println(resState)\n val result = resState.bitCounts.zipWithIndex\n .map { case (c, i) \u21d2 c.toLong << i }.sum\n\n println(result)\n}\n"}], "negative_code": [], "src_uid": "c44554273f9c53d11aa1b0edeb121113"} {"nl": {"description": "Did you know you can download more RAM? There is a shop with $$$n$$$ different pieces of software that increase your RAM. The $$$i$$$-th RAM increasing software takes $$$a_i$$$ GB of memory to run (temporarily, once the program is done running, you get the RAM back), and gives you an additional $$$b_i$$$ GB of RAM (permanently). Each software can only be used once. Your PC currently has $$$k$$$ GB of RAM.Note that you can't use a RAM-increasing software if it takes more GB of RAM to use than what you currently have.Since RAM is the most important thing in the world, you wonder, what is the maximum possible amount of RAM achievable?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le k \\le 1000$$$). Then two lines follow, each containing $$$n$$$ integers describing the arrays $$$a$$$ and $$$b$$$ ($$$1 \\le a_i, b_i \\le 1000$$$).", "output_spec": "For each test case, output a single line containing the largest amount of RAM you can achieve.", "sample_inputs": ["4\n\n3 10\n\n20 30 10\n\n9 100 10\n\n5 1\n\n1 1 5 1 1\n\n1 1 1 1 1\n\n5 1\n\n2 2 2 2 2\n\n100 100 100 100 100\n\n5 8\n\n128 64 32 16 8\n\n128 64 32 16 8"], "sample_outputs": ["29\n6\n1\n256"], "notes": "NoteIn the first test case, you only have enough RAM to run the third software initially, but that increases your RAM to $$$20$$$ GB, which allows you to use the first software, increasing your RAM to $$$29$$$ GB. The only software left needs $$$30$$$ GB of RAM, so you have to stop here.In the second test case, you can use the first, second, fourth and fifth software that need only $$$1$$$ GB of RAM per software to run to increase your RAM to $$$5$$$ GB, and then use the last remaining one to increase your RAM to $$$6$$$ GB.In the third test case, all the software need more than $$$1$$$ GB of RAM to run, so the amount of RAM you have stays at $$$1$$$ GB."}, "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(_, 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"}, {"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"} {"nl": {"description": "Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n\u2009-\u2009i\u2009+\u20091)-th. He does this while i\u2009\u2264\u2009n\u2009-\u2009i\u2009+\u20091.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday\u00a0\u2014 restore the initial order of the cubes using information of their current location.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of cubes. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the number written on the i-th cube after Dima has changed their order.", "output_spec": "Print n integers, separated by spaces\u00a0\u2014 the numbers written on the cubes in their initial order. It can be shown that the answer is unique.", "sample_inputs": ["7\n4 3 7 6 9 1 2", "8\n6 1 4 2 5 6 9 2"], "sample_outputs": ["2 3 9 6 7 1 4", "2 1 6 2 5 4 9 6"], "notes": "NoteConsider the first sample. At the begining row was [2, 3, 9, 6, 7, 1, 4]. After first operation row was [4, 1, 7, 6, 9, 3, 2]. After second operation row was [4, 3, 9, 6, 7, 1, 2]. After third operation row was [4, 3, 7, 6, 9, 1, 2]. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. "}, "positive_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 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"}, {"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"}, {"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}"}], "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"} {"nl": {"description": "Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example: the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds; the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array; the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \\ne 1$$$; the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \\ne 1$$$; the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u2014 the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \\le s \\le 5000$$$) for the $$$i$$$-th test case.", "output_spec": "Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.", "sample_inputs": ["4\n1\n8\n7\n42"], "sample_outputs": ["1\n3\n3\n7"], "notes": "NoteConsider the example test: in the first test case, the array $$$[1]$$$ meets all conditions; in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions; in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions; in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions. "}, "positive_code": [{"source_code": "object A extends App {\r\n import scala.io.StdIn._\r\n\r\n def f: Int => Int = x => math.ceil(math.sqrt(x)).toInt\r\n\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val x = readInt()\r\n println(f(x))\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "322792a11d3eb1df6b54e8f89c9a0490"} {"nl": {"description": "Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom \"Graph Theory\". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100000)\u00a0\u2014 the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n. The second line contains n\u2009-\u20091 integer a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n)\u00a0\u2014 the numbers of episodes that Polycarpus has watched. All values of ai are distinct.", "output_spec": "Print the number of the episode that Polycarpus hasn't watched.", "sample_inputs": ["10\n3 8 10 1 7 9 6 5 2"], "sample_outputs": ["4"], "notes": null}, "positive_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 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}"}, {"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": "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}"}, {"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": "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}"}], "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"} {"nl": {"description": "In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k\u2009-\u20091)m,\u2009(k\u2009-\u20091)m\u2009+\u2009l], and l\u2009<\u2009m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.", "input_spec": "The first input line contains 4 integer numbers n, d, m, l (1\u2009\u2264\u2009n,\u2009d,\u2009m,\u2009l\u2009\u2264\u2009106,\u2009l\u2009<\u2009m) \u2014 respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k\u2009-\u20091)m,\u2009(k\u2009-\u20091)m\u2009+\u2009l].", "output_spec": "Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.", "sample_inputs": ["2 2 5 3", "5 4 11 8"], "sample_outputs": ["4", "20"], "notes": null}, "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"}, {"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 "}], "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"} {"nl": {"description": "A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre \u2014 an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1,\u2009a2,\u2009...,\u2009an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1\u2009\u2264\u2009x\u2009\u2264\u2009k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.", "input_spec": "The first line of the input contains two integers n and k (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.", "output_spec": "Print a single number \u2014 the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.", "sample_inputs": ["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"], "sample_outputs": ["3", "1"], "notes": "NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2,\u20093,\u20092,\u20093,\u20093,\u20093 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1,\u20091,\u20093,\u20093,\u20093,\u20091,\u20091,\u20093 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1,\u20091,\u20092,\u20092,\u20091,\u20091 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses."}, "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, 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"}, {"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"} {"nl": {"description": "After defeating a Blacklist Rival, you get a chance to draw $$$1$$$ reward slip out of $$$x$$$ hidden valid slips. Initially, $$$x=3$$$ and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are $$$c$$$, $$$m$$$, and $$$p$$$, respectively. There is also a volatility factor $$$v$$$. You can play any number of Rival Races as long as you don't draw a Pink Slip. Assume that you win each race and get a chance to draw a reward slip. In each draw, you draw one of the $$$x$$$ valid items with their respective probabilities. Suppose you draw a particular item and its probability of drawing before the draw was $$$a$$$. Then, If the item was a Pink Slip, the quest is over, and you will not play any more races. Otherwise, If $$$a\\leq v$$$, the probability of the item drawn becomes $$$0$$$ and the item is no longer a valid item for all the further draws, reducing $$$x$$$ by $$$1$$$. Moreover, the reduced probability $$$a$$$ is distributed equally among the other remaining valid items. If $$$a > v$$$, the probability of the item drawn reduces by $$$v$$$ and the reduced probability is distributed equally among the other valid items. For example, If $$$(c,m,p)=(0.2,0.1,0.7)$$$ and $$$v=0.1$$$, after drawing Cash, the new probabilities will be $$$(0.1,0.15,0.75)$$$. If $$$(c,m,p)=(0.1,0.2,0.7)$$$ and $$$v=0.2$$$, after drawing Cash, the new probabilities will be $$$(Invalid,0.25,0.75)$$$. If $$$(c,m,p)=(0.2,Invalid,0.8)$$$ and $$$v=0.1$$$, after drawing Cash, the new probabilities will be $$$(0.1,Invalid,0.9)$$$. If $$$(c,m,p)=(0.1,Invalid,0.9)$$$ and $$$v=0.2$$$, after drawing Cash, the new probabilities will be $$$(Invalid,Invalid,1.0)$$$. You need the cars of Rivals. So, you need to find the expected number of races that you must play in order to draw a pink slip.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 10$$$) \u00a0\u2014 the number of test cases. The first and the only line of each test case contains four real numbers $$$c$$$, $$$m$$$, $$$p$$$ and $$$v$$$ ($$$0 < c,m,p < 1$$$, $$$c+m+p=1$$$, $$$0.1\\leq v\\leq 0.9$$$). Additionally, it is guaranteed that each of $$$c$$$, $$$m$$$, $$$p$$$ and $$$v$$$ have at most $$$4$$$ decimal places.", "output_spec": "For each test case, output a single line containing a single real number\u00a0\u2014 the expected number of races that you must play in order to draw a Pink Slip. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["4\n0.2 0.2 0.6 0.2\n0.4 0.2 0.4 0.8\n0.4998 0.4998 0.0004 0.1666\n0.3125 0.6561 0.0314 0.2048"], "sample_outputs": ["1.532000000000\n1.860000000000\n5.005050776521\n4.260163673896"], "notes": "NoteFor the first test case, the possible drawing sequences are: P with a probability of $$$0.6$$$; CP with a probability of $$$0.2\\cdot 0.7 = 0.14$$$; CMP with a probability of $$$0.2\\cdot 0.3\\cdot 0.9 = 0.054$$$; CMMP with a probability of $$$0.2\\cdot 0.3\\cdot 0.1\\cdot 1 = 0.006$$$; MP with a probability of $$$0.2\\cdot 0.7 = 0.14$$$; MCP with a probability of $$$0.2\\cdot 0.3\\cdot 0.9 = 0.054$$$; MCCP with a probability of $$$0.2\\cdot 0.3\\cdot 0.1\\cdot 1 = 0.006$$$. So, the expected number of races is equal to $$$1\\cdot 0.6 + 2\\cdot 0.14 + 3\\cdot 0.054 + 4\\cdot 0.006 + 2\\cdot 0.14 + 3\\cdot 0.054 + 4\\cdot 0.006 = 1.532$$$.For the second test case, the possible drawing sequences are: P with a probability of $$$0.4$$$; CP with a probability of $$$0.4\\cdot 0.6 = 0.24$$$; CMP with a probability of $$$0.4\\cdot 0.4\\cdot 1 = 0.16$$$; MP with a probability of $$$0.2\\cdot 0.5 = 0.1$$$; MCP with a probability of $$$0.2\\cdot 0.5\\cdot 1 = 0.1$$$. So, the expected number of races is equal to $$$1\\cdot 0.4 + 2\\cdot 0.24 + 3\\cdot 0.16 + 2\\cdot 0.1 + 3\\cdot 0.1 = 1.86$$$."}, "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) = 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"}, {"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"} {"nl": {"description": "Alice and Bob play a game. They have a binary string $$$s$$$ (a string such that each character in it is either $$$0$$$ or $$$1$$$). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in $$$s$$$ and delete them.For example, if the string is $$$10110$$$, there are $$$6$$$ possible moves (deleted characters are bold): $$$\\textbf{1}0110 \\to 0110$$$; $$$1\\textbf{0}110 \\to 1110$$$; $$$10\\textbf{1}10 \\to 1010$$$; $$$101\\textbf{1}0 \\to 1010$$$; $$$10\\textbf{11}0 \\to 100$$$; $$$1011\\textbf{0} \\to 1011$$$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I.\u2009e. the following sequence of moves is valid: $$$10\\textbf{11}0 \\to 1\\textbf{00} \\to 1$$$.The game ends when the string becomes empty, and the score of each player is the number of $$$1$$$-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 500$$$) \u2014 the number of test cases. Each test case contains exactly one line containing a binary string $$$s$$$ ($$$1 \\le |s| \\le 100$$$).", "output_spec": "For each test case, print one integer \u2014 the resulting score of Alice (the number of $$$1$$$-characters deleted by her).", "sample_inputs": ["5\n01111001\n0000\n111111\n101010101\n011011110111"], "sample_outputs": ["4\n0\n6\n3\n6"], "notes": "NoteQuestions about the optimal strategy will be ignored."}, "positive_code": [{"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"}, {"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"} {"nl": {"description": "Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci \u2014 the receiving time (the second) and the number of the text messages, correspondingly.Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows: If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1\u2009\u2264\u2009ti,\u2009ci\u2009\u2264\u2009106) \u2014 the time (the second) when the i-th task was received and the number of messages to send, correspondingly. It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti\u2009<\u2009ti\u2009+\u20091 for all integer i (1\u2009\u2264\u2009i\u2009<\u2009n).", "output_spec": "In a single line print two space-separated integers \u2014 the time when the last text message was sent and the maximum queue size at a certain moment of time.", "sample_inputs": ["2\n1 1\n2 1", "1\n1000000 10", "3\n3 3\n4 3\n5 3"], "sample_outputs": ["3 1", "1000010 10", "12 7"], "notes": "NoteIn the first test sample: second 1: the first message has appeared in the queue, the queue's size is 1; second 2: the first message is sent, the second message has been received, the queue's size is 1; second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3."}, "positive_code": [{"source_code": "/*\nA. SMS-\u0446\u0435\u043d\u0442\u0440\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b\n\u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u043f\u0430\u043c\u044f\u0442\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\n256 \u043c\u0435\u0433\u0430\u0431\u0430\u0439\u0442\n\u0432\u0432\u043e\u0434\nstandard input\n\u0432\u044b\u0432\u043e\u0434\nstandard output\n\n\u0412 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446\u0438\u0438, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f, \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0441\u043e\u0431\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 sms-\u0446\u0435\u043d\u0442\u0440. \u0417\u0430\u0434\u0430\u0447\u0435\u0439 \u0446\u0435\u043d\u0442\u0440\u0430 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0440\u0430\u0441\u0441\u044b\u043b\u043a\u0430 \u0441\u043e\u0442\u0440\u0443\u0434\u043d\u0438\u043a\u0430\u043c \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u043e\u0439 \u0432\u0430\u0436\u043d\u043e\u0439 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438. \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0440\u0435\u0448\u0438\u043b \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u043e\u0441\u0442\u044c \u0440\u0430\u0431\u043e\u0442\u044b sms-\u0446\u0435\u043d\u0442\u0440\u0430.\n\n\u0414\u043b\u044f \u044d\u0442\u043e\u0433\u043e \u043e\u043d \u043f\u043e\u043f\u0440\u043e\u0441\u0438\u043b \u043f\u0440\u0435\u0434\u043e\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u0435\u043c\u0443 \u0434\u0430\u043d\u043d\u044b\u0435 \u043e \u0440\u0430\u0431\u043e\u0442\u0435 sms-\u0446\u0435\u043d\u0442\u0440\u0430 \u0437\u0430 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043f\u0435\u0440\u0438\u043e\u0434 \u0432\u0440\u0435\u043c\u0435\u043d\u0438. \u0412 \u043e\u0442\u0432\u0435\u0442 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u043f\u043e\u043b\u0443\u0447\u0438\u043b \u0441\u043f\u0438\u0441\u043e\u043a \u0438\u0437 n \u0437\u0430\u0434\u0430\u043d\u0438\u0439, \u043f\u043e\u0441\u0442\u0443\u043f\u0430\u0432\u0448\u0438\u0445 \u0432 sms-\u0446\u0435\u043d\u0442\u0440 \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u0438. \u041a\u0430\u0436\u0434\u043e\u0435 \u0437\u0430\u0434\u0430\u043d\u0438\u0435 \u043e\u043f\u0438\u0441\u044b\u0432\u0430\u043b\u043e\u0441\u044c \u0432\u0440\u0435\u043c\u0435\u043d\u0435\u043c \u043f\u043e\u0441\u0442\u0443\u043f\u043b\u0435\u043d\u0438\u044f \u0432 sms-\u0446\u0435\u043d\u0442\u0440 \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e\u043c sms-\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043d\u0443\u0436\u043d\u043e \u0431\u044b\u043b\u043e \u043e\u0442\u043e\u0441\u043b\u0430\u0442\u044c. \u0411\u043e\u043b\u0435\u0435 \u0444\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, i-\u043e\u0435 \u0437\u0430\u0434\u0430\u043d\u0438\u0435 \u043e\u043f\u0438\u0441\u044b\u0432\u0430\u043b\u043e\u0441\u044c \u0434\u0432\u0443\u043c\u044f \u0446\u0435\u043b\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 ti \u0438 ci \u2014 \u043c\u043e\u043c\u0435\u043d\u0442\u043e\u043c \u0432\u0440\u0435\u043c\u0435\u043d\u0438 (\u0441\u0435\u043a\u0443\u043d\u0434\u043e\u0439) \u043f\u043e\u0441\u0442\u0443\u043f\u043b\u0435\u043d\u0438\u044f \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e\u043c sms-\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e.\n\n\u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0437\u043d\u0430\u0435\u0442, \u0447\u0442\u043e sms-\u0446\u0435\u043d\u0442\u0440 \u043c\u043e\u0436\u0435\u0442 \u043e\u0442\u0441\u044b\u043b\u0430\u0442\u044c \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u043e\u0434\u043d\u043e\u0433\u043e sms-\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0432 \u0441\u0435\u043a\u0443\u043d\u0434\u0443. \u0414\u043b\u044f \u043e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446\u0438\u0438 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0438 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439 sms-\u0446\u0435\u043d\u0442\u0440 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442 \u043e\u0447\u0435\u0440\u0435\u0434\u044c. \u0420\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x, sms-\u0446\u0435\u043d\u0442\u0440 \u0431\u0443\u0434\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0432 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c:\n\n \u0415\u0441\u043b\u0438 \u0432 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x \u043e\u0447\u0435\u0440\u0435\u0434\u044c \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439 \u043d\u0435 \u043f\u0443\u0441\u0442\u0430, \u0442\u043e\u0433\u0434\u0430 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0430 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0438\u0437 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 (\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u0431\u0435\u0440\u0435\u0442\u0441\u044f \u0438\u0437 \u0433\u043e\u043b\u043e\u0432\u044b \u043e\u0447\u0435\u0440\u0435\u0434\u0438). \u0418\u043d\u0430\u0447\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0430 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0432 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x \u043d\u0435 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442.\n \u0415\u0441\u043b\u0438 \u0432 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x \u043f\u043e\u0441\u0442\u0443\u043f\u0438\u043b\u043e \u0437\u0430\u0434\u0430\u043d\u0438\u0435 \u043d\u0430 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0443 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439, \u0442\u043e \u0432 \u043e\u0447\u0435\u0440\u0435\u0434\u044c \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u0432\u0441\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0438\u0437 \u044d\u0442\u043e\u0433\u043e \u0437\u0430\u0434\u0430\u043d\u0438\u044f (\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u0432 \u0445\u0432\u043e\u0441\u0442 \u043e\u0447\u0435\u0440\u0435\u0434\u0438). \u041e\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435, \u043d\u0438 \u043e\u0434\u043d\u043e \u0438\u0437 \u044d\u0442\u0438\u0445 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439 \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e \u0432 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x, \u0442\u0430\u043a \u043a\u0430\u043a \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u043e\u0431 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0435 \u0438\u043b\u0438 \u043d\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0432 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 x \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442\u0441\u044f \u0432 \u043f\u0443\u043d\u043a\u0442\u0435 1 \u0434\u043e \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u044d\u0442\u0438\u0445 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439. \n\n\u041f\u043e \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430\u043c \u0430\u043d\u0430\u043b\u0438\u0437\u0430 \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u0432\u0441\u0435\u0445 n \u0437\u0430\u0434\u0430\u043d\u0438\u0439 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f \u0445\u043e\u0447\u0435\u0442 \u043f\u043e\u0441\u0447\u0438\u0442\u0430\u0442\u044c \u0434\u0432\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b: \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438, \u043a\u043e\u0433\u0434\u0430 \u0431\u044b\u043b\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 sms-\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435, \u0430 \u0442\u0430\u043a\u0436\u0435 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 \u0432 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438. \u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u0435\u043c\u0443 \u043f\u043e\u0441\u0447\u0438\u0442\u0430\u0442\u044c \u044d\u0442\u0438 \u0434\u0432\u0435 \u0445\u0430\u0440\u0430\u043a\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043a\u0438, \u043f\u043e \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u043e\u043d \u043e\u0446\u0435\u043d\u0438\u0442 \u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u043e\u0441\u0442\u044c \u0440\u0430\u0431\u043e\u0442\u044b sms-\u0446\u0435\u043d\u0442\u0440\u0430.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d\u043e \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0437\u0430\u0434\u0430\u043d\u0438\u0439 \u0440\u0430\u0441\u0441\u044b\u043b\u043a\u0438 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439. \u0414\u0430\u043b\u0435\u0435 \u0432 n \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0437\u0430\u0434\u0430\u043d\u044b \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u0437\u0430\u0434\u0430\u043d\u0438\u0439: \u0432 i-\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0437\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 ti \u0438 ci (1\u2009\u2264\u2009ti,\u2009ci\u2009\u2264\u2009106) \u2014 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 (\u0441\u0435\u043a\u0443\u043d\u0434\u0430) \u043f\u043e\u0441\u0442\u0443\u043f\u043b\u0435\u043d\u0438\u044f i-\u0433\u043e \u0437\u0430\u0434\u0430\u043d\u0438\u044f \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043d\u0443\u0436\u043d\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c, \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0435\u043d\u043d\u043e.\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0441\u0435 \u0437\u0430\u0434\u0430\u043d\u0438\u044f \u043f\u043e\u0441\u0442\u0443\u043f\u0430\u043b\u0438 \u0432 \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0435 \u043c\u043e\u043c\u0435\u043d\u0442\u044b \u0432\u0440\u0435\u043c\u0435\u043d\u0438. \u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0437\u0430\u0434\u0430\u043d\u0438\u044f \u043e\u0442\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u044b \u0432 \u0445\u0440\u043e\u043d\u043e\u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u043e\u043c \u043f\u043e\u0440\u044f\u0434\u043a\u0435, \u0442\u043e \u0435\u0441\u0442\u044c ti\u2009<\u2009ti\u2009+\u20091 \u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0446\u0435\u043b\u044b\u0445 i (1\u2009\u2264\u2009i\u2009<\u2009n).\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0447\u0435\u0440\u0435\u0437 \u043f\u0440\u043e\u0431\u0435\u043b \u0432\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0434\u0432\u0430 \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u043b\u0430 \u2014 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438, \u043a\u043e\u0433\u0434\u0430 \u0431\u044b\u043b\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 sms-\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 \u0432 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u0432\u0440\u0435\u043c\u0435\u043d\u0438.\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2\n1 1\n2 1\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n3 1\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1\n1000000 10\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1000010 10\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n3\n3 3\n4 3\n5 3\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n12 7\n\n\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435:\n\n \u0441\u0435\u043a\u0443\u043d\u0434\u0430 1 \u2014 \u043f\u0435\u0440\u0432\u043e\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043f\u043e\u044f\u0432\u0438\u043b\u043e\u0441\u044c \u0432 \u043e\u0447\u0435\u0440\u0435\u0434\u0438, \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 1;\n \u0441\u0435\u043a\u0443\u043d\u0434\u0430 2 \u2014 \u043f\u0435\u0440\u0432\u043e\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e, \u0432\u0442\u043e\u0440\u043e\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043f\u043e\u044f\u0432\u0438\u043b\u043e\u0441\u044c \u0432 \u043e\u0447\u0435\u0440\u0435\u0434\u0438, \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 1;\n \u0441\u0435\u043a\u0443\u043d\u0434\u0430 3 \u2014 \u0432\u0442\u043e\u0440\u043e\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e, \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 0, \n\n\u0422\u0430\u043a\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c, \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u0447\u0435\u0440\u0435\u0434\u0438 1, \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e \u0432 \u0441\u0435\u043a\u0443\u043d\u0434\u0443 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}"}, {"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"} {"nl": {"description": "Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of \u00abHunger Games\u00bb for the ants. He chooses two numbers l and r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi\u2009=\u2009r\u2009-\u2009l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li,\u2009ri] and asks for each of them how many ants is he going to eat if those ants fight.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the size of the ant colony. The second line contains n integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u2009109), the strengths of the ants. The third line contains one integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009105), the number of test cases. Each of the next t lines contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n), describing one query.", "output_spec": "Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li,\u2009ri].", "sample_inputs": ["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"], "sample_outputs": ["4\n4\n1\n1"], "notes": "NoteIn the first test battle points for each ant are v\u2009=\u2009[4,\u20090,\u20092,\u20090,\u20092], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v\u2009=\u2009[0,\u20092,\u20090,\u20092], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v\u2009=\u2009[2,\u20090,\u20092], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v\u2009=\u2009[0,\u20091], so ant number 5 is freed. Mole eats the ant 4."}, "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 C271F(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 C271F(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 s: Array[Int] = na(n)\n val t = new SegmentTree(n, s)\n t.build(1, 0, n-1)\n val q = ni()\n// t.print()\n REP(q) { _ =>\n val l = ni()\n val r = ni()\n out.println((r - l + 1 ) - t.get(1, 0, n-1, l-1, r-1).count)\n }\n }\n\n case class Node(count: Int, number: Int)\n\n private class SegmentTree(n: Int, s: Array[Int]) {\n private val tree = Array.ofDim[Node](4 * n)\n\n private def gcd(x: Int, y: Int): Int = {\n if(y == 0) x\n else gcd(y, x % y)\n }\n\n private def combine(x: Node, y: Node): Node = {\n if(x.number == 0) y\n else if(y.number == 0) x\n else if(x.number == y.number) {\n Node(x.count + y.count, x.number)\n } else if(y.number % x.number == 0) {\n Node(x.count, x.number)\n } else if (x.number % y.number == 0) {\n Node(y.count, y.number)\n } else {\n Node(0, gcd(x.number, y.number))\n }\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n tree(v) = Node(1, s(tl))\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 get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Node = {\n if(l > r) Node(0, 0)\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 def print(): Unit = {\n tree.foreach(out.println)\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 C271F(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 C271F(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 s: Array[Int] = na(n)\n val t = new SegmentTree(n, s)\n t.build(1, 0, n-1)\n val q = ni()\n// t.print()\n REP(q) { _ =>\n val l = ni()\n val r = ni()\n out.println((r - l + 1 ) - t.get(1, 0, n-1, l-1, r-1).count)\n }\n }\n\n case class Node(count: Int, number: Int)\n\n private class SegmentTree(n: Int, s: Array[Int]) {\n private val tree = Array.ofDim[Node](4 * n)\n\n private def combine(x: Node, y: Node): Node = {\n if(x.number == 0) y\n else if(y.number == 0) x\n else if(x.number == y.number) {\n Node(x.count + y.count, x.number)\n } else if(y.number % x.number == 0) {\n Node(x.count, x.number)\n } else if (x.number % y.number == 0) {\n Node(y.count, y.number)\n } else {\n Node(0, Int.MaxValue)\n }\n }\n\n def build(v: Int, tl: Int, tr: Int): Unit = {\n if(tl == tr) {\n tree(v) = Node(1, s(tl))\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 get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Node = {\n if(l > r) Node(0, 0)\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 def print(): Unit = {\n tree.foreach(out.println)\n }\n }\n}\n"}], "src_uid": "f7f1d57921fe7b7a697967dcfc8f0169"} {"nl": {"description": "Student Dima from Kremland has a matrix $$$a$$$ of size $$$n \\times m$$$ filled with non-negative integers.He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!Formally, he wants to choose an integers sequence $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\leq c_j \\leq m$$$) so that the inequality $$$a_{1, c_1} \\oplus a_{2, c_2} \\oplus \\ldots \\oplus a_{n, c_n} > 0$$$ holds, where $$$a_{i, j}$$$ is the matrix element from the $$$i$$$-th row and the $$$j$$$-th column.Here $$$x \\oplus y$$$ denotes the bitwise XOR operation of integers $$$x$$$ and $$$y$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 500$$$)\u00a0\u2014 the number of rows and the number of columns in the matrix $$$a$$$. Each of the next $$$n$$$ lines contains $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$a$$$, i.e. $$$a_{i, j}$$$ ($$$0 \\leq a_{i, j} \\leq 1023$$$). ", "output_spec": "If there is no way to choose one integer from each row so that their bitwise exclusive OR is strictly greater than zero, print \"NIE\". Otherwise print \"TAK\" in the first line, in the next line print $$$n$$$ integers $$$c_1, c_2, \\ldots c_n$$$ ($$$1 \\leq c_j \\leq m$$$), so that the inequality $$$a_{1, c_1} \\oplus a_{2, c_2} \\oplus \\ldots \\oplus a_{n, c_n} > 0$$$ holds. If there is more than one possible answer, you may output any.", "sample_inputs": ["3 2\n0 0\n0 0\n0 0", "2 3\n7 7 7\n7 7 10"], "sample_outputs": ["NIE", "TAK\n1 3"], "notes": "NoteIn the first example, all the numbers in the matrix are $$$0$$$, so it is impossible to select one number in each row of the table so that their bitwise exclusive OR is strictly greater than zero.In the second example, the selected numbers are $$$7$$$ (the first number in the first line) and $$$10$$$ (the third number in the second line), $$$7 \\oplus 10 = 13$$$, $$$13$$$ is more than $$$0$$$, so the answer is found."}, "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.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 m = nm(N, M)\n val m2 = m.clone()\n REP(N) { i =>\n m2(i) = m(i).distinct.take(2)\n }\n\n def dfs(i: Int, x: Int): ArrayBuffer[Int] = {\n if (i == N) {\n return if (x == 0) null else ArrayBuffer()\n }\n REP(m2(i).length) { j =>\n val ans = dfs(i + 1, x ^ m2(i)(j))\n if (ans != null) {\n ans += m(i).indexWhere(_ == m2(i)(j))\n return ans\n }\n }\n null\n }\n\n val ans = dfs(0, 0)\n if (ans == null) {\n out.println(\"NIE\")\n } else {\n out.println(\"TAK\")\n out.println(ans.reverse.map(_+1).mkString(\" \"))\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[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": "3efc451a0fd5b67d58812eff774b3c6a"} {"nl": {"description": "You've got an array, consisting of n integers a1,\u2009a2,\u2009...,\u2009an. Also, you've got m queries, the i-th query is described by two integers li,\u2009ri. Numbers li,\u2009ri define a subsegment of the original array, that is, the sequence of numbers ali,\u2009ali\u2009+\u20091,\u2009ali\u2009+\u20092,\u2009...,\u2009ari. For each query you should check whether the corresponding segment is a ladder. A ladder is a sequence of integers b1,\u2009b2,\u2009...,\u2009bk, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1\u2009\u2264\u2009x\u2009\u2264\u2009k), that the following inequation fulfills: b1\u2009\u2264\u2009b2\u2009\u2264\u2009...\u2009\u2264\u2009bx\u2009\u2265\u2009bx\u2009+\u20091\u2009\u2265\u2009bx\u2009+\u20092...\u2009\u2265\u2009bk. Note that the non-decreasing and the non-increasing sequences are also considered ladders.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of array elements and the number of queries. The second line contains the sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where number ai stands for the i-th array element. The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) \u2014 the boundaries of the subsegment of the initial array. The numbers in the lines are separated by single spaces.", "output_spec": "Print m lines, in the i-th line print word \"Yes\" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word \"No\" (without the quotes) otherwise. ", "sample_inputs": ["8 6\n1 2 1 3 3 5 2 1\n1 3\n2 3\n2 4\n8 8\n1 4\n5 8"], "sample_outputs": ["Yes\nYes\nNo\nYes\nNo\nYes"], "notes": null}, "positive_code": [{"source_code": "object probC extends App{\n var Array(m,n) = readLine().split(\" \") map (_.toInt)\n var vals = readLine() split \" \" map (_.toInt)\n var inc: Array[Int] = new Array[Int](m)\n var dec: Array[Int] = new Array[Int](m) \n inc(m-1)=m-1\n dec(m-1)=m-1\n for(i <- m-2 to 0 by -1){\n if(vals(i+1)vals(i)){\n\t\t\tinc(i)=inc(i+1);\n\t\t\tdec(i)=i;\n\t\t}\n\t\telse{\n\t\t\tdec(i)=dec(i+1);\n\t\t\tinc(i)=inc(i+1);\n\t\t}\n } \n for(i <- 1 to n){\n var Array(a,b) = readLine().split(\" \") map (_.toInt)\n a-=1\n b-=1\n if(dec(inc(a))>=b) println(\"Yes\")\n else println(\"No\")\n }\n}"}], "negative_code": [], "src_uid": "c39db222c42d8e85dee5686088dc3dac"} {"nl": {"description": "Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n\u2009>\u20091) is an n\u2009\u00d7\u2009n matrix with a diamond inscribed into it.You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character \"D\". All other cells of the matrix should be represented by character \"*\". Look at the examples to understand what you need to draw.", "input_spec": "The only line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009101; n is odd). ", "output_spec": "Output a crystal of size n.", "sample_inputs": ["3", "5", "7"], "sample_outputs": ["*D*\nDDD\n*D*", "**D**\n*DDD*\nDDDDD\n*DDD*\n**D**", "***D***\n**DDD**\n*DDDDD*\nDDDDDDD\n*DDDDD*\n**DDD**\n***D***"], "notes": null}, "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._\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}"}, {"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"} {"nl": {"description": "You are given a sequence of $$$n$$$ integers $$$a_1, \\, a_2, \\, \\dots, \\, a_n$$$.Does there exist a sequence of $$$n$$$ integers $$$b_1, \\, b_2, \\, \\dots, \\, b_n$$$ such that the following property holds? For each $$$1 \\le i \\le n$$$, there exist two (not necessarily distinct) indices $$$j$$$ and $$$k$$$ ($$$1 \\le j, \\, k \\le n$$$) such that $$$a_i = b_j - b_k$$$. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 20$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10$$$). The second line of each test case contains the $$$n$$$ integers $$$a_1, \\, \\dots, \\, a_n$$$ ($$$-10^5 \\le a_i \\le 10^5$$$).", "output_spec": "For each test case, output a line containing YES if a sequence $$$b_1, \\, \\dots, \\, b_n$$$ satisfying the required property exists, and NO otherwise.", "sample_inputs": ["5\n5\n4 -7 -1 5 10\n1\n0\n3\n1 10 100\n4\n-3 2 10 2\n9\n25 -171 250 174 152 242 100 -205 -258"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES"], "notes": "NoteIn the first test case, the sequence $$$b = [-9, \\, 2, \\, 1, \\, 3, \\, -2]$$$ satisfies the property. Indeed, the following holds: $$$a_1 = 4 = 2 - (-2) = b_2 - b_5$$$; $$$a_2 = -7 = -9 - (-2) = b_1 - b_5$$$; $$$a_3 = -1 = 1 - 2 = b_3 - b_2$$$; $$$a_4 = 5 = 3 - (-2) = b_4 - b_5$$$; $$$a_5 = 10 = 1 - (-9) = b_3 - b_1$$$. In the second test case, it is sufficient to choose $$$b = [0]$$$, since $$$a_1 = 0 = 0 - 0 = b_1 - b_1$$$.In the third test case, it is possible to show that no sequence $$$b$$$ of length $$$3$$$ satisfies the property."}, "positive_code": [{"source_code": "object D1552 {\n import scala.collection.mutable.ArrayBuffer\n\n /** TODO: Check! */\n private val multipleTests: Boolean = true\n\n case class Sum(sum: Int, ok: Boolean)\n\n def run(testNum: Int): Unit = {\n val n = int()\n val a = Seq.fill(n)(int())\n var sums = ArrayBuffer.fill(1)(Sum(0, ok = false))\n a.foreach { a =>\n val newSums = new ArrayBuffer[Sum]()\n sums.foreach { case Sum(sum, ok) =>\n newSums += Sum(sum, ok)\n newSums += Sum(sum + a, ok = true)\n newSums += Sum(sum - a, ok = true)\n }\n sums = newSums\n }\n val found = sums.find { case Sum(sum, ok) => sum == 0 && ok }\n println(if (found.isDefined) \"YES\" else \"NO\")\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"}], "negative_code": [], "src_uid": "e8e32f179080f9d12bb1e4df303ea124"} {"nl": {"description": "Vasya came up with a password to register for EatForces \u2014 a string $$$s$$$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords \"abaCABA12\", \"Z7q\" and \"3R24m\" are valid, and the passwords \"qwerty\", \"qwerty12345\" and \"Password\" are not. A substring of string $$$s$$$ is a string $$$x = s_l s_{l + 1} \\dots s_{l + len - 1} (1 \\le l \\le |s|, 0 \\le len \\le |s| - l + 1)$$$. $$$len$$$ is the length of the substring. Note that the empty string is also considered a substring of $$$s$$$, it has the length $$$0$$$.Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of $$$s$$$ should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of testcases. Each of the next $$$T$$$ lines contains the initial password $$$s~(3 \\le |s| \\le 100)$$$, consisting of lowercase and uppercase Latin letters and digits. Only $$$T = 1$$$ is allowed for hacks.", "output_spec": "For each testcase print a renewed password, which corresponds to given conditions. The length of the replaced substring is calculated as following: write down all the changed positions. If there are none, then the length is $$$0$$$. Otherwise the length is the difference between the first and the last changed position plus one. For example, the length of the changed substring between the passwords \"abcdef\" $$$\\rightarrow$$$ \"a7cdEf\" is $$$4$$$, because the changed positions are $$$2$$$ and $$$5$$$, thus $$$(5 - 2) + 1 = 4$$$. It is guaranteed that such a password always exists. If there are several suitable passwords \u2014 output any of them.", "sample_inputs": ["2\nabcDCE\nhtQw27"], "sample_outputs": ["abcD4E\nhtQw27"], "notes": "NoteIn the first example Vasya's password lacks a digit, he replaces substring \"C\" with \"4\" and gets password \"abcD4E\". That means, he changed the substring of length 1.In the second example Vasya's password is ok from the beginning, and nothing has to be changed. That is the same as replacing the empty substring with another empty substring (length 0)."}, "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\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}"}, {"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"} {"nl": {"description": "Given a permutation $$$p$$$ of length $$$n$$$, find its subsequence $$$s_1$$$, $$$s_2$$$, $$$\\ldots$$$, $$$s_k$$$ of length at least $$$2$$$ such that: $$$|s_1-s_2|+|s_2-s_3|+\\ldots+|s_{k-1}-s_k|$$$ is as big as possible over all subsequences of $$$p$$$ with length at least $$$2$$$. Among all such subsequences, choose the one whose length, $$$k$$$, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some (possibly, zero or all) elements.A permutation of length $$$n$$$ is an array of length $$$n$$$ in which every element from $$$1$$$ to $$$n$$$ occurs exactly once.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the permutation $$$p$$$. The second line of each test case contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\\ldots$$$, $$$p_{n}$$$ ($$$1 \\le p_i \\le n$$$, $$$p_i$$$ are distinct)\u00a0\u2014 the elements of the permutation $$$p$$$. The sum of $$$n$$$ across the test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, the first line should contain the length of the found subsequence, $$$k$$$. The second line should contain $$$s_1$$$, $$$s_2$$$, $$$\\ldots$$$, $$$s_k$$$\u00a0\u2014 its elements. If multiple subsequences satisfy these conditions, you are allowed to find any of them.", "sample_inputs": ["2\n3\n3 2 1\n4\n1 3 4 2"], "sample_outputs": ["2\n3 1 \n3\n1 4 2"], "notes": "NoteIn the first test case, there are $$$4$$$ subsequences of length at least $$$2$$$: $$$[3,2]$$$ which gives us $$$|3-2|=1$$$. $$$[3,1]$$$ which gives us $$$|3-1|=2$$$. $$$[2,1]$$$ which gives us $$$|2-1|=1$$$. $$$[3,2,1]$$$ which gives us $$$|3-2|+|2-1|=2$$$. So the answer is either $$$[3,1]$$$ or $$$[3,2,1]$$$. Since we want the subsequence to be as short as possible, the answer is $$$[3,1]$$$."}, "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"}, {"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"}], "negative_code": [], "src_uid": "857de33d75daee460206079fa2c15814"} {"nl": {"description": "Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called \"chizhik\". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price $$$z$$$ chizhiks per coconut. Sasha has $$$x$$$ chizhiks, Masha has $$$y$$$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has $$$5$$$ chizhiks, Masha has $$$4$$$ chizhiks, and the price for one coconut be $$$3$$$ chizhiks. If the girls don't exchange with chizhiks, they will buy $$$1 + 1 = 2$$$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $$$6$$$ chizhiks, Masha will have $$$3$$$ chizhiks, and the girls will buy $$$2 + 1 = 3$$$ coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).", "input_spec": "The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$0 \\le x, y \\le 10^{18}$$$, $$$1 \\le z \\le 10^{18}$$$)\u00a0\u2014 the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut. ", "output_spec": "Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.", "sample_inputs": ["5 4 3", "6 8 2"], "sample_outputs": ["3 1", "7 0"], "notes": "NoteThe first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy $$$3 + 4 = 7$$$ coconuts."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val x, y, z = nl()\n val m1 = x % z\n val m2 = y % z\n val add = m1 + m2 >= z\n val cnt = x / z + y / z + (if(add) 1 else 0)\n val give = if (add) {\n min(z-m1, z-m2)\n } else {\n 0\n }\n\n out.println(s\"$cnt $give\")\n }\n}"}], "negative_code": [], "src_uid": "863a8124d46bb09b49fc88939fb5f364"} {"nl": {"description": "You know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event \"Remote Control Kaboom Show\" and stream everything online.For the preparation you arranged an arena\u00a0\u2014 an infinite 2D-field. You also bought $$$n$$$ remote controlled cars and set them up on the arena. Unfortunately, the cars you bought can only go forward without turning left, right or around. So you additionally put the cars in the direction you want them to go.To be formal, for each car $$$i$$$ ($$$1 \\le i \\le n$$$) you chose its initial position ($$$x_i, y_i$$$) and a direction vector ($$$dx_i, dy_i$$$). Moreover, each car has a constant speed $$$s_i$$$ units per second. So after car $$$i$$$ is launched, it stars moving from ($$$x_i, y_i$$$) in the direction ($$$dx_i, dy_i$$$) with constant speed $$$s_i$$$.The goal of the show is to create a car collision as fast as possible! You noted that launching every car at the beginning of the show often fails to produce any collisions at all. Thus, you plan to launch the $$$i$$$-th car at some moment $$$t_i$$$. You haven't chosen $$$t_i$$$, that's yet to be decided. Note that it's not necessary for $$$t_i$$$ to be integer and $$$t_i$$$ is allowed to be equal to $$$t_j$$$ for any $$$i, j$$$.The show starts at time $$$0$$$. The show ends when two cars $$$i$$$ and $$$j$$$ ($$$i \\ne j$$$) collide (i.\u2009e. come to the same coordinate at the same time). The duration of the show is the time between the start and the end.What's the fastest crash you can arrange by choosing all $$$t_i$$$? If it's possible to arrange a crash then print the shortest possible duration of the show. Otherwise, report that it's impossible.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 25000$$$)\u00a0\u2014 the number of cars. Each of the next $$$n$$$ lines contains five integers $$$x_i$$$, $$$y_i$$$, $$$dx_i$$$, $$$dy_i$$$, $$$s_i$$$ ($$$-10^3 \\le x_i, y_i \\le 10^3$$$; $$$1 \\le |dx_i| \\le 10^3$$$; $$$1 \\le |dy_i| \\le 10^3$$$; $$$1 \\le s_i \\le 10^3$$$)\u00a0\u2014 the initial position of the $$$i$$$-th car, its direction vector and its speed, respectively. It's guaranteed that all cars start at distinct positions (i.\u2009e. $$$(x_i, y_i) \\neq (x_j, y_j)$$$ for $$$i \\neq j$$$).", "output_spec": "Print the shortest possible duration of the show if it's possible to arrange a crash by choosing all $$$t_i$$$. Otherwise, print \"No show :(\". Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["4\n3 -1 -1 1 2\n2 3 -3 -2 10\n-4 2 1 -2 1\n-2 -2 -1 2 4", "2\n-1 1 -1 1 200\n1 1 1 5 200"], "sample_outputs": ["0.585902082262898", "No show :("], "notes": "NoteHere is the picture for the first example: The fastest cars to crash are cars $$$2$$$ and $$$4$$$. Let's launch car $$$2$$$ at $$$0$$$, car $$$4$$$ at about $$$0.096762$$$ and cars $$$1$$$ and $$$3$$$ at arbitrary time. That way cars $$$2$$$ and $$$4$$$ will crash into each other at about $$$0.585902$$$. So here's what it looks like at the moment of the collision: Here's the picture for the second example: "}, "positive_code": [{"source_code": "//package codeforces.contests._1359\n\n\n/*\nhttps://codeforces.com/contest/1359/problem/F\n */\nobject _6 {\n\n import scala.collection.mutable\n\n val EPS: Double = 1E-9;\n\n case class Kinematics private(x: Int, y: Int, xDir: Double, yDir: Double, s: Int) {\n\n def lineSegment(time: Double): LineSegment = {\n LineSegment(x, y, x + s * xDir * time, y + s * yDir * time)\n }\n }\n\n object Kinematics {\n def apply(x: Int, y: Int, dx: Int, dy: Int, s: Int): Kinematics = {\n val hypot = math.hypot(dx, dy)\n val xDir: Double = dx / hypot\n val yDir: Double = dy / hypot\n new Kinematics(x, y, xDir, yDir, s)\n }\n }\n\n case class LineSegment(x1: Double, y1: Double, x2: Double, y2: Double) {\n def getY(x: Double): Double = if (math.abs(x1 - x2) < EPS) y2 else y1 + (x - x1) * (y2 - y1) / (x2 - x1)\n\n def intersect(that: LineSegment): Boolean = {\n val x3 = that.x1\n val y3 = that.y1\n val x4 = that.x2\n val y4 = that.y2\n\n intersectOneD(x1, x2, x3, x4) && intersectOneD(y1, y2, y3, y4) &&\n orientation(x1, y1, x2, y2, x3, y3) * orientation(x1, y1, x2, y2, x4, y4) <= 0 &&\n orientation(x3, y3, x4, y4, x1, y1) * orientation(x3, y3, x4, y4, x2, y2) <= 0\n }\n\n private def intersectOneD(a: Double, b: Double, c: Double, d: Double): Boolean = {\n val aa = a min b\n val bb = a max b\n val cc = c min d\n val dd = c max d\n\n aa.max(cc) <= bb.min(dd) + EPS\n }\n\n private def orientation(x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double): Double = {\n val value = (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1)\n\n if (math.abs(value) < EPS) 0 else math.signum(value) // 0 => collinear, 1 => clockwise, -1 => anti-clockwise\n }\n }\n\n object LineSegment {\n implicit val ordering: Ordering[LineSegment] = (l1: LineSegment, l2: LineSegment) => {\n val x = (l1.x1 min l1.x2) max (l2.x1 min l2.x2)\n val o = l1.getY(x) - l2.getY(x)\n\n if (math.abs(o) < EPS) 0 else if (o < 0) -1 else 1\n }\n }\n\n def doIntersect(kinematics: Array[Kinematics], t: Double): Boolean = {\n val lines: Array[LineSegment] = kinematics.map(_.lineSegment(t))\n\n val abscissas: mutable.TreeSet[(Double, Int, Int)] = mutable.TreeSet.empty[(Double, Int, Int)]\n lines.indices.foreach { i =>\n val lineSegment = lines(i)\n abscissas += ((lineSegment.x1 min lineSegment.x2, 1, i))\n abscissas += ((lineSegment.x1 max lineSegment.x2, 2, i))\n }\n\n val ordinates = mutable.TreeSet.empty[LineSegment]\n\n // line should exist\n def next(l: LineSegment): Option[LineSegment] = {\n val itr = ordinates.iteratorFrom(l)\n itr.next()\n if (itr.hasNext) Some(itr.next()) else None\n }\n\n // line should exist\n def prev(l: LineSegment): Option[LineSegment] = {\n ordinates.until(l).lastOption\n }\n\n abscissas.iterator.exists { case (_, event, i) =>\n val line = lines(i)\n event match {\n case 1 =>\n ordinates(line) || {\n ordinates += line\n val p = prev(line).exists(_.intersect(line))\n val n = next(line).exists(_.intersect(line))\n p || n\n }\n case 2 =>\n val ans = (for {\n p <- prev(line)\n n <- next(line)\n } yield p intersect n).getOrElse(false)\n ordinates -= line\n ans\n }\n }\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val kinematics = {\n val arr = new Array[Kinematics](n)\n (0 until n).foreach { i =>\n val input = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(i) = Kinematics(input(0), input(1), input(2), input(3), input(4))\n }\n arr\n }\n\n val ERROR = 1e-7\n\n @scala.annotation.tailrec\n def find(start: Double, end: Double): Double = {\n val t = start + (end - start) / 2\n\n if (math.abs(start - end) <= ERROR || start == t || t == end)\n t\n else if (doIntersect(kinematics, t)) {\n // println(s\"[$start] $t $end \")\n find(start, t)\n }\n else {\n // println(s\"$start $t [$end]\")\n find(t, end)\n }\n }\n\n val dMax = 8e9 + 7\n\n println {\n if (doIntersect(kinematics, dMax))\n find(0.0, dMax)\n else\n \"No show :(\"\n }\n\n }\n}\n"}], "negative_code": [{"source_code": "//package codeforces.contests._1359\n\n\n/*\nhttps://codeforces.com/contest/1359/problem/F\n */\nobject _6 {\n\n import scala.collection.mutable\n\n val EPS: Double = 1E-9;\n\n case class Kinematics private(x: Int, y: Int, xDir: Double, yDir: Double, s: Int) {\n\n def lineSegment(time: Double): LineSegment = {\n LineSegment(x, y, x + s * xDir * time, y + s * yDir * time)\n }\n }\n\n object Kinematics {\n def apply(x: Int, y: Int, dx: Int, dy: Int, s: Int): Kinematics = {\n val hypot = math.hypot(dx, dy)\n val xDir: Double = dx / hypot\n val yDir: Double = dy / hypot\n new Kinematics(x, y, xDir, yDir, s)\n }\n }\n\n case class LineSegment(x1: Double, y1: Double, x2: Double, y2: Double) {\n def getY(x: Double): Double = if (math.abs(x1 - x2) < EPS) y2 else y1 + (x - x1) * (y2 - y1) / (x2 - x1)\n\n def intersect(that: LineSegment): Boolean = {\n val x3 = that.x1\n val y3 = that.y1\n val x4 = that.x2\n val y4 = that.y2\n\n intersectOneD(x1, x2, x3, x4) && intersectOneD(y1, y2, y3, y4) &&\n orientation(x1, y1, x2, y2, x3, y3) * orientation(x1, y1, x2, y2, x4, y4) <= 0 &&\n orientation(x3, y3, x4, y4, x1, y1) * orientation(x3, y3, x4, y4, x2, y2) <= 0\n }\n\n private def intersectOneD(a: Double, b: Double, c: Double, d: Double): Boolean = {\n val aa = a min b\n val bb = a max b\n val cc = c min d\n val dd = c max d\n\n aa.max(cc) <= bb.min(dd) + EPS\n }\n\n private def orientation(x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double): Double = {\n val value = (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1)\n\n if (math.abs(value) < EPS) 0 else math.signum(value) // 0 => collinear, 1 => clockwise, -1 => anti-clockwise\n }\n }\n\n object LineSegment {\n implicit val ordering: Ordering[LineSegment] = (l1: LineSegment, l2: LineSegment) => {\n val x = (l1.x1 min l1.x2) max (l2.x1 min l2.x2)\n val o = l1.getY(x) - l2.getY(x)\n\n if (math.abs(o) < EPS) 0 else if (o < 0) -1 else 1\n }\n }\n\n def doIntersect(kinematics: Array[Kinematics], t: Double): Boolean = {\n val lines: Array[LineSegment] = kinematics.map(_.lineSegment(t))\n\n val abscissas: mutable.TreeSet[(Double, Int, Int)] = mutable.TreeSet.empty[(Double, Int, Int)]\n lines.indices.foreach { i =>\n val lineSegment = lines(i)\n abscissas += ((lineSegment.x1 min lineSegment.x2, 1, i))\n abscissas += ((lineSegment.x1 max lineSegment.x2, 2, i))\n }\n\n val ordinates = mutable.TreeSet.empty[LineSegment]\n\n // line should exist\n def next(l: LineSegment): Option[LineSegment] = {\n val itr = ordinates.iteratorFrom(l)\n itr.next()\n if (itr.hasNext) Some(itr.next()) else None\n }\n\n // line should exist\n def prev(l: LineSegment): Option[LineSegment] = {\n ordinates.until(l).lastOption\n }\n\n abscissas.iterator.exists { case (_, event, i) =>\n val line = lines(i)\n event match {\n case 1 =>\n ordinates(line) || {\n ordinates += line\n val p = prev(line).exists(_.intersect(line))\n val n = next(line).exists(_.intersect(line))\n p || n\n }\n case 2 =>\n val ans = (for {\n p <- prev(line)\n n <- next(line)\n } yield p intersect n).getOrElse(false)\n ordinates -= line\n ans\n }\n }\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val kinematics = {\n val arr = new Array[Kinematics](n)\n (0 until n).foreach { i =>\n val input = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(i) = Kinematics(input(0), input(1), input(2), input(3), input(4))\n }\n arr\n }\n\n val ERROR = 1e-9\n\n @scala.annotation.tailrec\n def find(start: Double, end: Double): Double = {\n val t = start + (end - start) / 2\n\n if (math.abs(start - end) <= ERROR)\n t\n else if (doIntersect(kinematics, t)) {\n println(s\"[$start] $t $end \")\n find(start, t)\n }\n else {\n println(s\"$start $t [$end]\")\n find(t, end)\n }\n }\n\n val dMax = 8e9 + 7\n\n println {\n if (doIntersect(kinematics, dMax))\n find(0.0, dMax)\n else\n \"No show :(\"\n }\n\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\n\n/*\nhttps://codeforces.com/contest/1359/problem/F\n */\nobject _6 {\n\n import scala.collection.mutable\n\n case class Kinematics private(x: Int, y: Int, xDir: Double, yDir: Double, s: Int) {\n\n def lineSegment(time: Double): LineSegment = {\n LineSegment(x, y, x + s * xDir * time, y + s * yDir * time)\n }\n }\n\n object Kinematics {\n def apply(x: Int, y: Int, dx: Int, dy: Int, s: Int): Kinematics = {\n val hypot = math.hypot(dx, dy)\n val xDir: Double = dx / hypot\n val yDir: Double = dy / hypot\n new Kinematics(x, y, xDir, yDir, s)\n }\n }\n\n case class LineSegment(x1: Double, y1: Double, x2: Double, y2: Double) {\n def getY(x: Double): Double = y1 + (x - x1) * (y2 - y1) / (x2 - x1)\n\n def intersect(that: LineSegment): Boolean = {\n val x3 = that.x1\n val y3 = that.y1\n val x4 = that.x2\n val y4 = that.y2\n\n intersectOneD(x1, x2, x3, x4) && intersectOneD(y1, y2, y3, y4) &&\n orientation(x1, y1, x2, y2, x3, y3) * orientation(x1, y1, x2, y2, x4, y4) <= 0 &&\n orientation(x3, y3, x4, y4, x1, y1) * orientation(x3, y3, x4, y4, x2, y2) <= 0\n }\n\n private def intersectOneD(a: Double, b: Double, c: Double, d: Double): Boolean = {\n val aa = a min b\n val bb = a max b\n val cc = c min d\n val dd = c max d\n\n aa.max(cc) <= bb.min(dd)\n }\n\n private def orientation(x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double): Double = {\n val value = (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1)\n math.signum(value) // 0 => collinear, 1 => clockwise, -1 => anti-clockwise\n }\n }\n\n object LineSegment {\n implicit val ordering: Ordering[LineSegment] = (l1: LineSegment, l2: LineSegment) => {\n val x = (l1.x1 min l1.x2) max (l2.x1 min l2.x2)\n val o = l1.getY(x) - l2.getY(x)\n\n if (o < 0) -1 else if (o > 0) 1 else 0\n }\n }\n\n def doIntersect(lines: Array[LineSegment]): Boolean = {\n val abscissas: mutable.TreeSet[(Double, Int, Int)] = mutable.TreeSet.empty[(Double, Int, Int)]\n lines.indices.foreach { i =>\n val lineSegment = lines(i)\n abscissas += ((lineSegment.x1 min lineSegment.x2, 1, i))\n abscissas += ((lineSegment.x1 max lineSegment.x2, 2, i))\n }\n\n val ordinates = mutable.TreeSet.empty[LineSegment]\n\n // line should exist\n def next(l: LineSegment): Option[LineSegment] = {\n val itr = ordinates.iteratorFrom(l)\n if (itr.hasNext) Some(itr.next()) else None\n }\n\n // line should exist\n def prev(l: LineSegment): Option[LineSegment] = {\n ordinates.until(l).lastOption\n }\n\n abscissas.iterator.exists { case (_, event, i) =>\n val line = lines(i)\n event match {\n case 1 =>\n ordinates(line) || {\n ordinates += line\n prev(line).exists(_.intersect(line)) && next(line).exists(_.intersect(line))\n }\n case 2 =>\n val ans = (for {\n p <- prev(line)\n n <- next(line)\n } yield p intersect n).getOrElse(false)\n ordinates -= line\n ans\n }\n }\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val kinematics = {\n val arr = new Array[Kinematics](n)\n (0 until n).foreach { i =>\n val input = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(i) = Kinematics(input(0), input(1), input(2), input(3), input(4))\n }\n arr\n }\n\n val ERROR = 1e-7\n\n @scala.annotation.tailrec\n def find(start: Double, end: Double): Double = {\n val t = (start + end) / 2\n\n if (math.abs(start - t) <= ERROR)\n start\n else if (doIntersect(kinematics.map(_.lineSegment(t))))\n find(start, t)\n else\n find(t + ERROR, end)\n }\n\n val dMax = 8e9 + 7\n\n println {\n if (doIntersect(kinematics.map(_.lineSegment(dMax))))\n find(0.0, 8e9 + 7)\n else\n \"No show :(\"\n }\n\n }\n}\n"}, {"source_code": "//package codeforces.contests._1359\n\n\n/*\nhttps://codeforces.com/contest/1359/problem/F\n */\nobject _6 {\n\n import scala.collection.mutable\n\n case class Kinematics private(x: Int, y: Int, xDir: Double, yDir: Double, s: Int) {\n\n def lineSegment(time: Double): LineSegment = {\n LineSegment(x, y, x + s * xDir * time, y + s * yDir * time)\n }\n }\n\n object Kinematics {\n def apply(x: Int, y: Int, dx: Int, dy: Int, s: Int): Kinematics = {\n val hypot = math.hypot(dx, dy)\n val xDir: Double = dx / hypot\n val yDir: Double = dy / hypot\n new Kinematics(x, y, xDir, yDir, s)\n }\n }\n\n case class LineSegment(x1: Double, y1: Double, x2: Double, y2: Double) {\n def getY(x: Double): Double = y1 + (x - x1) * (y2 - y1) / (x2 - x1)\n\n def intersect(that: LineSegment): Boolean = {\n val x3 = that.x1\n val y3 = that.y1\n val x4 = that.x2\n val y4 = that.y2\n\n intersectOneD(x1, x2, x3, x4) && intersectOneD(y1, y2, y3, y4) &&\n orientation(x1, y1, x2, y2, x3, y3) * orientation(x1, y1, x2, y2, x4, y4) <= 0 &&\n orientation(x3, y3, x4, y4, x1, y1) * orientation(x3, y3, x4, y4, x2, y2) <= 0\n }\n\n private def intersectOneD(a: Double, b: Double, c: Double, d: Double): Boolean = {\n val aa = a min b\n val bb = a max b\n val cc = c min d\n val dd = c max d\n\n aa.max(cc) <= bb.min(dd)\n }\n\n private def orientation(x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double): Double = {\n val value = (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1)\n math.signum(value) // 0 => collinear, 1 => clockwise, -1 => anti-clockwise\n }\n }\n\n object LineSegment {\n implicit val ordering: Ordering[LineSegment] = (l1: LineSegment, l2: LineSegment) => {\n val x = (l1.x1 min l1.x2) max (l2.x1 min l2.x2)\n val o = l1.getY(x) - l2.getY(x)\n\n if (o < 0) -1 else if (o > 0) 1 else 0\n }\n }\n\n def doIntersect(lines: Array[LineSegment]): Boolean = {\n val abscissas: mutable.TreeSet[(Double, Int, Int)] = mutable.TreeSet.empty[(Double, Int, Int)]\n lines.indices.foreach { i =>\n val lineSegment = lines(i)\n abscissas += ((lineSegment.x1 min lineSegment.x2, 1, i))\n abscissas += ((lineSegment.x1 max lineSegment.x2, 2, i))\n }\n\n val ordinates = mutable.TreeSet.empty[LineSegment]\n\n // line should exist\n def next(l: LineSegment): Option[LineSegment] = {\n val itr = ordinates.iteratorFrom(l)\n itr.next()\n if (itr.hasNext) Some(itr.next()) else None\n }\n\n // line should exist\n def prev(l: LineSegment): Option[LineSegment] = {\n ordinates.until(l).lastOption\n }\n\n abscissas.iterator.exists { case (_, event, i) =>\n val line = lines(i)\n event match {\n case 1 =>\n ordinates(line) || {\n ordinates += line\n val p = prev(line).exists(_.intersect(line))\n val n = next(line).exists(_.intersect(line))\n p || n\n }\n case 2 =>\n val ans = (for {\n p <- prev(line)\n n <- next(line)\n } yield p intersect n).getOrElse(false)\n ordinates -= line\n ans\n }\n }\n }\n\n\n def main(args: Array[String]): Unit = {\n val n = io.StdIn.readInt()\n val kinematics = {\n val arr = new Array[Kinematics](n)\n (0 until n).foreach { i =>\n val input = io.StdIn.readLine.split(\" \").map(_.toInt)\n arr(i) = Kinematics(input(0), input(1), input(2), input(3), input(4))\n }\n arr\n }\n\n val ERROR = 1e-7\n\n @scala.annotation.tailrec\n def find(start: Double, end: Double): Double = {\n val t = (start + end) / 2\n\n if (math.abs(start - t) <= ERROR)\n start\n else if (doIntersect(kinematics.map(_.lineSegment(t))))\n find(start, t)\n else\n find(t + ERROR, end)\n }\n\n val dMax = 8e9 + 7\n\n println {\n if (doIntersect(kinematics.map(_.lineSegment(dMax))))\n find(0.0, 8e9 + 7)\n else\n \"No show :(\"\n }\n\n }\n}\n"}], "src_uid": "15a1be58932d04e3a783483cc1496c9a"} {"nl": {"description": "Andryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time? ", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of sock pairs. The second line contains 2n integers x1,\u2009x2,\u2009...,\u2009x2n (1\u2009\u2264\u2009xi\u2009\u2264\u2009n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi. It is guaranteed that Andryusha took exactly two socks of each pair.", "output_spec": "Print single integer\u00a0\u2014 the maximum number of socks that were on the table at the same time.", "sample_inputs": ["1\n1 1", "3\n2 1 1 3 2 3"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows: Initially the table was empty, he took out a sock from pair 2 and put it on the table. Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table. Socks (1,\u20092) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe. Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table. Socks (2,\u20093) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe. Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe. Thus, at most two socks were on the table at the same time."}, "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) \u21d2\n (seen - i, cnt max seen.size)\n case ((seen, cnt), i )\u21d2\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}"}, {"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"}], "negative_code": [], "src_uid": "7f98c9258f3e127a782041c421d6317b"} {"nl": {"description": "You have $$$n$$$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $$$i$$$-th student skill is denoted by an integer $$$a_i$$$ (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints: The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given): $$$[1, 2, 3]$$$, $$$[4, 4]$$$ is not a good pair of teams because sizes should be the same; $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ is not a good pair of teams because the first team should not contain students with the same skills; $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ is not a good pair of teams because the second team should contain students with the same skills; $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ is a good pair of teams; $$$[5]$$$, $$$[6]$$$ is a good pair of teams. Your task is to find the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of students. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th student. Different students can have the same skills. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$.", "sample_inputs": ["4\n7\n4 2 4 1 4 3 4\n5\n2 1 5 4 3\n1\n1\n4\n1 1 1 3"], "sample_outputs": ["3\n1\n0\n2"], "notes": "NoteIn the first test case of the example, it is possible to construct two teams of size $$$3$$$: the first team is $$$[1, 2, 4]$$$ and the second team is $$$[4, 4, 4]$$$. Note, that there are some other ways to construct two valid teams of size $$$3$$$."}, "positive_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, 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}"}, {"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"} {"nl": {"description": "On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi,\u2009j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!", "input_spec": "The first line of input contains two integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi,\u2009j (0\u2009\u2264\u2009gi,\u2009j\u2009\u2264\u2009500).", "output_spec": "If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1\u2009\u2264\u2009x\u2009\u2264\u2009n) describing a move of the form \"choose the x-th row\". col x, (1\u2009\u2264\u2009x\u2009\u2264\u2009m) describing a move of the form \"choose the x-th column\". If there are multiple optimal solutions, output any one of them.", "sample_inputs": ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"], "sample_outputs": ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"], "notes": "NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3."}, "positive_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\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, m) = readInts(2)\n\n val grid = Array.fill(n) { readInts(m) }\n\n val res = ArrayBuffer.empty[String]\n\n def solveRows() = {\n\n for (r <- 0 until n) {\n val min = grid(r).min\n if (min > 0) {\n for (c <- 0 until m) grid(r)(c) -= min\n for (_ <- 0 until min) res += s\"row ${r + 1}\"\n }\n }\n\n }\n\n def solveColumns() = {\n\n for (c <- 0 until m) {\n var min = Int.MaxValue\n for (r <- 0 until n) min = Math.min(min, grid(r)(c))\n if (min > 0) {\n for (r <- 0 until n) grid(r)(c) -= min\n for (_ <- 0 until min) res += s\"col ${c + 1}\"\n }\n }\n\n }\n\n if (n < m) {\n solveRows()\n solveColumns()\n } else {\n solveColumns()\n solveRows()\n }\n\n val solved = grid.forall(_.forall(_ == 0))\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n if (solved) {\n println(res.size)\n println(res.mkString(\"\\n\"))\n } else println(-1)\n\n Console.flush\n}\n"}], "negative_code": [{"source_code": "import scala.collection.mutable.ArrayBuffer\n\nobject A 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, m) = readInts(2)\n\n val grid = Array.fill(n) {\n readInts(m)\n }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val res = ArrayBuffer.empty[String]\n\n var changed = true\n while (changed) {\n changed = false\n\n var max, maxR, maxC = 0\n\n for (r <- 0 until n) {\n for (c <- 0 until m) {\n val g = grid(r)(c)\n if (g > max) {\n maxR = r\n maxC = c\n max = g\n }\n }\n }\n\n if (max > 0) {\n\n val mustH = grid(maxR).forall(_ == max)\n if (mustH) {\n res += s\"row ${maxR + 1}\"\n changed = true\n for (c <- 0 until m) grid(maxR)(c) -= 1\n } else {\n var mustV = true\n for (r <- 0 until n) if (grid(r)(maxC) != max) mustV = false\n if (mustV) {\n res += s\"col ${maxC + 1}\"\n changed = true\n for (r <- 0 until n) grid(r)(maxC) -= 1\n } else {\n val canH = grid(maxR).forall(_ > 0)\n if (canH) {\n res += s\"row ${maxR + 1}\"\n changed = true\n for (c <- 0 until m) grid(maxR)(c) -= 1\n } else {\n var canV = true\n for (r <- 0 until n) if (grid(r)(maxC) == 0) canV = false\n if (canV) {\n res += s\"col ${maxC + 1}\"\n changed = true\n for (r <- 0 until n) grid(r)(maxC) -= 1\n }\n }\n }\n }\n }\n\n }\n\n val solved = grid.forall(_.forall(_ == 0))\n\n if (solved) {\n println(res.size)\n println(res.mkString(\"\\n\"))\n } else println(-1)\n\n Console.flush\n}\n"}, {"source_code": "import scala.collection.mutable.ArrayBuffer\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 grid = Array.fill(n) { readInts(m) }\n\n Console.setOut(new java.io.BufferedOutputStream(Console.out))\n\n val res = ArrayBuffer.empty[String]\n\n var changed = true\n while (changed) {\n changed = false\n\n var max, maxR, maxC = 0\n\n for (r <- 0 until n) {\n for (c <- 0 until m) {\n val g = grid(r)(c)\n if (g > max) {\n maxR = r\n maxC = c\n max = g\n }\n }\n }\n\n if (max > 0) {\n\n val canH = grid(maxR).forall(_ > 0)\n if (canH) {\n res += s\"row ${maxR + 1}\"\n changed = true\n for (c <- 0 until m) grid(maxR)(c) -= 1\n } else {\n\n var canV = true\n for (r <- 0 until n) if (grid(r)(maxC) == 0) canV = false\n if (canV) {\n res += s\"col ${maxC + 1}\"\n changed = true\n for (r <- 0 until n) grid(r)(maxC) -= 1\n }\n }\n }\n\n }\n\n val solved = grid.forall(_.forall(_ == 0))\n\n if (solved) {\n println(res.size)\n println(res.mkString(\"\\n\"))\n } else println(-1)\n\n Console.flush\n}\n"}], "src_uid": "b19ab2db46484f0c9b49cf261502bf64"} {"nl": {"description": "User ainta has a permutation p1,\u2009p2,\u2009...,\u2009pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1,\u2009a2,\u2009...,\u2009an is prettier than permutation b1,\u2009b2,\u2009...,\u2009bn, if and only if there exists an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n) where a1\u2009=\u2009b1,\u2009a2\u2009=\u2009b2,\u2009...,\u2009ak\u2009-\u20091\u2009=\u2009bk\u2009-\u20091 and ak\u2009<\u2009bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n\u2009\u00d7\u2009n binary matrix A, user ainta can swap the values of pi and pj (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n, i\u2009\u2260\u2009j) if and only if Ai,\u2009j\u2009=\u20091.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300) \u2014 the size of the permutation p. The second line contains n space-separated integers p1,\u2009p2,\u2009...,\u2009pn \u2014 the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai,\u2009j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i,\u2009j where 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n, Ai,\u2009j\u2009=\u2009Aj,\u2009i holds. Also, for all integers i where 1\u2009\u2264\u2009i\u2009\u2264\u2009n, Ai,\u2009i\u2009=\u20090 holds.", "output_spec": "In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.", "sample_inputs": ["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"], "sample_outputs": ["1 2 4 3 6 7 5", "1 2 3 4 5"], "notes": "NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1,\u2009p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1,\u2009p3),\u2009(p4,\u2009p5),\u2009(p3,\u2009p4). A permutation p is a sequence of integers p1,\u2009p2,\u2009...,\u2009pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as 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 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}"}, {"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"} {"nl": {"description": "When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $$$2 \\times n$$$ grid where each row is a permutation of the numbers $$$1,2,3,\\ldots,n$$$.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $$$10^9+7$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 4 \\cdot 10^5$$$). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers $$$1,2,3,\\ldots,n$$$ and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \\cdot 10^5$$$.", "output_spec": "For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo $$$10^9+7$$$. The answer for each test case should be on a separate line.", "sample_inputs": ["2\n4\n1 4 2 3\n3 2 1 4\n8\n2 6 5 1 4 3 7 8\n3 8 7 5 1 2 4 6"], "sample_outputs": ["2\n8"], "notes": "NoteThe two possible puzzle configurations for example $$$1$$$ are: $$$[1,4,2,3]$$$ in the first row and $$$[3,2,1,4]$$$ in the second; $$$[3,2,1,4]$$$ in the first row and $$$[1,4,2,3]$$$ in the second. "}, "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n val Mod = 1000000007\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 colors = Array.fill(n + 1)(0)\r\n\r\n val adjacent = {\r\n val temp = Array.fill(n + 1)(0)\r\n (0 until n).foreach { i => temp(an(i)) = bn(i) }\r\n temp\r\n }\r\n\r\n @annotation.tailrec\r\n def dfs(ai: Int): Unit = {\r\n colors(ai) = 1\r\n val aj = adjacent(ai)\r\n if (colors(aj) == 0) dfs(aj)\r\n }\r\n\r\n val ans = (1 to n).foldLeft(1) {\r\n case (count, ai) if colors(ai) == 0 =>\r\n dfs(ai)\r\n (count << 1) % Mod\r\n case (count, _) => count\r\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 val Mod = 1000000007\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 ans = {\r\n val is = Array.fill(n)(0)\r\n val ai2i = an.zipWithIndex.toMap\r\n\r\n @annotation.tailrec\r\n def go(count: Int): Int =\r\n is.zipWithIndex.collectFirst { case (0, i) => i } match {\r\n case None => count\r\n case Some(i) =>\r\n @annotation.tailrec\r\n def path(j: Int, count: Int = 0): Int = {\r\n is(j) = 1\r\n\r\n val bj = bn(j)\r\n val k = ai2i(bj)\r\n\r\n if (i == k) count\r\n else path(k, count + 1)\r\n }\r\n\r\n go((2 * path(i)) % Mod)\r\n }\r\n\r\n go(1)\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 val Mod = 1000000007\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 ans = {\r\n val is = Array.fill(n)(0)\r\n val ai2i = an.zipWithIndex.toMap\r\n\r\n @annotation.tailrec\r\n def go(count: Int): Int =\r\n is.zipWithIndex.collectFirst { case (0, i) => i } match {\r\n case None => count\r\n case Some(i) =>\r\n @annotation.tailrec\r\n def path(j: Int, count: Int = 0): Int = {\r\n is(i) = 1\r\n\r\n val bj = bn(j)\r\n val k = ai2i(bj)\r\n\r\n if (i == k) count\r\n else path(k, count + 1)\r\n }\r\n\r\n go((2 * path(i)) % Mod)\r\n }\r\n\r\n go(1)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "src_uid": "3f1e2549d7342364b08f976fcbb7b1fa"} {"nl": {"description": "YouKn0wWho has an integer sequence $$$a_1, a_2, \\ldots, a_n$$$. He will perform the following operation until the sequence becomes empty: select an index $$$i$$$ such that $$$1 \\le i \\le |a|$$$ and $$$a_i$$$ is not divisible by $$$(i + 1)$$$, and erase this element from the sequence. Here $$$|a|$$$ is the length of sequence $$$a$$$ at the moment of operation. Note that the sequence $$$a$$$ changes and the next operation is performed on this changed sequence.For example, if $$$a=[3,5,4,5]$$$, then he can select $$$i = 2$$$, because $$$a_2 = 5$$$ is not divisible by $$$i+1 = 3$$$. After this operation the sequence is $$$[3,4,5]$$$.Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$) \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"YES\" (without quotes) if it is possible to erase the whole sequence using the aforementioned operation, print \"NO\" (without quotes) otherwise. You can print each letter in any register (upper or lower).", "sample_inputs": ["5\n3\n1 2 3\n1\n2\n2\n7 7\n10\n384836991 191890310 576823355 782177068 404011431 818008580 954291757 160449218 155374934 840594328\n8\n6 69 696 69696 696969 6969696 69696969 696969696"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteIn the first test case, YouKn0wWho can perform the following operations (the erased elements are underlined): $$$[1, \\underline{2}, 3] \\rightarrow [\\underline{1}, 3] \\rightarrow [\\underline{3}] \\rightarrow [\\,].$$$In the second test case, it is impossible to erase the sequence as $$$i$$$ can only be $$$1$$$, and when $$$i=1$$$, $$$a_1 = 2$$$ is divisible by $$$i + 1 = 2$$$."}, "positive_code": [{"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"}, {"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"}, {"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"}], "negative_code": [], "src_uid": "080f29d4e2aa5bb9ee26d882362c8cd7"} {"nl": {"description": "A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of employees. The next n lines contain the integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n or pi\u2009=\u2009-1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi\u2009\u2260\u2009i). Also, there will be no managerial cycles.", "output_spec": "Print a single integer denoting the minimum number of groups that will be formed in the party.", "sample_inputs": ["5\n-1\n1\n2\n1\n-1"], "sample_outputs": ["3"], "notes": "NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5 "}, "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": "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"}, {"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"} {"nl": {"description": "You are given $$$n$$$ arrays that can have different sizes. You also have a table with $$$w$$$ columns and $$$n$$$ rows. The $$$i$$$-th array is placed horizontally in the $$$i$$$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.You need to find the maximum sum of the integers in the $$$j$$$-th column for each $$$j$$$ from $$$1$$$ to $$$w$$$ independently. Optimal placements for columns $$$1$$$, $$$2$$$ and $$$3$$$ are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.", "input_spec": "The first line contains two integers $$$n$$$ ($$$1 \\le n \\le 10^{6}$$$) and $$$w$$$ ($$$1 \\le w \\le 10^{6}$$$)\u00a0\u2014 the number of arrays and the width of the table. Each of the next $$$n$$$ lines consists of an integer $$$l_{i}$$$ ($$$1 \\le l_{i} \\le w$$$), the length of the $$$i$$$-th array, followed by $$$l_{i}$$$ integers $$$a_{i1}, a_{i2}, \\ldots, a_{il_i}$$$ ($$$-10^{9} \\le a_{ij} \\le 10^{9}$$$)\u00a0\u2014 the elements of the array. The total length of the arrays does no exceed $$$10^{6}$$$.", "output_spec": "Print $$$w$$$ integers, the $$$i$$$-th of them should be the maximum sum for column $$$i$$$.", "sample_inputs": ["3 3\n3 2 4 8\n2 2 5\n2 6 3", "2 2\n2 7 8\n1 -8"], "sample_outputs": ["10 15 16", "7 8"], "notes": "NoteIllustration for the first example is in the statement."}, "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\u3068\u304b+7\u3068\u304b\u3059\u308b\u306a\u3089val\u306b\u3057\u308d\n @inline private def MOD = 1000000007\n\n def solve(): Unit = {\n val N, W = ni()\n val ans = Array.ofDim[Long](W + 1)\n\n // [l, r)\n def add(l: Int, r: Int, a: Int): Unit = {\n debug(s\"add($l, $r, $a)\")\n ans(l) += a\n ans(r) -= a\n }\n\n val INF = -1e9.toInt - 10\n REP(N) { _ =>\n val l = ni()\n val t = new SegmentTree(l + 2, INF)(max) // \u4e21\u30b5\u30a4\u30c9\u306b0\u3092\u8ffd\u52a0\n t.update(0, 0)\n t.update(l + 1, 0)\n REP(l) { i =>\n val a = ni()\n t.update(i + 1, a)\n }\n\n def calc1(i: Int): Int = {\n val a = max(0, i - (W - l) + 1)\n val b = min(l + 2, i + 2)\n t.query(a, b)\n }\n\n // [0, l+2)\u306e\u90e8\u5206\u304c\u3042\u308b\u304b\n if (l < W - l) {\n // [0, l)\n REP(l) { i =>\n add(i, i + 1, calc1(i))\n }\n\n // [l, w-l)\n if (l < W - l) {\n add(l, W - l, t.query(0, l + 2))\n }\n\n // [w-l, w)\n TO(W - l, W - 1) { i =>\n add(i, i + 1, calc1(i))\n }\n } else {\n REP(W) { i =>\n add(i, i + 1, calc1(i))\n }\n }\n\n debug(ans)\n }\n\n REP(W) { i =>\n ans(i + 1) += ans(i)\n }\n\n out.println(ans.take(W).mkString(\" \"))\n }\n\n class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => 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] = 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 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): Int = {\n assert(a < n && b <= n)\n\n var res: Int = 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 // \u53f3\u306e\u5b50\u4f9b\u306a\u3089\u53f3\u306e\u89aa\u306b\u79fb\u52d5\n right = (right - 1) >> 1 // \u5de6\u306e\u5b50\u4f9b\u306a\u3089\u5de6\u306e\u89aa\u306b\u79fb\u52d5\n }\n\n res\n }\n }\n}"}], "negative_code": [], "src_uid": "b731368efab76347a821de9ad6e0f443"} {"nl": {"description": "The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi.Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process: First, he will jump from island 0 to island d. After that, he will continue jumping according to the following rule. Let l be the length of the previous jump, that is, if his previous jump was from island prev to island cur, let l\u2009=\u2009cur\u2009-\u2009prev. He will perform a jump of length l\u2009-\u20091, l or l\u2009+\u20091 to the east. That is, he will jump to island (cur\u2009+\u2009l\u2009-\u20091), (cur\u2009+\u2009l) or (cur\u2009+\u2009l\u2009+\u20091) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when l\u2009=\u20091. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.", "input_spec": "The first line of the input contains two space-separated integers n and d (1\u2009\u2264\u2009n,\u2009d\u2009\u2264\u200930000), denoting the number of the gems in the Shuseki Islands and the length of the Mr. Kitayuta's first jump, respectively. The next n lines describe the location of the gems. The i-th of them (1\u2009\u2264\u2009i\u2009\u2264\u2009n) contains a integer pi (d\u2009\u2264\u2009p1\u2009\u2264\u2009p2\u2009\u2264\u2009...\u2009\u2264\u2009pn\u2009\u2264\u200930000), denoting the number of the island that contains the i-th gem.", "output_spec": "Print the maximum number of gems that Mr. Kitayuta can collect.", "sample_inputs": ["4 10\n10\n21\n27\n27", "8 8\n9\n19\n28\n36\n45\n55\n66\n78", "13 7\n8\n8\n9\n16\n17\n17\n18\n21\n23\n24\n24\n26\n30"], "sample_outputs": ["3", "6", "4"], "notes": "NoteIn the first sample, the optimal route is 0 \u2009\u2192\u2009 10 (+1 gem) \u2009\u2192\u2009 19 \u2009\u2192\u2009 27 (+2 gems) \u2009\u2192\u2009...In the second sample, the optimal route is 0 \u2009\u2192\u2009 8 \u2009\u2192\u2009 15 \u2009\u2192\u2009 21\u2009\u2192\u2009 28 (+1 gem) \u2009\u2192\u2009 36 (+1 gem) \u2009\u2192\u2009 45 (+1 gem) \u2009\u2192\u2009 55 (+1 gem) \u2009\u2192\u2009 66 (+1 gem) \u2009\u2192\u2009 78 (+1 gem) \u2009\u2192\u2009...In the third sample, the optimal route is 0 \u2009\u2192\u2009 7 \u2009\u2192\u2009 13 \u2009\u2192\u2009 18 (+1 gem) \u2009\u2192\u2009 24 (+2 gems) \u2009\u2192\u2009 30 (+1 gem) \u2009\u2192\u2009..."}, "positive_code": [{"source_code": "object Solution extends App {\n val data = scala.io.Source.stdin.getLines()\n val Array(n, d) = data.next().split(\" \").map(_.toInt)\n val M = 30001\n val nn = 250\n val gem = Array.ofDim[Int](M)\n val dp = Array.fill[Int](M, nn * 2){ -1}\n val tasks = Range(0, n).foreach{i => gem(data.next().toInt) += 1}\n var i = d\n\n def solve(i: Int, j: Int): Int = {\n val jj = j - (d - nn)\n if (i >= M) 0\n else if (dp(i)(jj) != -1) dp(i)(jj)\n else {\n dp(i)(jj) = 0\n dp(i)(jj) = gem(i) + (if (j == 1) Math.max(solve(i + j, j), solve(i + j + 1, j + 1)) else\n Math.max(solve(i + j - 1, j - 1), Math.max(solve(i + j, j), solve(i + j + 1, j + 1))))\n dp(i)(jj)\n }\n }\n\n println(solve(d, d))\n}"}], "negative_code": [], "src_uid": "20cbd67b7bfd8bb201f4113a09aae000"} {"nl": {"description": "Let $$$f(i)$$$ denote the minimum positive integer $$$x$$$ such that $$$x$$$ is not a divisor of $$$i$$$.Compute $$$\\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$. In other words, compute $$$f(1)+f(2)+\\dots+f(n)$$$ modulo $$$10^9+7$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\leq t\\leq 10^4$$$), the number of test cases. Then $$$t$$$ cases follow. The only line of each test case contains a single integer $$$n$$$ ($$$1\\leq n\\leq 10^{16}$$$).", "output_spec": "For each test case, output a single integer $$$ans$$$, where $$$ans=\\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$.", "sample_inputs": ["6\n1\n2\n3\n4\n10\n10000000000000000"], "sample_outputs": ["2\n5\n7\n10\n26\n366580019"], "notes": "NoteIn the fourth test case $$$n=4$$$, so $$$ans=f(1)+f(2)+f(3)+f(4)$$$. $$$1$$$ is a divisor of $$$1$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$1$$$. Thus, $$$f(1)=2$$$. $$$1$$$ and $$$2$$$ are divisors of $$$2$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$2$$$. Thus, $$$f(2)=3$$$. $$$1$$$ is a divisor of $$$3$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$3$$$. Thus, $$$f(3)=2$$$. $$$1$$$ and $$$2$$$ are divisors of $$$4$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$4$$$. Thus, $$$f(4)=3$$$. Therefore, $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$$$."}, "positive_code": [{"source_code": "object C extends App {\r\n import scala.io.StdIn._\r\n\r\n @annotation.tailrec\r\n def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)\r\n\r\n def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\r\n\r\n val Mod = (1e9 + 7).toLong\r\n val t = readInt()\r\n\r\n (0 until t).foreach { _ =>\r\n val n = readLong()\r\n\r\n val ans = {\r\n @annotation.tailrec\r\n def go(y: Long, lcmx: Long = 1L, result: Long = 0L): Long =\r\n if (lcmx > n) result\r\n else {\r\n val lcmy = lcm(lcmx, y)\r\n val count = n / lcmx - n / lcmy\r\n go(y + 1, lcmy, (result + y * count % Mod) % Mod)\r\n }\r\n\r\n go(2L)\r\n }\r\n\r\n println(ans)\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "2b15a299c25254f265cce106dffd6174"} {"nl": {"description": "You and your friend are participating in a TV show \"Run For Your Prize\".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend \u2014 at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x\u2009+\u20091 or x\u2009-\u20091, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of prizes. The second line contains n integers a1, a2, ..., an (2\u2009\u2264\u2009ai\u2009\u2264\u2009106\u2009-\u20091) \u2014 the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.", "output_spec": "Print one integer \u2014 the minimum number of seconds it will take to collect all prizes.", "sample_inputs": ["3\n2 3 9", "2\n2 999995"], "sample_outputs": ["8", "5"], "notes": "NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5."}, "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 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"}, {"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"} {"nl": {"description": "Tsumugi brought $$$n$$$ delicious sweets to the Light Music Club. They are numbered from $$$1$$$ to $$$n$$$, where the $$$i$$$-th sweet has a sugar concentration described by an integer $$$a_i$$$.Yui loves sweets, but she can eat at most $$$m$$$ sweets each day for health reasons.Days are $$$1$$$-indexed (numbered $$$1, 2, 3, \\ldots$$$). Eating the sweet $$$i$$$ at the $$$d$$$-th day will cause a sugar penalty of $$$(d \\cdot a_i)$$$, as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly $$$k$$$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of $$$k$$$ between $$$1$$$ and $$$n$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le m \\le n \\le 200\\ 000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 200\\ 000$$$).", "output_spec": "You have to output $$$n$$$ integers $$$x_1, x_2, \\ldots, x_n$$$ on a single line, separed by spaces, where $$$x_k$$$ is the minimum total sugar penalty Yui can get if she eats exactly $$$k$$$ sweets.", "sample_inputs": ["9 2\n6 19 3 4 4 2 6 7 8", "1 1\n7"], "sample_outputs": ["2 5 11 18 30 43 62 83 121", "7"], "notes": "NoteLet's analyze the answer for $$$k = 5$$$ in the first example. Here is one of the possible ways to eat $$$5$$$ sweets that minimize total sugar penalty: Day $$$1$$$: sweets $$$1$$$ and $$$4$$$ Day $$$2$$$: sweets $$$5$$$ and $$$3$$$ Day $$$3$$$ : sweet $$$6$$$ Total penalty is $$$1 \\cdot a_1 + 1 \\cdot a_4 + 2 \\cdot a_5 + 2 \\cdot a_3 + 3 \\cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$$$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $$$5$$$ sweets, hence $$$x_5 = 30$$$."}, "positive_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)(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"}, {"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"} {"nl": {"description": "A piece of paper contains an array of n integers a1,\u2009a2,\u2009...,\u2009an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations \u2014 choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105; 0\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009109) \u2014 the initial array. The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print two numbers \u2014 the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.", "sample_inputs": ["5 3\n6 3 4 0 2", "3 4\n5 5 5", "5 3\n3 1 2 2 1"], "sample_outputs": ["3 4", "3 5", "4 2"], "notes": "NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6,\u20094,\u20094,\u20090,\u20094, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5,\u20095,\u20095, if we increase each by one, we get 6,\u20096,\u20096. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3,\u20092,\u20092,\u20092,\u20092, where number 2 occurs 4 times."}, "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"}, {"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}"}], "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"} {"nl": {"description": "A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \\le i \\le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \\ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \\ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$1 \\le x_i \\le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \\dots, y_n$$$ ($$$1 \\le y_i \\le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.", "sample_inputs": ["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"], "sample_outputs": ["2\n0\n1\n3\n1\n3"], "notes": "NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \\ge 2+3+7$$$). Note that they do not have the option of splitting into two groups."}, "positive_code": [{"source_code": "object _1729D extends CodeForcesApp {\n override def solve() = repeat() {\n val n = nextInt()\n val xs, ys = IndexedSeq.fill(n)(nextInt())\n val debt = (xs.zip(ys)).map({case (x, y) => y - x}).sorted\n\n var i = 0\n var j = n-1\n var ans = 0\n while(j > i) {\n if (debt(i) + debt(j) >= 0) {\n j -= 1\n ans += 1\n }\n i += 1\n }\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 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": [], "src_uid": "7c8884b72dcc3c51e0696eec8d6aa8ef"} {"nl": {"description": "Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the \"free items\" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected \"free items\" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.", "input_spec": "The first line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of discount types. The second line contains m integers: q1,\u2009q2,\u2009...,\u2009qm (1\u2009\u2264\u2009qi\u2009\u2264\u2009105). The third line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of items Maxim needs. The fourth line contains n integers: a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) \u2014 the items' prices. The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["1\n2\n4\n50 50 100 100", "2\n2 3\n5\n50 50 50 50 50", "1\n1\n7\n1 1 1 1 1 1 1"], "sample_outputs": ["200", "150", "3"], "notes": "NoteIn the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150."}, "positive_code": [{"source_code": "import scala.io.Source\n\nobject Solution extends App {\n val in = Source.stdin.getLines()\n in.next()\n val q = in.next().split(' ').map(_.toInt).min\n in.next()\n val data = in.next().split(' ').map(_.toInt).sorted.reverse\n println(data.grouped(q + 2).map(_.take(q).sum).sum)\n}"}], "negative_code": [], "src_uid": "08803b63ae803e4a76afe7258a4004aa"} {"nl": {"description": "Polycarp has prepared $$$n$$$ competitive programming problems. The topic of the $$$i$$$-th problem is $$$a_i$$$, and some problems' topics may coincide.Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that: number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems; the total number of problems in all the contests should be maximized. Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of problems Polycarp has prepared. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) where $$$a_i$$$ is the topic of the $$$i$$$-th problem.", "output_spec": "Print one integer \u2014 the maximum number of problems in the set of thematic contests.", "sample_inputs": ["18\n2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10", "10\n6 6 6 3 6 1000000000 3 3 6 6", "3\n1337 1337 1337"], "sample_outputs": ["14", "9", "3"], "notes": "NoteIn the first example the optimal sequence of contests is: $$$2$$$ problems of the topic $$$1$$$, $$$4$$$ problems of the topic $$$2$$$, $$$8$$$ problems of the topic $$$10$$$.In the second example the optimal sequence of contests is: $$$3$$$ problems of the topic $$$3$$$, $$$6$$$ problems of the topic $$$6$$$.In the third example you can take all the problems with the topic $$$1337$$$ (the number of such problems is $$$3$$$ so the answer is $$$3$$$) and host a single contest."}, "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 = mutable.Map[Int, Int]().withDefaultValue(0)\n\n rep(N) { i =>\n val a = A(i)\n C(a) += 1\n }\n\n val V = C.values.toArray\n radixSort(V)\n\n // 2^30\u306f\u306a\u3044\n val ans = map(min(V.length, 30), 1) { k =>\n val t = V.takeRight(k)\n rep(k) { i =>\n t(i) /= 1 << i\n }\n val x = t.min\n x.toLong * ((1 << k) - 1)\n }.max\n\n out.println(ans)\n }\n\n /**\n * \u6b63\u306e\u5024\u306e\u307f\u306e\u3068\u304d\u3060\u3051\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, offset: Int = 0)(f: Int => 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": "7b12845f668e28b7f18019d5ab5eaec7"} {"nl": {"description": "You've got an n\u2009\u00d7\u2009m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500) \u2014 the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers \u2014 the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.", "output_spec": "Print a single integer \u2014 the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.", "sample_inputs": ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"], "sample_outputs": ["1", "3", "0"], "notes": "NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. "}, "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 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"}, {"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"}, {"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"}], "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"} {"nl": {"description": "A string $$$s$$$ of length $$$n$$$ ($$$1 \\le n \\le 26$$$) is called alphabetical if it can be obtained using the following algorithm: first, write an empty string to $$$s$$$ (i.e. perform the assignment $$$s$$$\u00a0:= \"\"); then perform the next step $$$n$$$ times; at the $$$i$$$-th step take $$$i$$$-th lowercase letter of the Latin alphabet and write it either to the left of the string $$$s$$$ or to the right of the string $$$s$$$ (i.e. perform the assignment $$$s$$$\u00a0:=\u00a0$$$c+s$$$ or $$$s$$$\u00a0:=\u00a0$$$s+c$$$, where $$$c$$$ is the $$$i$$$-th letter of the Latin alphabet). In other words, iterate over the $$$n$$$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $$$s$$$ or append a letter to the right of the string $$$s$$$. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: \"a\", \"ba\", \"ab\", \"bac\" and \"ihfcbadeg\". The following strings are not alphabetical: \"z\", \"aa\", \"ca\", \"acb\", \"xyz\" and \"ddcba\".From the given string, determine if it is alphabetical.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case is written on a separate line that contains one string $$$s$$$. String $$$s$$$ consists of lowercase letters of the Latin alphabet and has a length between $$$1$$$ and $$$26$$$, inclusive.", "output_spec": "Output $$$t$$$ lines, each of them must contain the answer to the corresponding test case. Output YES if the given string $$$s$$$ is alphabetical and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).", "sample_inputs": ["11\na\nba\nab\nbac\nihfcbadeg\nz\naa\nca\nacb\nxyz\nddcba"], "sample_outputs": ["YES\nYES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO\nNO"], "notes": "NoteThe example contains test cases from the main part of the condition."}, "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 s = readLine()\r\n val n = s.length\r\n\r\n def go(i: Int, j: Int): Boolean =\r\n if (i == 0 && j == n - 1) true\r\n else if (i < 0 || j > n - 1) false\r\n else {\r\n val c = s(i) max s(j)\r\n\r\n if (i > 0 && s(i - 1) == c + 1) go(i - 1, j)\r\n else if (j < n - 1 && s(j + 1) == c + 1) go(i, j + 1)\r\n else false\r\n }\r\n\r\n val i = s.indexWhere(_ == 'a')\r\n\r\n go(i, i) match {\r\n case true => println(\"yes\")\r\n case _ => println(\"no\")\r\n }\r\n\r\n }\r\n}\r\n"}], "negative_code": [], "src_uid": "801bf7c73c44c68eaa61c714d5aedf50"}