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, yi).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 - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), 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.

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.

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.

NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and  for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

import java.io._
import java.util.Scanner

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elementToCount = mutable.HashMap.empty[(Int, Int), Int]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        val xx = forX.get(x)
        forX.put(x, xx.getOrElse(0) + 1)

        val yy = forY.get(y)
        forY.put(y, yy.getOrElse(0) + 1)

        val zz = elementToCount.get((x, y))
        elementToCount.put((x, y), zz.getOrElse(0) + 1)
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- elementToCount) {
        result -= (el._2.toLong * (el._2.toLong - 1L)) / 2L
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2.toLong * (el._2.toLong - 1L)) / 2L
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import java.io._
import java.util._

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val d = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      d(i) = (nextInt, nextInt)
    }
    var ans = 0L
    val byX = d.sortBy(x => x._1)
    val byY = d.sortBy(x => x._2)
    var tmp = 1L
    var prev = byX(0)._1
    for (i <- 1 until n) {
      if (byX(i)._1 == byX(i - 1)._1) {
        tmp += 1
      } else {
        prev = byX(i)._1
        ans += (tmp * (tmp - 1L)) / 2
        tmp = 1
      }
    }
    ans += (tmp * (tmp - 1L)) / 2
    tmp = 1
    prev = byY(0)._2
    for (i <- 1 until n) {
      if (byY(i)._2 == byY(i - 1)._2) {
        tmp += 1
      } else {
        prev = byY(i)._2
        ans += (tmp * (tmp - 1L)) / 2
        tmp = 1
      }
    }
    ans += (tmp * (tmp - 1L)) / 2
    val sorted = d.sortBy(r => (r._1, r._2))
    var common = 1L
    var ind = 1
    while (ind < n) {
      while (ind < n && sorted(ind)._1 == sorted(ind - 1)._1 && sorted(ind)._2 == sorted(ind - 1)._2) {
        common += 1
        ind += 1
      }
      ans -= (common * (common - 1L)) / 2
      common = 1
      ind += 1
    }
    out.println(ans)
    return 0
  }
}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _651C extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val n = in[Int]
    val xc, yc = map[Int] to 0L
    val pc = map[(Int, Int)] to 0L

    repeat(n) {
      val x, y = in[Int]
      xc(x) += 1
      yc(y) += 1
      pc(x -> y) += 1
    }

    val res = pc map {
      case ((x, y), c) =>
        val i = xc(x) - c
        val j = yc(y) - c
        //debug(x, y, c, i, j, (i + j)*c)
        (i + j)*c + (c*(c-1))
    }
    out += res.sum/2
  }

  def map[K] = new {
    def to[V](default: V): mutable.Map[K, V] = mutable.Map.empty[K, V] withDefaultValue default
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Any
  def main(args: Array[String]): Unit = {
    val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))
    solve(in, out)
    in.close()
    out.close()
  }
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)
  def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}

object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  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]))
  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]))
}

class OutputWriter(out: PrintWriter) extends AutoCloseable {
  def this(out: OutputStream) = this(new PrintWriter(out))

  var separator = " "
  private[this] var isNewLine: Boolean = true

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    isNewLine = true
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj

  override def close() = {
    out.flush()
    out.close()
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object ProblemCScala {
  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n : Int = readInt();

    val xys = for {
      i <- 1 to n
      xy = readInts()
    } yield (xy(0), xy(1))

    val xsorted = xys.sortBy(r =>  (r._1,r._2))
    val ysorted = xys.sortBy(_._2)

    //println(xsorted)

    //println(ysorted)

    var total : Long = 0
    var i : Int = 0;
    while (i < n) {
      val start : Int = i;
      var l : Long = 1
      i = i + 1
      while (i < n && xsorted(start)._1 == xsorted(i)._1) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Long = 1
      i = i + 1
      while (i < n && ysorted(start)._2 == ysorted(i)._2) {
        l = l + 1
        i = i + 1
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }

    i = 0;
    var dc : Long = 0;
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Long = 1
      i = i + 1
      while (i < n && xsorted(start) == xsorted(i)) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      dc = dc + (l-1)*l/2;
    }

    total = total - dc

    println(total)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{ _ =>
    val a = in.next().split(' ').map(_.toInt)
    (a.head, a.last)
  }
  val same = data.groupBy(i => i).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum
  val vertical = data.groupBy(i => i._2).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum
  val horizontal = data.groupBy(i => i._1).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum
  println(vertical + horizontal - same)
}

import java.io._
import java.util.StringTokenizer

import scala.collection.immutable
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C345A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C345A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a: immutable.IndexedSeq[Point] = 0 until n by 1 map { _ =>
      Point(ni(), ni())
    }
    val ans = 0L
    val cntx: Long = a.groupBy(_.x).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum
    val cnty: Long = a.groupBy(_.y).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum
    val x = a.groupBy(identity).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum
    println(cntx + cnty - x)
  }

  case class Point (
                    x: Int,
                    y: Int
                   )
}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*(10000000001L) + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*2000000001L + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[(Int, Int), Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy((a, b))
      xy((a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*(1L << 32) + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import java.io._
import java.util.Scanner

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      var answer: Long = 0
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elements = mutable.HashSet.empty[(Int, Int)]
      val doubles = mutable.HashSet.empty[(Int, Int)]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        if (!elements.contains((x, y))) {
          val xx = forX.get(x)
          forX.put(x, xx.getOrElse(0) + 1)

          val yy = forY.get(y)
          forY.put(y, yy.getOrElse(0) + 1)

          elements.+=((x, y))
        } else {
          doubles.+=((x, y))
        }
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- doubles) {
        result += forX.getOrElse(el._1, 0)
        result += (forY.getOrElse(el._2, 0) - 1)
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2 * (el._2 - 1)) / 2
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import java.io._
import java.util.Scanner

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elements = mutable.HashSet.empty[(Int, Int)]
      val doubles = mutable.HashMap.empty[(Int, Int), Int]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        if (!elements.contains((x, y))) {
          val xx = forX.get(x)
          forX.put(x, xx.getOrElse(0) + 1)

          val yy = forY.get(y)
          forY.put(y, yy.getOrElse(0) + 1)

          elements.+=((x, y))
        } else {
          val xx = doubles.get((x, y))
          doubles.put((x, y), xx.getOrElse(0) + 1)
        }
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- doubles) {
        result += forX.getOrElse(el._1._1, 0).toLong * el._2.toLong + (el._2.toLong * (el._2.toLong - 1L)) / 2L
        result += (forY.getOrElse(el._1._2, 0).toLong - 1L) * el._2.toLong
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2.toLong * (el._2.toLong - 1L)) / 2L
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import java.io._
import java.util.Scanner

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elements = mutable.HashSet.empty[(Int, Int)]
      val doubles = mutable.HashMap.empty[(Int, Int), Int]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        if (!elements.contains((x, y))) {
          val xx = forX.get(x)
          forX.put(x, xx.getOrElse(0) + 1)

          val yy = forY.get(y)
          forY.put(y, yy.getOrElse(0) + 1)

          elements.+=((x, y))
        } else {
          val xx = doubles.get((x, y))
          doubles.put((x, y), xx.getOrElse(0) + 1)
        }
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- doubles) {
        result += forX.getOrElse(el._1._1, 0) * el._2 + (el._2 * (el._2 - 1)) / 2
        result += (forY.getOrElse(el._1._2, 0) - 1) * el._2
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2 * (el._2 - 1)) / 2
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import java.io._
import java.util._

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val d = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      d(i) = (nextInt, nextInt)
    }
    var ans = 0
    val byX = d.sortBy(x => x._1)
    val byY = d.sortBy(x => x._2)
    var tmp = 1
    var prev = byX(0)._1
    for (i <- 1 until n) {
      if (byX(i)._1 == byX(i - 1)._1) {
        if (byX(i)._1 == prev) {
          tmp += 1
        } else {
          prev = byX(i)._1
          ans += (tmp * (tmp - 1)) / 2
          tmp = 1
        }
      } else {
        prev = byX(i)._1
      }
    }
    ans += (tmp * (tmp - 1)) / 2
    tmp = 1
    prev = byY(0)._2
    for (i <- 1 until n) {
      if (byY(i)._2 == byY(i - 1)._2) {
        if (byY(i)._2 == prev) {
          tmp += 1
        } else {
          prev = byY(i)._2
          ans += (tmp * (tmp - 1)) / 2
          tmp = 1
        }
      } else {
        prev = byY(i)._2
      }
    }
    ans += (tmp * (tmp - 1)) / 2
    val sorted = d.sortBy(r => (r._1, r._2))
    var common = 1
    for (i <- 1 until n) {
      if (sorted(i)._1 == sorted(i - 1)._1 && sorted(i)._2 == sorted(i - 1)._2) {
        common += 1
      }
    }
    out.println(ans - (common * (common - 1)) / 2)
    return 0
  }
}

import java.io._
import java.util._

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val d = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      d(i) = (nextInt, nextInt)
    }
    var ans = 0
    val byX = d.sortBy(x => x._1)
    val byY = d.sortBy(x => x._2)
    for (i <- 1 until n) {
      if (byX(i)._1 == byX(i - 1)._1) {
        ans += 1
      }
    }
    for (i <- 1 until n) {
      if (byY(i)._2 == byY(i - 1)._2) {
        ans += 1
      }
    }
    val sorted = d.sortBy(r => (r._1, r._2))
    var common = 0
    for (i <- 1 until n) {
      if (sorted(i)._1 == sorted(i - 1)._1 && sorted(i)._2 == sorted(i - 1)._2) {
        common += 1
      }
    }
    out.println(ans - (common * (common - 1)) / 2)
    return 0
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object ProblemCScala {
  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n : Int = readInt();

    val xys = for {
      i <- 1 to n
      xy = readInts()
    } yield (xy(0), xy(1))

    val xsorted = xys.sortBy(r =>  (r._1,r._2))
    val ysorted = xys.sortBy(_._2)

    //println(xsorted)

    //println(ysorted)

    var total : Int = 0
    var i : Int = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start)._1 == xsorted(i)._1) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && ysorted(start)._2 == ysorted(i)._2) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }

    i = 0;
    var dc : Int = 0;
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start) == xsorted(i)) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      dc = dc + (l-1)*l/2;
    }

    total = total - dc

    println(total)

  }

}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object ProblemCScala {
  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n : Int = readInt();

    val xys = for {
      i <- 1 to n
      xy = readInts()
    } yield (xy(0), xy(1))

    val xsorted = xys.sortBy(r =>  (r._1,r._2))
    val ysorted = xys.sortBy(_._2)

    //println(xsorted)

    //println(ysorted)

    var total : Long = 0
    var i : Int = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start)._1 == xsorted(i)._1) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && ysorted(start)._2 == ysorted(i)._2) {
        l = l + 1
        i = i + 1
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }

    i = 0;
    var dc : Int = 0;
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start) == xsorted(i)) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      dc = dc + (l-1)*l/2;
    }

    total = total - dc

    println(total)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{ _ =>
    val a = in.next().split(' ').map(_.toLong)
    (a.head, a.last)
  }
  val same = data.groupBy(i => i).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum
  val vertical = data.groupBy(i => i._2).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum
  val horizontal = data.groupBy(i => i._1).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum
  println(vertical + horizontal - same)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{ _ =>
    val a = in.next().split(' ').map(_.toInt)
    (a.head, a.last)
  }
  val same = data.groupBy(i => i).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum
  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
  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
  println(vertical + horizontal - same)
}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*1000000001L + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}


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$$$?

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — 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.

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).

5

abcde

c

abcde

b

x

y

aaaaaaaaaaaaaaa

a

contest

t

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.

import scala.io.StdIn.readLine

object Solution {
  def main(args: Array[String]): Unit = {

    def f(s: String, c: Char) = {
      if (s.foldLeft(List.empty[Int], 0)(
        (acc, elem) => if (elem == c) ((acc._2 :: acc._1), acc._2 + 1) else (acc._1, acc._2 + 1)
      )._1.exists(_ % 2 == 0)) "YES" else "NO"

    }

    val cases = readLine().toInt
    for (
      i <- 0 until cases;
      s = readLine;
      c = readLine().head
    ) println(f(s, c))
    //readLine.split("\\s+")

  }
}


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?

The first line of the input contains a single integer $$$n$$$ ($$$3 \leq n \leq 50$$$) — 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 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).

NoteThe following sketches show the example boards and their tilings if such tilings exist:

import java.util.Scanner

import scala.io.StdIn

object Ukulele extends App {
  val FREE = '.'
  val WALL = '#'
  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  var matrix = Array.ofDim[Char](n, n)
  for (i <- 0 until n) {
    line = new Scanner(StdIn.readLine())
    var matrixString = line.next()
    for (j <- 0 until n) {
      matrix(i)(j) = matrixString(j)
    }
  }
  for (i <- 0 until n) {
    for (j <- 0 until n) {
      if (matrix(i)(j) == FREE && j != 0 && j != n-1 && i < n-2 &&
          matrix(i+1)(j) == FREE && matrix(i+2)(j) == FREE &&
        matrix(i+1)(j-1) == FREE && matrix(i+1)(j+1) == FREE) {
        matrix(i)(j) = WALL
        matrix(i+1)(j) = WALL
        matrix(i+2)(j) = WALL
        matrix(i+1)(j-1) = WALL
        matrix(i+1)(j+1) = WALL
      }
      if (matrix(i)(j) == FREE) {
        println("NO")
        System.exit(0)
      }
    }
  }
  println("YES")
}


Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — 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 — 2 — ... — n — 1. Formally, for every 1 ≤ i < n there is a road between i-th and i + 1-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 ≤ i ≤ n,  i ≠ x, 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·cj.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 < b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?

The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.

Print the only integer — summary price of passing each of the roads in XXX.

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.

import scala.io.StdIn._

object B extends App {
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val C = readLine().split(" ").map(_.toLong)
  val Cap = readLine().split(" ").map(i => i.toInt - 1)

  val IsCapital = Array.ofDim[Boolean](n)
  Cap.foreach { i => IsCapital(i) = true }

  var sum = C.sum
  var total = 0L
  for (i <- 0 until k) {
    val j = Cap(i)
    total += C(j) * (sum - C(j))
    sum -= C(j)
  }

  for (i <- 0 until n) {
    val next = (i + 1) % n
    if (!IsCapital(i) && !IsCapital(next)) {
      total += C(i) * C(next)
    }
  }

  println(total)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toLong)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.toList.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.toList.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _703B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n, k = read[Int]
    val beauty = read[Vector, Long](n)
    val capitals = read[Set, Int](k).map(_ - 1)

    var total = beauty.sum
    var ans = 0L

    def add(u: Int, v: Int): Unit = if(!capitals(u) && !capitals(v)) {
      ans += beauty(u)*beauty(v)
      //debug(u, v, ans)
    }

    beauty.indices foreach {i =>
      add(i, (i + 1)%n)
    }

    capitals foreach {i =>
      total -= beauty(i)
      ans += beauty(i) * total
      //debug(i, ans)
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.StdIn._

object B extends App {
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val C = ("0 " + readLine()).split(" ").map(_.toLong)
  val Cap = ("0 " + readLine()).split(" ").map(_.toInt)
  val IsCapital = Array.ofDim[Boolean](n + 1)
  Cap.foreach { i =>
    IsCapital(i) = true
  }

  var capTotal = Cap.map(i => C(i)).sum
  val CapSum = Array.ofDim[Long](k + 2)
  for (i <- 1 to k) {
    CapSum(i) = capTotal
    capTotal -= C(Cap(i))
  }

  val CitiesSum = C.sum - CapSum(1)

  var totalCapitals = 0L
  for (i <- 1 to k) {
    val capitalIdx = Cap(i)
    val capitalValue = C(capitalIdx)
    val next = if (capitalIdx + 1 <= n) capitalIdx + 1 else 1
    val prev = if (capitalIdx - 1 >= 1) capitalIdx - 1 else n
    totalCapitals += capitalValue * (CitiesSum + CapSum(i + 1) - C(next) - C(prev))
  }

  var border = 0L
  for (i <- 1 to n) {
    val j = if (i + 1 <= n) i + 1 else 1
    if (!IsCapital(i) || !IsCapital(j)) border += C(i) * C(j)
  }

  println(border + totalCapitals)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toInt)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.toList.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toInt)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toInt)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.toList.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.toList.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

import scala.io.StdIn._

object B extends App {
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val C = ("0 " + readLine()).split(" ").map(_.toLong)
  val Cap = ("0 " + readLine()).split(" ").map(_.toInt)

  var capTotal = Cap.map(i => C(i)).sum
  val CapSum = Array.ofDim[Long](k + 2)
  for (i <- 1 to k) {
    CapSum(i) = capTotal
    capTotal -= C(Cap(i))
  }

  val CitiesSum = C.sum - CapSum(1)

  var totalCapitals = 0L
  for (i <- 1 to k) {
    val capitalIdx = Cap(i)
    val capitalValue = C(capitalIdx)
    val next = if (capitalIdx + 1 <= n) capitalIdx + 1 else 1
    val prev = if (capitalIdx - 1 >= 1) capitalIdx - 1 else n
    totalCapitals += capitalValue * (CitiesSum + CapSum(i + 1) - C(next) - C(prev))
  }

  var border = 0L
  for (i <- 1 to n) {
    val j = i + 1
    if (j <= n) border += C(i) * C(j)
    else border += C(i) * C(1)
  }

  println(border + totalCapitals)
}


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’s 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.

The first line contains three space-separated integers n, m, r (2 ≤ n ≤ 60, 1 ≤ m ≤ 60, 1 ≤ r ≤ 105) — 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 × n matrices of integers between 0 to 106 (inclusive) will follow — 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, ti, ki (1 ≤ si, ti ≤ n, si ≠ ti, 0 ≤ ki ≤ 1000) — the number of starting city, finishing city and the number of possible car changes in i-th round, correspondingly.

For each round you should print the minimum required time to complete the round in a single line.

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.

import scala.math

object CF119Div1B {
  val INF = 1 << 28

  def main(args: Array[String]): Unit = {
    val (n, m, r) = readThreeInts()
    val costMatrices = Array.ofDim[Int](m, n, n)  // Type, Start, End
    for (t <- 0 until m) {
      for (i <- 0 until n) {
        val lineValues = readIntArray()
        for (j <- 0 until n) {
          costMatrices(t)(i)(j) = lineValues(j)
        }
      }

      // FW
      for (p <- 0 until n) {
        for (i <- 0 until n) {
          for (j <- 0 until n) {
            costMatrices(t)(i)(j) = math.min(
              costMatrices(t)(i)(p) + costMatrices(t)(p)(j),
              costMatrices(t)(i)(j))
          }
        }
      }
    }

    // Construct SM
    val superMatrices = Array.ofDim[Int](n, n, n)  // # Change, Start, End
    for (k <- 0 until n) {
      for (i <- 0 until n) {
        for (j <- 0 until n) {
          superMatrices(k)(i)(j) = INF
        }
      }
    }
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        for (t <- 0 until m) {
          superMatrices(0)(i)(j) = math.min(costMatrices(t)(i)(j), superMatrices(0)(i)(j))
        }
      }
    }
    for (k <- 1 until n) {
      for (i <- 0 until n) {
        for (j <- 0 until n) {
          for (m <- 0 until n) {
            superMatrices(k)(i)(j) = math.min(
              superMatrices(k - 1)(i)(m) + superMatrices(0)(m)(j),
              superMatrices(k)(i)(j))
          }
        }
      }
    }

//    for (k <- 0 until  n) {
//      for (i <- 0 until n) {
//        println(superMatrices(k)(i).toList)
//      }
//      println()
//    }

    for (i <- 0 until r) {
      val (sPlusOne, tPlusOne, k) = readThreeInts()
      val s = sPlusOne - 1
      val t = tPlusOne - 1
      println(superMatrices(math.min(k, n - 1))(s)(t))
    }
  }

  def readThreeInts(): (Int, Int, Int) = {
    val line = readLine()
    val words = line.split(" ")
    return (words(0).toInt, words(1).toInt, words(2).toInt)
  }

  def readIntArray(): Array[Int] = {
    val line = readLine()
    val words = line.split(" ")
    val n = words.length
    val values = new Array[Int](n)
    for (i <- 0 until n) {
      values(i) = words(i).toInt
    }
    values
  }
}

import scala.math

object CF119Div1B {
  val INF = 1 << 28

  def main(args: Array[String]): Unit = {
    val (n, m, r) = readThreeInts()
    val costMatrices = Array.ofDim[Int](m, n, n)  // Type, Start, End
    for (t <- 0 until m) {
      for (i <- 0 until n) {
        val lineValues = readIntArray()
        for (j <- 0 until n) {
          costMatrices(t)(i)(j) = lineValues(j)
        }
      }

      // FW
      for (p <- 0 until n) {
        for (i <- 0 until n) {
          for (j <- 0 until n) {
            costMatrices(t)(i)(j) = math.min(
              costMatrices(t)(i)(p) + costMatrices(t)(p)(j),
              costMatrices(t)(i)(j))
          }
        }
      }
    }

    // Construct SM
    val superMatrices = Array.ofDim[Int](n, n, n)  // # Change, Start, End
    for (k <- 0 until n) {
      for (i <- 0 until n) {
        for (j <- 0 until n) {
          superMatrices(k)(i)(j) = INF
        }
      }
    }
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        for (t <- 0 until m) {
          superMatrices(0)(i)(j) = math.min(costMatrices(t)(i)(j), superMatrices(0)(i)(j))
        }
      }
    }
    for (k <- 1 until n) {
      for (i <- 0 until n) {
        for (j <- 0 until n) {
          for (m <- 0 until n) {
            superMatrices(k)(i)(j) = math.min(
              superMatrices(k - 1)(i)(m) + superMatrices(0)(m)(j),
              superMatrices(k)(i)(j))
          }
        }
      }
    }

//    for (k <- 0 until  n) {
//      for (i <- 0 until n) {
//        println(superMatrices(k)(i).toList)
//      }
//      println()
//    }

    for (i <- 0 until r) {
      val (sPlusOne, tPlusOne, k) = readThreeInts()
      val s = sPlusOne - 1
      val t = tPlusOne - 1
      println(superMatrices(math.max(k, n - 1))(s)(t))
    }
  }

  def readThreeInts(): (Int, Int, Int) = {
    val line = readLine()
    val words = line.split(" ")
    return (words(0).toInt, words(1).toInt, words(2).toInt)
  }

  def readIntArray(): Array[Int] = {
    val line = readLine()
    val words = line.split(" ")
    val n = words.length
    val values = new Array[Int](n)
    for (i <- 0 until n) {
      values(i) = words(i).toInt
    }
    values
  }
}


A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-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 «Flatville». The customer wants his future house to be on the Оx-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 «Flatville». Would you help him find the amount of possible positions of the new house?

The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).

Output the amount of possible positions of the new house.

NoteIt is possible for the x-coordinate of the new house to have non-integer value.

import java.util.Scanner

object Houses extends App {

  var result = 0
  val s = new Scanner(System.in)
  val n = s.nextInt()
  val t = s.nextInt() * 2
  val arr = Array.ofDim[Int](40000)
  (0 until n).foreach { _ =>
     val x = (s.nextInt() * 2) + 5000
     val a = s.nextInt() * 2
    ((x - a / 2) until x + (a / 2)).foreach { m =>
      arr(m) = 1
    }
  }
  var i = 0;
  while (arr(i) == 0) {
    i += 1
  }
  while (i < arr.length) {
    val start = i
    while (i < arr.length && arr(i) == 0) {
      i += 1
    }
    val end = i
    val dist = end - start
    if (t < dist) {
      result += 2
    } else if (t == dist) {
      result += 1
    }
    i += 1
  }

  //result += 2
  println(result)

}


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.

The first lines contains one integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of locks.  The second lines contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$1 \le v_i \le 10^9$$$)) — volumes of the locks.  The third line contains one integer $$$q$$$ ($$$1 \le q \le 200\,000$$$) — the number of queries.  Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \le t_j \le 10^9$$$) — the number of seconds you have to fill all the locks in the query $$$j$$$.

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$$$.

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$$$.

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt).map(_.toLong).toList
  val m: Long = v.sum
  var j: Long = 0
  var p: Long = 0
  var co = 0
  val vv = scala.collection.mutable.ListBuffer.empty[Long]
  for (i <- v) {
    co += 1
    j += i
    p = max(p, (j.toDouble / co).ceil.toLong)
    vv += max(p, (m.toDouble / co).ceil.toLong)
  }
  val wwww = vv.toList.toArray
  val k = readInt()
  for (i <- 1 to k) {
    val l = readInt()
    if (wwww.last > l){
      println(-1)
    }
    else if (wwww.head <= l){
      println(1)
    }
    else {
      var a = 0
      var b = wwww.length - 1
      while ( (b - a) > 1) {
        val qqqq = (a + b) / 2
        if (wwww(qqqq) <= l) {
          b = qqqq
        }
        else {
          a = qqqq
        }
      }
      println(b+1)
    }
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt).toList
  val m: Long = v.sum
  var j: Long = 0
  var p: Long = 0
  val vv = scala.collection.mutable.ListBuffer.empty[Long]
  for (i <- v.indices) {
    j+= v(i).toLong
    p = max(p, (j / (i+1)) + min(1,j % (i+1)))
    vv += max(p, (m / (i+1)) +min(1,m %(i+1)))
  }
  val wwww = vv.toList
  val k = readInt()
  for (i <- 1 to k) {
    val l = readInt()
    if (wwww.last > l){
      println(-1)
    }
    else if (wwww.head <= l){
      println(1)
    }
    else {
      var a = 0
      var b = wwww.length - 1
      while ( (b - a) > 1) {
        if (wwww((a + b) / 2) <= l) {
          b = (a + b) / 2
        }
        else {
          a = (a + b) / 2
        }
      }
      println(b+1)
    }
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt).toList
  val m: Long = v.sum
  var j: Long = 0
  var p: Long = 0
  val vv = scala.collection.mutable.ListBuffer.empty[Long]
  for (i <- v.indices) {
    j+= v(i)
    p = max(p, (j / (i+1)) + min(1,j % (i+1)))
    vv += max(p, (m / (i+1)) +min(1,m %(i+1))).toLong
  }
  val wwww = vv.toList
  val k = readInt()
  for (i <- 1 to k) {
    val l = readInt()
    if (wwww.last > l){
      println(-1)
    }
    else if (wwww.head <= l){
      println(1)
    }
    else {
      var a = 0
      var b = wwww.length - 1
      while ( (b - a) > 1) {
        if (wwww((a + b) / 2) <= l) {
          b = (a + b) / 2
        }
        else {
          a = (a + b) / 2
        }
      }
      println(b+1)
    }
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt).toList
  val m = v.sum
  var j: Long = 0
  var d = 0
  var p: Long = 0
  val vv = scala.collection.mutable.ListBuffer.empty[Long]
  for (i <- v.indices) {
    j+= v(i)
    p = max(p, (j / (i+1)) + min(1,j % (i+1)))
    vv += max(p, (m / (i+1)) +min(1,m %(i+1)))
  }
  val wwww = vv.toList
  val k = readInt()
  for (i <- 1 to k) {
    val l = readInt()
    if (wwww.last > l){
      println(-1)
    }
    else if (wwww.head <= l){
      println(1)
    }
    else {
      var a = 0
      var b = wwww.length - 1
      while ( (b - a) > 1) {
        if (wwww((a + b) / 2) <= l) {
          b = (a + b) / 2
        }
        else {
          a = (a + b) / 2
        }
      }
      println(b+1)
    }
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val k = readInt()
  for (i <- 1 to k) {
    val l = readInt()
    var a = true
    var b: Long = 0
    var j = 0
    for (s <- v) {
      j+=1
      b +=s
      if (((b / l) + min(1, b % l)) > j) {
        a = false
      }
    }
    if (a==true){
      println(b)
    }
    else{
      println(-1)
    }

  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Int]
    for (t <- vvv) {
      ss += ((t / s) + min(1,t % s))
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.last)
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Byte]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j.toByte
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Byte]
    for (t <- vvv) {
      ss += ((t / s) + min(1,t % s)).toByte
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.max)
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Short]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j.toShort
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Short]
    for (t <- vvv) {
      ss += ((t / s) + min(1,t % s)).toShort
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.max)
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Long]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Long]
    for (t <- vvv) {
      ss += (t / s) + min(1,t % s)
    }
    val sss = ss.toList
    println(sss)
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.max)
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Long]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Long]
    for (t <- vvv) {
      ss += (t / s) + min(1,t % s)
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.max)
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Int]
    var ooo = 0
    for (t <- vvv) {
      val eee = max(ooo,(t / s) + min(1,t % s))
      ss += eee
      ooo = eee
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.max)
  }
}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Int]
    for (t <- vvv) {
      ss += (t / s) + min(1,t % s)
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.max)
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer

  val a = List(5,1,2,3,4)
  print(a.reduceLeft((c,b) => max(c,b) ), a.reduceLeft((c,b) => max(c,b) ), a.reduce((c,b) => max(c,b) ) )

}

object prob extends App {
  import scala.io.StdIn
  import scala.math.{max,min}
  import scala.List

  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val vv = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (i <- v) {
    j +=i
    vv += j
  }
  val vvv = vv.toList
  val k = readInt()
  for (i <- 1 to  k) {
    val s = readInt()
    val ss = scala.collection.mutable.ListBuffer.empty[Int]
    for (t <- vvv) {
      ss += (t / s) + min(1,t % s)
    }
    val sss = ss.toList
    var it = true
    for (t <- 0 until sss.length) {
      if (sss(t) > t+1) {
        it = false
      }
    }
    if (!it) {
      println(-1)
    }
    else println(sss.reduce((a,b) => max(a,b)))
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer
  def find(t:Long,b:List[Long]): Long = {
    val bi = scala.collection.mutable.ListBuffer.empty[Long]
    for (i <- b) {
      val a = if ((i % t) == 0) i / t else {(i / t) + 1}
      bi += a
    }
    val bj = bi.toList
    val r = bj.reduceLeft((a,b) => if (a>b) a else b )
    var ti = true
    for (i <- 0 until bj.length) {
      if (bj(i) > i+1) {
        ti = false
      }
    }
    if (ti)
      r
    else
      -1
  }
  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val b = scala.collection.mutable.ListBuffer.empty[Long]
  var j = 0
  for (l <- v) {
    j +=l
    b += j
  }
  val b1 = b.toList
  val k = readInt()
  for (i <- 1 to k){
    val qer = readInt()
    println(find(qer,b1))
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer
  def find(t:Int,b:List[Int]): Int = {
    val bi = scala.collection.mutable.ListBuffer.empty[Int]
    for (i <- b) {
      val a = if ((i % t) == 0) i / t else {(i / t) + 1}
      bi += a
    }
    val bj = bi.toList
    val r = bj.reduceLeft((a,b) => if (a>b) a else b )
    var ti = true
    for (i <- 0 until bj.length) {
      if (bj(i) > i+1) {
        ti = false
      }
    }
    if (ti)
      r
    else
      -1
  }
  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val b = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (l <- v) {
    j +=l
    b += j
  }
  val b1 = b.toList
  val k = readInt()
  for (i <- 1 to k){
    val qer = readInt()
    println(find(qer,b1))
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer
  def find(t:Int,b:List[Int]): Int = {
    val bi = scala.collection.mutable.ListBuffer.empty[Int]
    for (i <- b) {
      val a = if ((i % t) == 0) i / t else {(i / t) + 1}
      bi += a
    }
    val bj = bi.toList
    val r = bj.reduceLeft((a,b) => if (a>b) a else b )
    var ti = true
    for (i <- 0 until min(r,bj.length)) {
      if (bj(i) > i+1) {
        ti = false
      }
    }
    if (ti)
      r
    else
      -1
  }
  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val b = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (l <- v) {
    j +=l
    b += j
  }
  val b1 = b.toList
  val k = readInt()
  for (i <- 1 to k){
    val qer = readInt()
    println(find(qer,b1))
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max,min}
  import scala.List
  import scala.collection.mutable.ListBuffer
  def find(t:Int,b:List[Int]): Int = {
    val bi = scala.collection.mutable.ListBuffer.empty[Int]
    for (i <- b) {
      val a = if ((i % t) == 0) i / t else {(i / t) + 1}
      bi += a
    }
    val bj = bi.toList
    val r = bj.reduceLeft((a,b) => if (a>b) a else b )
    var ti = true
    for (i <- 0 until min(r,bj.length)) {
      if (bj(i) > i+1) {
        ti = false
      }
    }
    if (ti)
      r
    else
      -1
  }
  val n = readInt()
  val v = readLine.split(" ").map(_.toInt)
  val b = scala.collection.mutable.ListBuffer.empty[Int]
  var j = 0
  for (l <- v) {
    j +=l
    b += j
  }
  val b1 = b.toList
  val k = readInt()
  for (i <- 1 to k){
    val k = readInt()
    println(find(k,b1))
  }
}


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.

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$$$) — 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$$$) — 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$$$.

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.

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt)

    println(layer(as.reverse, 0, List.empty).map(x => if (x) 1 else 0).reverse.mkString(" "))

    @tailrec
    def layer(as: List[Int], a0: Int, ds: List[Boolean]): List[Boolean] = as match {
          case x :: xs => {
            val x0 = Math.max(a0 - 1, x)
            val d = if (x0 > 0) true else false
            layer(xs, x0, d:: ds)
          }
          case _ => ds.reverse
    }
  }
}

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toArray.map(x => x.toInt)

    println(layer_iterate(as).map(x => if (x) 1 else 0).mkString(" "))

    def layer_iterate(as: Array[Int]): Array[Boolean] = {
      var arr: Array[Boolean] = Array.fill(as.length)(false)
      var a = as.last
      if (a > 0) {
        arr(as.length - 1) = true
      }
      for (i <- (as.length - 2 to 0 by -1)) {
        val a_i = as(i)
        a = Math.max(a - 1, a_i)
        if (a > 0) {
          arr(i) = true
        }
      }
      arr
    }
  }
}

object B {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)
      val res = Array.ofDim[Int](n)

      var drenchUntil = n
      for (i <- as.indices.reverse) {
        val d = i - as(i)
        if (d < drenchUntil) drenchUntil = d
        if (i > drenchUntil) res(i) = 1
      }

      out.println(res.mkString(" "))
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}